# acde: 模块

每个模块同时有命名导出和默认导出:

```js
import { fs } from 'acde:fs'
import fs from 'acde:fs'
```

类型在 `@dopame/acde-api`: `@dopame/acde-api/app` 声明应用能导入的模块, `@dopame/acde-api/shell` 再加上 shell 模块, 包的根声明全部. 能力怎么申请、怎么批准见 [系统能力](https://docs.dopame.ai/zh/guide/capabilities.md).

谁能导入什么. 「应用」指自己单独一个包的应用; 「系统应用」随桌面的包一起发 (桌面配置的 `apps`). 格子里的名字是应用必须声明的能力:

| 模块 | 应用 | 系统应用 | 桌面页面 |
| --- | --- | --- | --- |
| `acde:window` | ✓ | ✓ | |
| `acde:capabilities` | ✓ | ✓ | ✓ |
| `acde:apps` | ✓ | ✓ | ✓ |
| `acde:open` | ✓ (打开应用要 `open`) | ✓ (同样) | ✓ |
| `acde:fs` | `fs` | `fs` | ✓ |
| `acde:terminal` | `terminal` | `terminal` | ✓ |
| `acde:network` | `network` | `network` | ✓ |
| `acde:system` | `system` | `system` | ✓ |
| `acde:bluetooth` | `bluetooth` | `bluetooth` | ✓ |
| `acde:audio` | `audio` | `audio` | ✓ |
| `acde:devices` | `devices` | `devices` | ✓ |
| `acde:power` | `power` | `power` | ✓ |
| `acde:input` | `input` | `input` | ✓ |
| `acde:display` | `display` | `display` | ✓ |
| `acde:office` | `office` | `office` | ✓ |
| `acde:openPath` `acde:handlers` | `openFiles` | `openFiles` | ✓ |
| `acde:launch` | `launch` 或 `slots` | `launch` 或 `slots` | ✓ |
| `acde:windows` `acde:packages` `acde:session` `acde:desktops` `acde:inspect` `acde:desktop` `acde:setDefault` `acde:permissions` (shell 模块) | | 模块的名字: `"windows": true` | ✓ |
| `acde:<服务>` | `services` 里的服务名 | 同样 | ✓ |

平台上没有的模块, 在那里谁都拿不到 (见 [平台支持](https://docs.dopame.ai/zh/reference/platforms.md)). 不允许的导入以 `AcdeError` 失败 (`code: 'forbidden'`, `status: 403`, `module` 是去掉 `acde:` 的名字), 消息里写明缺的是哪条声明, 比如 `acde:terminal needs "terminal" in the capabilities of Notes`; 提供这个模块的服务停了时, 代码是 `service_not_running`, 状态是 503. 见 [错误](#错误). 桌面服务不能导入 `acde:` 模块; 桌面授予了外壳模块的服务从 `ctx.import()` 拿到它们; 见 [服务接口](https://docs.dopame.ai/zh/reference/service.md).

事件用 `on(type, handler)` 订阅, 返回退订函数. 遇到模块没有的事件类型, `on()` 抛 `TypeError`, 比如 `acde:window has no nosuch event (activate, deactivate, …)`. `acde:terminal` 改用回调 (`subscribe`); `acde:network` 有 `on('changed')`, 也可以用 `watch` 传回调.

## 错误

系统模块 (`acde:network`、`acde:system`、`acde:bluetooth`、`acde:audio`、`acde:devices`、`acde:power`、`acde:input`、`acde:display`) 失败时只有一种错误, 不管是方法同步抛出还是它的 Promise reject: `name === 'AcdeError'` 的 `Error`, 带 `status`、`code` 和 `module` (去掉 `acde:` 的模块名). 原因放在 `cause` 里, 原因自己有代码时放在可选的 `reason` 里. 类型是 `@dopame/acde-api` 里的 `AcdeError` 和 `AcdeErrorCode`; 用 `error.name === 'AcdeError'` 判断这种错误. 代码有:

| `code` | `status` | 什么时候 |
| --- | --- | --- |
| `bad_request` | 400 | 参数不对, 比如主机名、时区、电源设置、亮度或设备 id |
| `forbidden` | 403 | 应用没被给予这个模块或这个调用 (不在它的能力里) |
| `unsupported` | 501 | 这个运行时或平台做不了 |
| `service_not_running` | 503 | 它需要的系统服务或总线不在 (NetworkManager、BlueZ、UPower、fcitx5 之类) |
| `failed` | 500 | 其他情况 |

```js
try {
  await network.connect('Home', 'secret')
} catch (error) {
  if (error.name === 'AcdeError' && error.code === 'service_not_running') showOffline()
  else throw error
}
```

导入应用没被给予的模块, 以同样的错误失败, `code: 'forbidden'` (见上文).

## acde:window

```ts
interface AcdeWindow {
  readonly id: number
  readonly state: WindowState
  readonly output: WindowOutput
  readonly hostControls: boolean
  readonly minimizable: boolean
  readonly host: WindowHost
  mount(app: WindowApp): void
  setTitle(title: string): void
  setMenus(menus: readonly AppMenu[]): void
  close(): Promise<boolean>
  minimize(): Promise<void>
  requestAttention(): Promise<void>
  requestState(state: WindowState): void
  requestMode(mode: WindowMode): void
  setGrabHint(rect: WindowRect, edges?: readonly ('top' | 'bottom' | 'left' | 'right')[]): void
  setBackdrop(rect: WindowRect | null, effect?: { radius?: number; blur?: number; saturate?: number; brightness?: number }): void
  requestActivate(): void
  requestGrab(kind: 'pointer' | 'keyboard'): void
  releaseGrab(kind: 'pointer' | 'keyboard'): void
  shortcut(combo: string): Promise<void>
  unshortcut(combo: string): Promise<void>
  on(name: 'beforeclose', handler: () => boolean | void | Promise<boolean | void>): () => boolean
  on<R extends AppRequest = AppRequest>(name: 'request', handler: (request: SystemRequest | R) => void): () => boolean
  on(name: 'activate' | 'deactivate', handler: () => void): () => boolean
  on(name: 'state', handler: (event: { readonly state: WindowState; readonly previous: WindowState }) => void): () => boolean
  on(name: 'output', handler: (output: WindowOutput) => void): () => boolean
  on(name: 'hostcontrols', handler: (hostControls: boolean) => void): () => boolean
  on(name: 'minimizable', handler: (minimizable: boolean) => void): () => boolean
  on(name: 'shortcut', handler: (event: ShortcutEvent) => void): () => boolean
  on(name: 'grab', handler: (event: { readonly kind: 'pointer' | 'keyboard'; readonly granted: boolean }) => void): () => boolean
  on(name: 'grablost', handler: (event: { readonly kind: 'lost'; readonly reason: 'esc' | 'other_window' | 'focus_lost' | 'denied' }) => void): () => boolean
  on(name: 'suspend' | 'resume', handler: () => void): () => boolean
}

type WindowState = 'normal' | 'minimized' | 'filled' | 'fullscreen'
type WindowMode = 'free' | 'fixed' | 'pinned'

interface WindowRect { x: number; y: number; width: number; height: number }
interface WindowOutput { width: number; height: number; scale: number; workArea: WindowRect }

interface ShortcutEvent { type: 'shortcut'; window: number; key: string; title: 'session' | 'desktop' | 'app' }

interface AppMenu {
  id: string
  label: string
  items: ({ type: 'separator' } | AppMenuItem)[]
}
interface AppMenuItem {
  id: string
  label: string
  shortcut?: string
  checked?: boolean
  disabled?: boolean
  onSelect?(): void | Promise<void>
}

interface WindowApp {
  mount(element: Element, host: WindowHost): () => void
}
interface WindowHost {
  setTitle(title: string): void
  setMenus(menus: readonly AppMenu[]): void
}
```

- 全屏是一种状态: `requestState('fullscreen')`. `requestMode('fullscreen')` 抛 `TypeError`, 不认识的状态也一样. `requestState` 没有结果, 看 `state` 事件. 见 [窗口状态](https://docs.dopame.ai/zh/guide/window.md#窗口状态).
- `close()` 关掉窗口, 不问 `beforeclose`.
- 窗口不能最小化时 (`minimizable` 是 `false`), `minimize()` 以 `status: 409`、`code: 'unavailable'` reject: 只跑一个应用的会话, 在 macOS 上和 headless 时, 应用的窗口报的是 `window 1048576 cannot be minimized: it fills the host window, which only the host window's own controls minimize here`. 那里 `requestState('minimized')` 什么都不变.
- `suspend` 和 `resume` 有声明, 但运行时现在还不发.
- 坐标是页面 (内容区) 的逻辑像素. 快捷键组合写成 `ctrl+alt+t`: 键是 xkb keysym 名, 也就是 X11 和 Wayland 用的键名 (`t`、`return`、`escape`、`f5`、`space`, 不分大小写), Shift 写进组合.

## acde:capabilities

```ts
interface AcdeCapabilities {
  readonly level: number
  readonly platform: 'linux' | 'win32' | 'darwin'
  readonly mode: 'session' | 'desktop' | 'standalone'
  readonly window: { readonly backdrop: 'full' | 'approximated' | 'unsupported' }
  get(name: string): CapabilityStatus
  list(): CapabilityStatus[]
  request(name: string): Promise<CapabilityStatus>
}

interface CapabilityStatus {
  name: string
  kind: 'system' | 'service'
  state: 'available' | 'not-asked' | 'asking' | 'not-declared' | 'unsupported' | 'service-not-running' | 'shell-only' | 'denied'
  reason: string
  optional: boolean
}
```

`level` 是契约级别 (1). `request(name)` 就一项需要批准的能力询问用户, 用户回答后以它的状态 resolve; 别的名字立刻 resolve. 需要批准的能力只有在用户允许之后才是 `available`: 提示之前是 `not-asked`, 提示在等的时候是 `asking`, 被拒绝或批准被收回之后是 `denied`. 被批准拦下的调用失败, 带 `status: 403`、`capability`, `code` 是 `not_asked`、`asking`、`denied` 之一. 名字可以是能力名、共享位置的 `fs.<位置>` (`fs.downloads`)、服务名和 `notifications` (标准的 `Notification` 接口: `available`, 在这种运行方式没有通知的地方是 `unsupported`). 见 [系统能力](https://docs.dopame.ai/zh/guide/capabilities.md#acdecapabilities).

## acde:fs

```ts
interface AcdeFs {
  roots(): Promise<FinderRoot[]>
  list(root: string, path?: string, hidden?: boolean): Promise<{ root: FinderRoot; path: string; entries: FinderEntry[]; truncated: boolean; skipped?: number }>
  stat(root: string, path: string): Promise<FinderEntry & { path: string }>
  readText(root: string, path: string): Promise<{ text: string; modifiedMs: number; size: number; version: string }>
  readBytes(root: string, path: string): Promise<{ data: Uint8Array; modifiedMs: number; size: number; version: string }>
  readRange(root: string, path: string, offset: number, length: number, options?: { ifVersion?: string }): Promise<{
    data: Uint8Array; offset: number; size: number; modifiedMs: number; version: string
  }>
  writeFile(root: string, path: string, data: string | Uint8Array, options?: {
    create?: 'always' | 'new' | 'never'
    ifVersion?: string
    ifModifiedMs?: number
    mkdirs?: boolean
  }): Promise<FinderEntry>
  openWrite(root: string, path: string, options?: {
    keepExistingData?: boolean
    create?: 'always' | 'new' | 'never'
    ifVersion?: string
    mkdirs?: boolean
  }): Promise<{ id: string; size: number }>
  writeChunk(id: string, offset: number, data: string | Uint8Array): Promise<void>
  truncateWrite(id: string, size: number): Promise<void>
  commitWrite(id: string): Promise<FinderEntry>
  abortWrite(id: string): Promise<void>
  mkdir(root: string, path: string, options?: { recursive?: boolean }): Promise<FinderEntry>
  rename(root: string, from: string, to: string): Promise<FinderEntry>
  delete(root: string, path: string): Promise<{ status: 'deleted'; path: string }>
  copy(fromRoot: string, fromPath: string, toRoot: string, toDir: string): Promise<FinderEntry & { path: string }>
  preview(root: string, path: string): Promise<FinderPreview>
  download(root: string, path: string): Promise<{ name: string; contentType: string; data: Uint8Array }>
  revoke(root: string): Promise<void>
  locate(path: string): Promise<{ root: string; path: string }>
  openPath(root: string, path: string): Promise<{ root: string; path: string; file: string }>
}

interface FinderRoot {
  id: string
  label: string
  source: 'private' | 'place' | 'granted' | 'desktop' | 'downloads' | 'default'
  place?: 'desktop' | 'documents' | 'downloads' | 'music' | 'pictures' | 'videos'
  path?: string
  mode: 'writable' | 'read_only' | 'unavailable'
  reason: string | null
  exists: boolean
}

interface FinderEntry {
  name: string
  kind: 'directory' | 'file' | 'symlink' | 'other'
  size: number
  modifiedMs: number
  target?: string
  version?: string
  inPlace?: true
}

interface FinderPreview {
  path: string
  name: string
  size: number
  modifiedMs: number
  kind: 'text' | 'image' | 'binary' | 'too_large'
  content?: string
  truncated?: boolean
}
```

- `root` 是 `roots()` 里某一项的 `id`: `private`、共享位置的名字, 或选中的文件夹的 `folder-…`; 永远不是路径. 应用的根的 `source` 是 `private`、`place` (带 `place`) 或 `granted`, 没有 `path`.
- 只有列了共享位置的系统应用和桌面页面才有 `path`. `locate` 和 `openPath` 也只对它们有效; 在别的应用里以 `EACCES` reject.
- 桌面页面的根是按路径给的文件夹 (`source` 是 `desktop`、`downloads`、`default` 或 `granted`), 它们的 `id` 就是路径.
- `list` 不含隐藏项, 除非 `hidden` 是 `true`; `skipped` 是名字不是合法 Unicode 而被跳过的项数.
- `copy` 把一个根里的文件或文件夹复制进另一个根的文件夹 `toDir`; 名字被占了就加一个编号 (`todo 2.md`), `path` 是副本在 `toRoot` 里的位置.
- `revoke` 交还用户选中的一个文件夹.
- `version` 是一个不透明的字符串, 代表文件的一个状态; 把它作为 `ifVersion` 传进去, 文件在那之后变了的话, 写 (或 `readRange`) 以 `ECONFLICT` 失败. `inPlace` 标出一次没能经过临时文件的写. 见 [安全地写](https://docs.dopame.ai/zh/guide/files.md#安全地写).
- `openWrite` 开始一次分块的写: 在任意偏移处 `writeChunk`、`truncateWrite`, 然后 `commitWrite` 把文件放到位 (或 `abortWrite`). 放着 10 分钟不管的写会被放弃. 见 [大文件](https://docs.dopame.ai/zh/guide/files.md#大文件).
- 上限: `readText` / `readBytes` / `writeFile` 64 MiB; `readRange` / `writeChunk` 每次调用 16 MiB; `list` 5000 项 (`truncated`); `preview` 的文字 256 KiB.
- `download` 回的 `contentType` 是系统按文件名认出的类型: `note.md` 是 `text/markdown`, `shot.png` 是 `image/png`, 名字认不出类型的 (`data.xyz`) 是 `application/octet-stream`. 类型来自系统, 见 [文件和链接](https://docs.dopame.ai/zh/guide/open.md#文件和链接) 里的说明.
- 错误带 `code` 和 `status`, 见 [文件与文件夹](https://docs.dopame.ai/zh/guide/files.md#错误).

## acde:open

```ts
interface AcdeOpen {
  (app: string, request?: null, options?: OpenWindowOptions): Promise<{ window: number }>
  <R extends AppRequest>(app: string, request: R, options?: OpenWindowOptions): Promise<{ window: number }>
  (app: string, request: SystemRequest): Promise<Opened>
  (request: SystemRequest): Promise<Opened>
}

type AppRequest<K extends string = string, Fields extends object = Record<never, never>> = { readonly kind: K } & { readonly [P in keyof Fields]: Fields[P] }

type SystemRequest =
  | { kind: 'open-file'; handle?: FileSystemFileHandle | FileSystemDirectoryHandle; url?: string; root?: string; path?: string; file?: string | null }
  | { kind: 'open-link'; url: string }

interface OpenWindowOptions { parent?: number; modal?: boolean }
interface Opened { kind: 'acdev' | 'native'; id: string; window?: number }
```

- `open(app)` 和 `open(app, request)` 需要 `open` 能力允许 `app`. 发给应用的请求必须有 `kind`, 而且是目标在自己的 `requests` 里列了的 (400 `untyped_request`、409 `not_accepted`).
- `open(request)` 带系统请求而不带应用时需要 `openFiles`: 由系统挑应用. 带应用时, 目标必须声明了这个文件的类型 (`mimeTypes`) 或这个链接的 scheme (`schemes`).
- 接收的应用拿到的文件是 `{ kind: 'open-file', handle }`; 列了共享位置的系统应用还会拿到 `url`. 发文件用 `handle` (这个页面从选择器、拖放或请求里拿到的句柄), 或者在调用方知道路径的地方用 `url`.
- 接收方用 `AppRequest<K, Fields>` 给自己的请求写类型: `type ShowImage = AppRequest<'show-image', { image: string }>`, 然后 `self.on<ShowImage>('request', …)` 按 `kind` 收窄. `SystemRequest` 和 `AppRequest` 也在 `acde:window` 的 `request` 事件里 (见上).

见 [打开应用](https://docs.dopame.ai/zh/guide/open.md).

## acde:apps

```ts
interface AcdeAppList {
  list(): Promise<DesktopApp[]>
  open: AcdeOpen
  on(type: 'changed', handler: (event: { type: 'appschanged'; apps: readonly DesktopApp[] }) => void): () => boolean
}

interface DesktopApp { id: string; label: string; icon: string; script: string }
```

`list()` 给出能在这里跑的应用; `open` 就是 `acde:open` 的那个函数. 列表变了, `changed` 就带着新的列表触发. 摄像头或麦克风被拒绝时, 应用仍留在列表里. 安装包和原生程序在 [`acde:packages`](#acdepackages) 里.

## acde:openPath / acde:handlers / acde:setDefault

```ts
function openPath(path: string, options?: { app?: string; select?: boolean }): Promise<{ kind: 'acdev' | 'native'; id: string; window?: number }>
function handlers(path: string): Promise<{ mime: string; association: string | null; handlers: OpenHandler[] }>
function setDefault(association: string, handler: string): Promise<string>

interface OpenHandler {
  kind: 'acdev' | 'native'
  id: string
  label: string
  icon: string
  default: boolean
  system?: boolean
}
```

`path` 可以是路径或 URI. `openPath` 和 `handlers` 需要 `openFiles`; 对应用来说, 文件必须在它的某个根里 (404 `outside_roots`). `setDefault` 是 shell 模块. `association` 是记住一次选择时用的键: MIME 类型, 或 Windows 上文件的扩展名 (`.md`); 系统不知道文件的类型时 `mime` 是 `''`. `system` 标出系统自己的默认程序 (Windows).

## acde:launch

需要 `launch` (用 `start`) 或 `slots` (用 `embed`).

```ts
interface AcdeLaunch {
  start(argv: readonly string[], options?: LaunchOptions): Promise<number>
  embed(argv: readonly string[], options?: LaunchOptions): Promise<number>
  close(window: number): Promise<boolean>
  list(): NativeWindow[]
  on<K extends WindowsEventType>(type: K, handler: (event: WindowsEventMap[K]) => void): () => boolean
}

interface LaunchOptions { cwd?: string; env?: Record<string, string> }
```

`start` 运行一个原生程序, `embed` 运行一个嵌在应用自己窗口里的原生程序 (仅 Dopame OS). `close` 关掉应用自己起的窗口; 别的窗口以 403 `forbidden` 拒绝. 事件就是 [`acde:windows`](#acdewindows) 的那些.

## acde:terminal

需要 `terminal`.

```ts
interface AcdeTerminals {
  open(cols: number, rows: number): Promise<{ id: string }>
  subscribe(id: string, callback: (events: TerminalEvent[]) => void): Promise<void>
  input(id: string, data: string): Promise<{ ok: true }>
  resize(id: string, cols: number, rows: number): Promise<{ cols: number; rows: number }>
  close(id: string): Promise<{ closed: string }>
}

type TerminalEvent =
  | { type: 'output'; data: string }
  | { type: 'cwd'; path: string }
  | { type: 'exit'; code: number | null; signal: number | null }
```

## acde:network

仅 Linux (Dopame OS, 或任何有 NetworkManager 的 Linux). 需要 `network`.

```ts
interface AcdeNetwork {
  state(): Promise<NetworkState>
  networks(scan?: boolean): Promise<WifiNetwork[]>
  connect(ssid: string, password?: string): Promise<void>
  activate(iface: string): Promise<void>
  disconnect(iface: string): Promise<void>
  setWifiEnabled(on: boolean): Promise<void>
  on(type: 'changed', handler: (state: NetworkState) => void): () => boolean
  watch(callback: (state: NetworkState) => void): void
}

interface NetworkState {
  wifiEnabled: boolean
  connectivity: 'full' | 'limited' | 'portal' | 'none' | 'unknown'
  primary: 'wifi' | 'ethernet' | string | null
  devices: NetworkDevice[]
}

interface NetworkDevice {
  iface: string
  type: 'wifi' | 'ethernet'
  state: 'connected' | 'connecting' | 'disconnecting' | 'disconnected' | 'unavailable' | 'unmanaged' | 'failed'
  connection: string | null
  ip4: string | null
  ssid?: string
  strength?: number
  carrier?: boolean
  speed?: number
}

interface WifiNetwork {
  ssid: string
  strength: number
  secure: boolean
  band: '2.4GHz' | '5GHz'
  active: boolean
  saved: boolean
}
```

## acde:system

仅 Linux. 需要 `system`. 它的错误是 [`AcdeError`](#错误).

```ts
interface AcdeSystem {
  info(): Promise<SystemInfo>
  storage(): Promise<SystemVolume[]>
  time(): Promise<SystemTime>
  timezones(): Promise<string[]>
  setTimezone(zone: string): Promise<void>
  setNtp(on: boolean): Promise<void>
  setHostname(name: string): Promise<void>
  user(): Promise<SystemUser>
  on(type: 'changed', handler: (change: SystemChange) => void): () => boolean
}
```

这台计算机: `info()` (主机名和其他信息)、`storage()` (它的卷)、`time()` (带 `timezone` 和 `ntp`)、`timezones()`, 设置项 `setTimezone`、`setNtp` 和 `setHostname`, 以及 `user()`. 其中一项变了时, `changed` 给出 `{storage, hostname, timezone, ntp}`, 每次都是完整的一份; 有人在听时每 30 秒查一次, 这个页面设了其中一项之后也马上查一次. 状态的类型在 `@dopame/acde-api` 里.

## acde:bluetooth

仅 Linux. 需要 `bluetooth`. 它的错误是 [`AcdeError`](#错误).

```ts
interface AcdeBluetooth {
  state(): Promise<BluetoothState>
  setPowered(on: boolean): Promise<void>
  setDiscoverable(on: boolean, timeout?: number): Promise<void>
  setName(name: string): Promise<void>
  scan(on: boolean): Promise<void>
  pair(id: string): Promise<void>
  answer(id: string, accept: boolean, pin?: string): Promise<void>
  connect(id: string): Promise<void>
  disconnect(id: string): Promise<void>
  forget(id: string): Promise<void>
  setTrusted(id: string, on: boolean): Promise<void>
  setBlocked(id: string, on: boolean): Promise<void>
  rename(id: string, name: string): Promise<void>
  setOnLogin(mode: 'remember' | 'on' | 'off'): Promise<void>
  on(type: 'changed', handler: (state: BluetoothState) => void): () => boolean
  on(type: 'pairing', handler: (request: BluetoothPairing) => void): () => boolean
}
```

蓝牙适配器和它的设备 (BlueZ). `changed` 给出完整的 `BluetoothState`; `pairing` 请页面确认一次配对、显示或输入 PIN 或配对码, 或授权一项服务, 页面用 `answer(id, accept, pin?)` 回答. 状态的类型在 `@dopame/acde-api` 里.

## acde:audio

仅 Linux. 需要 `audio`. 它的错误是 [`AcdeError`](#错误).

```ts
interface AcdeAudio {
  state(): Promise<AudioState>
  setDefault(id: string): Promise<void>
  setVolume(id: string, volume: number): Promise<void>
  setMuted(id: string, muted: boolean): Promise<void>
  setBalance(id: string, balance: number): Promise<void>
  setPort(id: string, port: string): Promise<void>
  setProfile(card: string, profile: string): Promise<void>
  moveStream(id: string, device: string | null): Promise<void>
  on(type: 'changed', handler: (state: AudioState) => void): () => boolean
}
```

声卡、输出、输入和正在播放的音频流: 默认设备、音量、静音、平衡、端口和声卡配置, 以及一个音频流在哪个设备上播放. `changed` 给出完整的 `AudioState`. 状态的类型在 `@dopame/acde-api` 里.

## acde:devices

仅 Linux. 需要 `devices`. 它的错误是 [`AcdeError`](#错误).

```ts
interface AcdeDevices {
  state(): Promise<DevicesState>
  mount(id: string): Promise<string>
  unmount(id: string): Promise<void>
  eject(id: string): Promise<void>
  setAutomount(patch: Partial<Pick<Automount, 'onLogin' | 'onAttach' | 'unknown'>>): Promise<void>
  setDeviceAutomount(id: string, patch: Partial<Pick<AutomountDevice, 'login' | 'attach'>>): Promise<void>
  forgetDevice(id: string): Promise<void>
  setDefaultPrinter(id: string): Promise<void>
  pausePrinter(id: string): Promise<void>
  resumePrinter(id: string): Promise<void>
  jobs(printer: string): Promise<PrintJob[]>
  cancelJob(printer: string, job: number): Promise<void>
  on(type: 'changed', handler: (state: DevicesState) => void): () => boolean
  on(type: 'added', handler: (drive: Drive) => void): () => boolean
}
```

驱动器 (U 盘、存储卡、光盘、手机、磁盘: 挂载、卸载、弹出, 以及自动挂载的设置) 和打印机 (默认打印机、暂停、恢复、任务). `changed` 给出完整的 `DevicesState`; 插入一个驱动器时 `added` 给出它. 状态的类型在 `@dopame/acde-api` 里.

## acde:power

仅 Linux. 需要 `power`. 它的错误是 [`AcdeError`](#错误).

```ts
interface AcdePower {
  state(): Promise<PowerState>
  setProfile(profile: PowerProfile): Promise<void>
  configure(patch: PowerSettingsPatch): Promise<void>
  setScreenOff(seconds: number | null): Promise<void>
  setSleep(seconds: number | null): Promise<void>
  suspend(): Promise<void>
  hibernate(): Promise<void>
  setBrightness(value: number): Promise<void>
  setChargeLimit(percent: number | null): Promise<void>
  on(type: 'changed', handler: (state: PowerState) => void): () => boolean
  on(type: 'prompt', handler: (event: PowerPromptEvent) => void): () => boolean
  on(type: 'critical', handler: (event: PowerCriticalEvent) => void): () => boolean
}
```

电池、电源模式、合上盖子、按电源键和空闲时做什么 (接通电源时、用电池时和电量低时)、关屏和睡眠的计时、挂起和休眠、背光, 以及充电上限. `changed` 给出完整的 `PowerState`; `prompt` (`{type: 'prompt'}`) 请页面给出电源选项, `critical` (`{type: 'critical', action, seconds}`) 说明电池电量极低, 以及多少秒后会发生什么. 状态的类型在 `@dopame/acde-api` 里.

## acde:input

仅 Linux. 需要 `input`. 它的错误是 [`AcdeError`](#错误).

```ts
interface AcdeInput {
  state(): Promise<InputState>
  set(patch: InputPatch): Promise<void>
  catalog(): Promise<InputCatalog>
  on(type: 'changed', handler: (state: InputState) => void): () => boolean
}
```

键盘 (型号、布局、选项、Num Lock)、鼠标和触摸板的设置, 以及输入法. `set()` 接受要改的部分; `catalog()` 列出可选的型号、布局、选项和输入法. `changed` 给出完整的 `InputState`. 状态的类型在 `@dopame/acde-api` 里.

## acde:display

仅 Linux. 需要 `display`. 它的错误是 [`AcdeError`](#错误).

```ts
interface AcdeDisplay {
  state(): Promise<DisplayState>
  configure(id: string, patch: DisplayPatch): Promise<void>
  setBrightness(id: string, value: number): Promise<void>
  setNightLight(patch: Partial<NightLight>): Promise<void>
  on(type: 'changed', handler: (state: DisplayState) => void): () => boolean
}
```

显示器 (模式、缩放、旋转等, 用 `configure` 设置)、它们的亮度, 以及夜间模式. `changed` 给出完整的 `DisplayState`. 状态的类型在 `@dopame/acde-api` 里.

## acde:session

shell 模块: 只有桌面页面和它的包里 (能力里写了 `"session": true` 的) 系统应用能导入; 普通应用不能, 即使声明了 `session`.

```ts
interface AcdeSession {
  own(): boolean
  logout(): Promise<void>
  reboot(): Promise<void>
  poweroff(): Promise<void>
  setLanguage(tag: string): Promise<void>
}
```

`own()`: 是不是真正的 Dopame OS 会话 (`acdev dev` 的宿主窗口里是 `false`). `setLanguage` 之后页面收到 `languagechange`.

## acde:desktops

shell 模块.

```ts
interface AcdeDesktops {
  list(): Promise<{ desktops: DesktopInfo[]; current: string }>
  choose(id: string, remember?: boolean): Promise<void>
}

interface DesktopInfo {
  kind: 'acdev' | 'session'
  id: string
  name: string
  description: string | null
  package: string | null
}
```

`kind: 'session'` 是系统里别的 Wayland 会话 (GNOME、KDE ……).

## acde:packages

shell 模块.

```ts
interface AcdePackages {
  refresh(): Promise<DesktopApp[]>
  install(dir: string): Promise<{ id: string; dir: string; apps: DesktopApp[] }>
  natives(): Promise<NativeApp[]>
  runNative(id: string): Promise<number>
  on(type: 'changed', handler: (event: { type: 'appschanged'; apps: readonly DesktopApp[] }) => void): () => boolean
}

interface NativeApp {
  id: string
  name: string
  comment: string | null
  icon: string
  keywords: string[]
  wmClass: string | null
}
```

`natives()` 列出系统里的原生程序 (`.desktop` 文件, 仅 Linux).

## acde:windows

shell 模块: 会话里的每一个窗口.

```ts
interface AcdeWindows {
  on<K extends WindowsEventType>(type: K, handler: (event: WindowsEventMap[K]) => void): () => boolean
  list(): NativeWindow[]
  close(id: number): void
  requestState(id: number, state: WindowState): Promise<void>
  kill(id: number): Promise<boolean>
  focus(id: number): Promise<void>
  hide(id: number): Promise<void>
  show(id: number): Promise<void>
  invokeMenu(id: number, menu: string, item: string): Promise<void>
  stats(): Promise<Record<string, number>>
  animate(id: number, options: {
    opacity?: number; scale?: number; dx?: number; dy?: number
    duration?: number; delay?: number
    easing?: 'linear' | 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out'
  }): Promise<void>
  shortcut(combo: string, scope?: 'session' | 'desktop'): Promise<void>
  unshortcut(combo: string, scope?: 'session' | 'desktop'): Promise<void>
  launch(argv: string[], options?: { cwd?: string; env?: Record<string, string>; slot?: boolean }): number | Promise<number>
}

interface NativeWindow { id: number; appId: string | null; title: string | null; web?: boolean; state: WindowState }
```

`WindowsEventType`: `open` `close` `title` `state` `activate` `minsize` `parent` `menus` `crash` `hang` `responsive` `attention` `ready` `show` `animated`. 每个事件都是 `{ type: 'window<名字>', window: number, … }`:

| 事件 | 额外的字段 |
| --- | --- |
| `open` | `appId`、`title`、`web`、`icon` |
| `title` | `appId`、`title` |
| `state` | `state`、`previous` |
| `minsize` | `width`、`height` |
| `parent` | `parent` |
| `menus` | `menus`: 应用的菜单, 每一项带 `action: boolean`, 没有 `onSelect` |
| `crash` | `reason` |

- 窗口状态的变化由 `state` 报告; 全屏和最小化没有自己的事件. `requestState` 遇到不认识的状态以 `TypeError` reject.
- `close(id)` 会问应用 (`beforeclose`); `kill(id)` 不问, 直接结束窗口.
- 运行时做不了动画的地方, `animate` 可能立刻结束; `animated` 照样触发.
- `list()` 的每一行都带窗口当前的 `state`, `list()` 里有每一个窗口, 在窗口打开之后才启动的系统应用里也一样.
- 应用用 [`acde:launch`](#acdelaunch) 起原生程序, 不用这里的 `launch`.

## acde:desktop

shell 模块.

```ts
interface AcdeDesktop {
  apps(): Promise<{ apps: DesktopApp[] }>
  pin(element: Element, options?: { margin?: number; reserve?: PanelReserve }): PinnedPanel
  setDoubleClick(action: 'fill' | 'minimize' | 'none'): void
  setFrameTheme(theme: FrameTheme | null): void
  on(type: 'notification', handler: (e: NotificationEvent) => void): () => boolean
  on(type: 'download', handler: (e: DownloadEvent) => void): () => boolean
  on(type: 'screenshot', handler: (e: { type: 'screenshot'; path: string; width: number; height: number } | { type: 'screenshot'; path: string; error: string }) => void): () => boolean
  on(type: 'shortcut', handler: (e: ShortcutEvent) => void): () => boolean
  on(type: 'edge', handler: (e: { type: 'screenedge'; edge: 'top' | 'right' | 'bottom' | 'left'; entered: boolean; output: string }) => void): () => boolean
}

interface PanelReserve { edge: 'top' | 'bottom' | 'left' | 'right'; thickness?: number }
interface PinnedPanel {
  update(): void
  unpin(): void
  reserve(reserve: PanelReserve | null): void
}

interface FrameTheme {
  active?: FrameColors
  inactive?: FrameColors
  light?: { active?: FrameColors; inactive?: FrameColors }
  buttonStyle?: 'dots' | 'glyphs'
  buttonSide?: 'left' | 'right'
  titleAlign?: 'center' | 'start'
}
interface FrameColors { background?: string; title?: string; line?: string; buttons?: string }

interface NotificationEvent {
  type: 'notification'
  window: number
  app: string | null
  label: string | null
  title: string
  body: string
  icon: string
  tag: string
}

interface DownloadEvent {
  type: 'download'
  window: number
  app: string | null
  path: string
  name: string
  size: number
}
```

- 指针到达 (`entered: true`) 或离开屏幕的一条边时触发 `edge`, 每条边一次 (在角上是两次); `output` 是屏幕的名字, 在宿主窗口里是 `host`. 它不抢焦点, 给要把藏起来的菜单栏或 Dock 再显示出来的桌面用.
- `light`: 给页面没声明支持深色 (`color-scheme` 里没有 `dark`) 的窗口用的标题栏颜色; 这时 `active` / `inactive` 给声明了支持深色的页面用. 每次 `setFrameTheme` 调用给的都是整套主题; 值不对会抛 `TypeError`, 不认识的键被忽略, 日志里打一条警告.
- 声明了 `"desktop": true` 的系统应用拿到 `apps()`、`setDoubleClick`、`setFrameTheme`, 以及 `notification`、`download` 和 `edge` 事件; `pin`、`screenshot` 和 `shortcut` 只给桌面页面.

见 [桌面](https://docs.dopame.ai/zh/guide/desktop.md#面板).

## acde:permissions

shell 模块: 批准提示, 以及对它们作出的决定.

```ts
interface AcdePermissions {
  pending(): Promise<PermissionPrompt[]>
  answer(id: number, allow: boolean): Promise<void>
  list(app?: string): Promise<PermissionDecision[]>
  revoke(app: string, capability: string): Promise<boolean>
  on(type: 'prompt', handler: (event: PermissionPrompt & { type: 'permissionprompt' }) => void): () => boolean
  on(type: 'answered', handler: (event: { type: 'permissionanswered'; id: number; app: string; capability: string; allowed: boolean }) => void): () => boolean
}

interface PermissionPrompt {
  id: number
  app: string
  label: string
  capability: string
  reason: 'request'
}

interface PermissionDecision {
  app: string
  label: string | null
  capability: string
  decision: 'granted' | 'denied'
  folder?: { label: string; exists: boolean }
}
```

提示的 `capability` 是 `camera`、`microphone` 或 `idleDetection`, 只有这几个能力会问用户; 在决定里还可以是 `fs.folder-…`, 即用户为这个应用选中的文件夹 (带 `folder`). 没有决定时 `revoke` resolve 成 `false`. 每个提示都在第一次使用时提出, `reason: 'request'`. 见 [桌面](https://docs.dopame.ai/zh/guide/desktop.md#摄像头和麦克风提示).

## acde:inspect

shell 模块, 也以 `ctx.inspect` 给桌面服务. 把屏幕变成文字的语义树, 并按 ref 操作; 给 AI agent 用. `acdev inspect` / `acdev act` 和 MCP 用的就是它.

```ts
interface AcdeInspect {
  snapshot(options?: {
    window?: string; ref?: string; all?: boolean; diff?: boolean
    limit?: number; find?: string; tree?: boolean; offscreen?: boolean
  }): Promise<{ text: string; windows: InspectWindow[]; trees: Record<string, InspectNode[]> }>
  act(ref: string, action: InspectAction, arg?: string | number | readonly string[] | null): Promise<{ ok: boolean; text: string }>
  run(steps: readonly { ref: string; action: InspectAction; text?: InspectArg }[]): Promise<{ ok: boolean; text: string }>
  open(name: string): Promise<{ ok: boolean; text: string }>
  query(options: { selector: string; window?: string; ref?: string; limit?: number; attributes?: readonly string[] }): Promise<{ window: string; count: number; nodes: InspectMatch[] }>
}

type InspectAction = 'click' | 'double' | 'right' | 'hover' | 'drag' | 'type' | 'settext' | 'select' | 'key' | 'scroll' | 'focus' | 'close' | 'minimize' | 'restore' | 'fill' | 'fullscreen'
```

窗口 ref 是 `w0` (桌面)、`w1` ……, 元素 ref 是 `w3.12`. 文字形式一行一个节点:

```text
- button "新建文件夹" [pressed] [w1.52]
```

## acde:office

仅 Linux. 办公文档 (文字、表格、演示) 的编辑服务, 给 Dopame 自带的办公应用用; 接口还可能变化.
