@armadra/agent 0.15.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/CHANGELOG.zh-CN.md +36 -0
  3. package/dist/agent/recovery-reminder.d.ts +23 -0
  4. package/dist/agent/recovery-reminder.js +42 -0
  5. package/dist/agent/reminders.d.ts +10 -4
  6. package/dist/agent/reminders.js +59 -19
  7. package/dist/agent/session-plan.js +3 -4
  8. package/dist/agent/session-settings.d.ts +5 -0
  9. package/dist/agent/session-settings.js +15 -2
  10. package/dist/agent/session-subagent.d.ts +5 -0
  11. package/dist/agent/session-subagent.js +65 -12
  12. package/dist/agent/session-tools.d.ts +3 -1
  13. package/dist/agent/session-tools.js +47 -3
  14. package/dist/agent/subagent-background.js +1 -0
  15. package/dist/agent/subagent-fork.js +3 -1
  16. package/dist/agent/subagent-handle.d.ts +22 -0
  17. package/dist/agent/subagent-handle.js +55 -0
  18. package/dist/agent/subagent-lifetime.d.ts +35 -0
  19. package/dist/agent/subagent-lifetime.js +112 -0
  20. package/dist/agent/subagent-registry.d.ts +23 -15
  21. package/dist/agent/subagent-registry.js +68 -81
  22. package/dist/agent/system-prompt.d.ts +8 -0
  23. package/dist/agent/system-prompt.js +4 -0
  24. package/dist/agent/types-w5.d.ts +8 -3
  25. package/dist/agent/types.d.ts +7 -0
  26. package/dist/agents/builtin.d.ts +1 -1
  27. package/dist/agents/builtin.js +3 -2
  28. package/dist/agents/report.d.ts +25 -0
  29. package/dist/agents/report.js +51 -0
  30. package/dist/agents/result.d.ts +9 -1
  31. package/dist/agents/result.js +16 -0
  32. package/dist/agents/task-control.d.ts +12 -0
  33. package/dist/agents/task-record.d.ts +24 -1
  34. package/dist/agents/task-record.js +24 -0
  35. package/dist/bundle/ama.cjs +3144 -1771
  36. package/dist/cli/bootstrap.js +14 -7
  37. package/dist/cli/compose-agents.d.ts +2 -1
  38. package/dist/cli/compose-agents.js +4 -1
  39. package/dist/cli/compose-events.d.ts +18 -3
  40. package/dist/cli/compose-events.js +17 -2
  41. package/dist/cli/compose-session.d.ts +1 -1
  42. package/dist/cli/compose-session.js +8 -16
  43. package/dist/cli/compose.d.ts +8 -0
  44. package/dist/cli/compose.js +25 -1
  45. package/dist/cli/deps.d.ts +12 -0
  46. package/dist/config/json-schema.js +4 -0
  47. package/dist/config/key-docs.js +3 -1
  48. package/dist/config/schema-w5.js +3 -0
  49. package/dist/config/schema.js +12 -1
  50. package/dist/config/settings-registry.js +4 -0
  51. package/dist/config/types-w5.d.ts +2 -0
  52. package/dist/config/types.d.ts +7 -0
  53. package/dist/drivers/acp/types.d.ts +4 -0
  54. package/dist/drivers/runner.js +5 -0
  55. package/dist/drivers/turn.d.ts +7 -0
  56. package/dist/drivers/turn.js +21 -0
  57. package/dist/drivers/types.d.ts +6 -0
  58. package/dist/hooks/dispatcher.d.ts +7 -1
  59. package/dist/hooks/dispatcher.js +28 -1
  60. package/dist/hooks/matcher.d.ts +4 -0
  61. package/dist/hooks/matcher.js +19 -2
  62. package/dist/host/api-impl.d.ts +8 -0
  63. package/dist/host/api-impl.js +10 -0
  64. package/dist/host/resources.d.ts +25 -0
  65. package/dist/host/resources.js +63 -0
  66. package/dist/host/types.d.ts +24 -2
  67. package/dist/host/types.js +9 -2
  68. package/dist/host.d.ts +1 -0
  69. package/dist/host.js +2 -0
  70. package/dist/i18n/catalog.d.ts +26 -0
  71. package/dist/i18n/messages/approval.d.ts +9 -0
  72. package/dist/i18n/messages/approval.js +9 -0
  73. package/dist/i18n/messages/config-keys.d.ts +8 -0
  74. package/dist/i18n/messages/config-keys.js +8 -0
  75. package/dist/i18n/messages/config.d.ts +8 -0
  76. package/dist/i18n/messages/drivers.d.ts +16 -0
  77. package/dist/i18n/messages/drivers.js +16 -0
  78. package/dist/i18n/messages/panels.d.ts +15 -0
  79. package/dist/i18n/messages/panels.js +5 -0
  80. package/dist/i18n/messages/settings.d.ts +6 -0
  81. package/dist/i18n/messages/settings.js +6 -0
  82. package/dist/modes/acp/acp-events.d.ts +3 -0
  83. package/dist/modes/acp/acp-events.js +21 -0
  84. package/dist/modes/interactive/agent-bar.d.ts +7 -2
  85. package/dist/modes/interactive/agent-bar.js +16 -6
  86. package/dist/modes/interactive/approval-ui.d.ts +2 -0
  87. package/dist/modes/interactive/approval-ui.js +4 -1
  88. package/dist/modes/interactive/interactive-mode.js +6 -1
  89. package/dist/modes/interactive/key-dispatch.d.ts +5 -0
  90. package/dist/modes/interactive/key-dispatch.js +28 -4
  91. package/dist/modes/interactive/program-status-ui.d.ts +1 -0
  92. package/dist/modes/interactive/program-status-ui.js +38 -5
  93. package/dist/modes/interactive/session-events.js +13 -1
  94. package/dist/modes/interactive/subagent-view.d.ts +4 -1
  95. package/dist/modes/interactive/subagent-view.js +26 -6
  96. package/dist/modes/interactive/tasks-report.d.ts +4 -1
  97. package/dist/modes/interactive/tasks-report.js +12 -0
  98. package/dist/modes/rpc/commands.d.ts +10 -1
  99. package/dist/modes/rpc/commands.js +19 -1
  100. package/dist/permissions/broker.d.ts +38 -3
  101. package/dist/permissions/broker.js +118 -7
  102. package/dist/permissions/pipeline.d.ts +11 -10
  103. package/dist/permissions/pipeline.js +18 -46
  104. package/dist/permissions/rules.d.ts +21 -4
  105. package/dist/permissions/rules.js +43 -9
  106. package/dist/permissions/session-grants.d.ts +14 -0
  107. package/dist/permissions/session-grants.js +47 -0
  108. package/dist/permissions/types.d.ts +18 -0
  109. package/dist/session/unclean-end.d.ts +47 -0
  110. package/dist/session/unclean-end.js +153 -0
  111. package/dist/tools/background-jobs.d.ts +50 -3
  112. package/dist/tools/background-jobs.js +70 -6
  113. package/dist/tools/bash-jobs.d.ts +26 -0
  114. package/dist/tools/bash-jobs.js +165 -0
  115. package/dist/tools/bash.d.ts +22 -5
  116. package/dist/tools/bash.js +76 -103
  117. package/dist/tools/output-accumulator.d.ts +5 -0
  118. package/dist/tools/output-accumulator.js +9 -0
  119. package/dist/tools/read-lines.d.ts +2 -0
  120. package/dist/tools/read-lines.js +4 -0
  121. package/dist/tools/read-resource.d.ts +24 -0
  122. package/dist/tools/read-resource.js +129 -0
  123. package/dist/tools/read.d.ts +7 -2
  124. package/dist/tools/read.js +16 -5
  125. package/dist/tools/registry.d.ts +5 -2
  126. package/dist/tools/registry.js +8 -3
  127. package/dist/tools/report.d.ts +24 -0
  128. package/dist/tools/report.js +81 -0
  129. package/dist/tools/resource-ref.d.ts +90 -0
  130. package/dist/tools/resource-ref.js +90 -0
  131. package/dist/tools/task-ctl.d.ts +8 -1
  132. package/dist/tools/task-ctl.js +31 -5
  133. package/dist/tools/task.d.ts +2 -0
  134. package/dist/tools/task.js +3 -0
  135. package/dist/tools/timers.d.ts +18 -0
  136. package/dist/tools/timers.js +26 -0
  137. package/dist/tools/types.d.ts +30 -0
  138. package/dist/tools/types.js +2 -0
  139. package/docs/en/guides/permissions.md +14 -0
  140. package/docs/en/guides/tui.md +21 -21
  141. package/docs/en/reference/acp.md +15 -14
  142. package/docs/en/reference/host-api.md +48 -20
  143. package/docs/en/reference/rpc.md +12 -9
  144. package/docs/guides/agents.md +83 -22
  145. package/docs/guides/hooks.md +12 -9
  146. package/docs/guides/permissions.md +14 -0
  147. package/docs/guides/tui.md +21 -21
  148. package/docs/reference/acp.md +15 -14
  149. package/docs/reference/host-api.md +69 -41
  150. package/docs/reference/rpc.md +15 -9
  151. package/docs/reference/session-format.md +29 -11
  152. package/package.json +2 -2
@@ -117,26 +117,26 @@ Trade-offs: the status bar shows the latest hit rate (the session total lives in
117
117
 
118
118
  ## Keys
119
119
 
120
- | Key | Effect |
121
- | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
122
- | Enter | Send; while running = steer (queued until the next delivery point: the end of this model reply or of this tool batch) |
123
- | Ctrl+Enter / Ctrl+X | While running, interrupt and send now: stop the current turn (model stream and running tools; tools record "aborted by user") and start a new turn with the input at once, queued steers first; with an empty input only the queued steers are sent now. When idle, same as Enter. Swapped with Enter under `ui.enterWhileRunning: "interrupt"` |
124
- | Alt+Enter | While running, queue after this turn (followUp); when idle, same as Enter |
125
- | Shift+Enter / Ctrl+J | New line |
126
- | Esc | Interrupt: queued messages go back into the input box, then the current run stops (with foreground sub-agent tasks; background tasks keep running, as the hint says); closes completion first when it is open |
127
- | Esc Esc (idle) | Empty input: open the rewind list (same as `/rewind`); with text: clear it and save it into input history |
128
- | Alt+↑ | Recall the last queued message |
129
- | Shift+Tab / Tab | Cycle permission modes Manual → Accept edits → Plan → Auto → Bypass permissions (Tab only on an empty input with completion closed, otherwise still completion; entering Bypass asks to confirm, see "Entering Bypass" below) |
130
- | Ctrl+O | Expand / fold tool output and thinking blocks |
131
- | Ctrl+L / Ctrl+T | Pick model / thinking level |
132
- | Ctrl+G | Bottom info line two lines (full) ↔ one line (compact), this session only |
133
- | Ctrl+V | Paste an image from the clipboard: saved in the data directory, `@<path>` inserted at the cursor (same as `/paste`) |
134
- | Ctrl+C | Clear the input; on an empty input, press again within 1.5 seconds to quit (exit code 130) |
135
- | Ctrl+D | Quit on an empty input |
136
- | Tab | Complete |
137
- | ↑ / ↓ | Browse history on a single line (`<data dir>/history`, 500 entries) |
138
- | ↓ (empty input) | Enter the agent bar (whenever there are sub-agent tasks); with text it still moves down / through history and hints once, see "Sub-agents" |
139
- | Ctrl+B | When foreground sub-agent tasks (or a `task_ctl wait`) block the turn, move them all to the background, whatever is in the input box; otherwise cursor left. In tmux press `C-b C-b`, see "Sub-agents" |
120
+ | Key | Effect |
121
+ | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
122
+ | Enter | Send; while running = steer (queued until the next delivery point: the end of this model reply or of this tool batch) |
123
+ | Ctrl+Enter / Ctrl+X | While running, interrupt and send now: stop the current turn (model stream and running tools; tools record "aborted by user") and start a new turn with the input at once, queued steers first; with an empty input only the queued steers are sent now. When idle, same as Enter. Swapped with Enter under `ui.enterWhileRunning: "interrupt"` |
124
+ | Alt+Enter | While running, queue after this turn (followUp); when idle, same as Enter |
125
+ | Shift+Enter / Ctrl+J | New line |
126
+ | Esc | Interrupt: queued messages go back into the input box, then the current run stops (with foreground sub-agent tasks; background tasks keep running, as the hint says); closes completion first when it is open |
127
+ | Esc Esc (idle) | Empty input: open the rewind list (same as `/rewind`); with text: clear it and save it into input history |
128
+ | Alt+↑ | Recall the last queued message |
129
+ | Shift+Tab / Tab | Cycle permission modes Manual → Accept edits → Plan → Auto → Bypass permissions (Tab only on an empty input with completion closed, otherwise still completion; entering Bypass asks to confirm, see "Entering Bypass" below). Shift+Tab still works while an approval dialog is open (Tab belongs to the dialog); waiting approvals are re-evaluated under the new mode ([permissions.md](permissions.md) "Pending approvals when the mode changes") |
130
+ | Ctrl+O | Expand / fold tool output and thinking blocks |
131
+ | Ctrl+L / Ctrl+T | Pick model / thinking level |
132
+ | Ctrl+G | Bottom info line two lines (full) ↔ one line (compact), this session only |
133
+ | Ctrl+V | Paste an image from the clipboard: saved in the data directory, `@<path>` inserted at the cursor (same as `/paste`) |
134
+ | Ctrl+C | Clear the input; on an empty input, press again within 1.5 seconds to quit (exit code 130) |
135
+ | Ctrl+D | Quit on an empty input |
136
+ | Tab | Complete |
137
+ | ↑ / ↓ | Browse history on a single line (`<data dir>/history`, 500 entries) |
138
+ | ↓ (empty input) | Enter the agent bar (whenever there are sub-agent tasks); with text it still moves down / through history and hints once, see "Sub-agents" |
139
+ | Ctrl+B | When foreground sub-agent tasks (or a `task_ctl wait`) block the turn, move them all to the background, whatever is in the input box; otherwise cursor left. In tmux press `C-b C-b`, see "Sub-agents" |
140
140
 
141
141
  Keys can be overridden in `~/.config/ama/keybindings.json`: keys are action ids (`app.interrupt`, `app.rewind`, `app.message.followUp`, `app.message.interrupt`, `app.statusLine.toggle`, `app.paste.image`, `app.agents.focus`, `app.tasks.background`, `tui.editor.newLine` …), values are a key or an array of keys, and an empty array disables the action. `app.rewind` is the key double-pressed while idle (Esc by default, at most 800 ms apart).
142
142
 
@@ -404,7 +404,7 @@ Above the status line (below the hint line) the bar lists sub-agent tasks, one l
404
404
  1 more
405
405
  ```
406
406
 
407
- - States: queued (the concurrency pool is full) / running (elapsed time, turns, latest tool) / awaiting approval (the approval dialog currently holds its request, or it is docked in the bar; the row is yellow) / done / failed / stopped (plus out of turns and interrupted); `⏺` is the accent color while running, green when done, red on failure, yellow / dim otherwise; `*` in ASCII.
407
+ - States: queued (the concurrency pool is full) / running (elapsed time, turns, latest tool) / awaiting approval (the approval dialog currently holds its request, or it is docked in the bar; the row is yellow) / done / failed / stopped (plus out of turns and interrupted); `⏺` is the accent color while running, green when done, red on failure, yellow / dim otherwise; `*` in ASCII. When a sub-agent reported its state through `report` ([agents.md](../../guides/agents.md) "structured reports", Chinese) the facts gain "ready / blocked / failed / waiting", and a question left for a person adds "needs a person: …" and turns the whole row yellow — visible here even if the main agent did not relay it; `/tasks` lines, the status line under the tool row and the notification line carry it too.
408
408
  - When it shows: while any task is queued, running or awaiting approval; tasks that ended in this session and have not been looked at in the view stay until viewed, at most 10 minutes. Tasks already finished when a session is resumed are not shown (`/tasks` lists them).
409
409
  - Entering: press `↓` with an empty input box and no completion open, whenever the session has tasks (even after the bar has collapsed, same as `/tasks`); the same inside and outside tmux. It works while a turn runs too; the `↓ Agent bar` at the end of the running line is the reminder. The key action is `app.agents.focus` (only `down` by default), configurable in `keybindings.json`.
410
410
  - When the key does not get you in, a one-line hint shows for 3 seconds: text in the input box — "Input is not empty; clear it and press ↓ for the Agent bar" (once per draft, with the cursor on the last line; `↓` still moves down); the bar is off — "Agent bar is off (ui.agentBar); use /tasks"; no tasks — "No sub-agent tasks yet". While browsing input history with `↑` `↓`, `↓` only steps through history.
@@ -53,19 +53,20 @@ One `ama --mode acp` process can keep several sessions open (Zed's threads share
53
53
 
54
54
  ### Event mapping
55
55
 
56
- | ama | `session/update` |
57
- | ------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
58
- | Text delta / thinking delta | `agent_message_chunk` / `agent_thought_chunk` |
59
- | The model emits a tool call | `tool_call` (`pending`, with `name`, `rawInput`, `kind`, `locations`) |
60
- | A call inside a codemode script starts | `tool_call` (`pending`, `title` prefixed `codemode › `, `_meta.ama.parentToolCallId` pointing at the outer `codemode` call), then `in_progress` |
61
- | Tool starts | `tool_call_update` (`in_progress`) |
62
- | Tool ends (inner calls included) | `tool_call_update` (`completed` / `failed`); `content` is `[diff?, text]`: edit / write carry a `diff` (`path`, `oldText`, `newText`; `oldText: null` for a new file), the text is limited to the first 4 KB; `locations[].line` is the first changed line; no `rawOutput` |
63
- | `todo` update | `plan` |
64
- | End of each assistant message and each turn | `usage_update` (context used, window size, session cost in USD); not resent when unchanged |
65
- | Permission mode change | `current_mode_update` |
66
- | Model / thinking level change | `config_option_update` (all options); a model change also sends a `usage_update` (the window may differ) |
67
- | After a session opens (new / load / resume) | `available_commands_update`, `config_option_update` and `usage_update` (for load, after the replay), so clients need not wait for the first turn |
68
- | After a turn | `session_info_update` (`updatedAt`; `title` only when it differs from the last one) |
56
+ | ama | `session/update` |
57
+ | ------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
58
+ | Text delta / thinking delta | `agent_message_chunk` / `agent_thought_chunk` |
59
+ | The model emits a tool call | `tool_call` (`pending`, with `name`, `rawInput`, `kind`, `locations`) |
60
+ | A call inside a codemode script starts | `tool_call` (`pending`, `title` prefixed `codemode › `, `_meta.ama.parentToolCallId` pointing at the outer `codemode` call), then `in_progress` |
61
+ | Tool starts | `tool_call_update` (`in_progress`) |
62
+ | Tool ends (inner calls included) | `tool_call_update` (`completed` / `failed`); `content` is `[diff?, text]`: edit / write carry a `diff` (`path`, `oldText`, `newText`; `oldText: null` for a new file), the text is limited to the first 4 KB; `locations[].line` is the first changed line; no `rawOutput` |
63
+ | A sub-agent called `report` (#269) | `tool_call_update` on the `task` call that started it, carrying only `_meta.ama = { taskId, report }` (`report = { state, summary, humanAction? }`, see [agents.md](../../guides/agents.md) "structured reports", Chinese); status and content untouched; sent even when a background task's parent call has already ended |
64
+ | `todo` update | `plan` |
65
+ | End of each assistant message and each turn | `usage_update` (context used, window size, session cost in USD); not resent when unchanged |
66
+ | Permission mode change | `current_mode_update` |
67
+ | Model / thinking level change | `config_option_update` (all options); a model change also sends a `usage_update` (the window may differ) |
68
+ | After a session opens (new / load / resume) | `available_commands_update`, `config_option_update` and `usage_update` (for load, after the replay), so clients need not wait for the first turn |
69
+ | After a turn | `session_info_update` (`updatedAt`; `title` only when it differs from the last one) |
69
70
 
70
71
  The full before / after text of a diff only travels with live events and is never written to the session file: above 256 KiB on either side there is no diff, and tool results replayed by `session/load` carry only their first 4 KB of text. The `name` of each mode is its display name (such as `Manual` or `Accept edits`); the `description` follows the UI language. The `session/prompt` result carries the turn's token usage `usage` (`inputTokens`, `outputTokens`, `cachedReadTokens`, `cachedWriteTokens`, `totalTokens`); in schema 1.24.1 this field is still UNSTABLE (only in the unstable schema), so clients may ignore it and rely on `usage_update`. When the model's context window is unknown (such as a custom model without `contextWindow`), no `usage_update` is sent: `size` is required by the schema and ama does not make up a window.
71
72
 
@@ -73,7 +74,7 @@ The full before / after text of a diff only travels with live events and is neve
73
74
 
74
75
  ### Approvals
75
76
 
76
- Calls that ama needs to ask about go to the client as `session/request_permission` with three options: `allow_once` (Allow), `allow_always` (Allow for this session) and `reject_once` (Deny). `toolCall.toolCallId` refers to the id of an earlier `tool_call` — including calls inside codemode, which point at the inner `tool_call`, not the outer `codemode` one. While the question is open the call goes back to `pending`, then `in_progress` once allowed (so an approved call goes `pending → in_progress → pending → in_progress → completed`); a denied call goes straight to `failed`. When the client answers `cancelled`, the connection drops or the turn is interrupted, it counts as unanswered (denied). When ama no longer needs an answer (the turn was interrupted by `session/cancel` / `$/cancel_request`, or the 10-minute approval timeout passed), it withdraws the pending `session/request_permission` with `$/cancel_request { requestId }` so the client can close its dialog. In auto mode ama's own classifier still works — this only applies to ama's own tools; requests from external agents that ama drives go to a human only (see [agents.md](../../guides/agents.md), Chinese).
77
+ Calls that ama needs to ask about go to the client as `session/request_permission` with three options: `allow_once` (Allow), `allow_always` (Allow for this session) and `reject_once` (Deny). `toolCall.toolCallId` refers to the id of an earlier `tool_call` — including calls inside codemode, which point at the inner `tool_call`, not the outer `codemode` one. While the question is open the call goes back to `pending`, then `in_progress` once allowed (so an approved call goes `pending → in_progress → pending → in_progress → completed`); a denied call goes straight to `failed`. When the client answers `cancelled`, the connection drops or the turn is interrupted, it counts as unanswered (denied). When ama no longer needs an answer (the turn was interrupted by `session/cancel` / `$/cancel_request`, the 10-minute approval timeout passed, or the mode set by `session/set_mode` already decided this call — then `in_progress` follows when allowed, `failed` when denied; see [permissions.md](../guides/permissions.md) "Pending approvals when the mode changes"), it withdraws the pending `session/request_permission` with `$/cancel_request { requestId }` so the client can close its dialog. In auto mode ama's own classifier still works — this only applies to ama's own tools; requests from external agents that ama drives go to a human only (see [agents.md](../../guides/agents.md), Chinese).
77
78
 
78
79
  ### Without a model
79
80
 
@@ -5,7 +5,7 @@ English · [简体中文](../../reference/host-api.md)
5
5
  > Translated from the Chinese [docs/reference/host-api.md](../../reference/host-api.md) as of commit `979608b`. When the two differ, the Chinese
6
6
  > version is authoritative.
7
7
 
8
- A host adapter is a local JS module that ama loads at startup and hands a `HostApi`. With it the adapter can register tools, append to the system prompt, observe events, answer approvals, inject user messages and show notifications and status in the interface. The Armadra canvas plugs in as a host adapter (the canvas tools `canvas_*` / `context_*` are all registered by the adapter). The types are defined in `src/host/types.ts` and exported from `@armadra/agent/host`; `HOST_API_VERSION = 1`, `HOST_API_MINOR = 1` (host-api 1.1, see "Versioning"). The design rationale is in [design.md](../../design/design.md) §6.2, §6.3 and §11.1 step 13 (Chinese).
8
+ A host adapter is a local JS module that ama loads at startup and hands a `HostApi`. With it the adapter can register tools, append to the system prompt, observe events, answer approvals, inject user messages and show notifications and status in the interface. The Armadra canvas plugs in as a host adapter (the canvas tools `canvas_*` / `context_*` are all registered by the adapter). The types are defined in `src/host/types.ts` and exported from `@armadra/agent/host`; `HOST_API_VERSION = 1`, `HOST_API_MINOR = 2` (host-api 1.2, see "Versioning"). The design rationale is in [design.md](../../design/design.md) §6.2, §6.3 and §11.1 step 13 (Chinese).
9
9
 
10
10
  ## Module shape
11
11
 
@@ -60,7 +60,9 @@ export function create(api) {
60
60
  | Minor | First ama version | Added |
61
61
  | ----- | ----------------- | -------------------------------------------------------------------------------------------------- |
62
62
  | 0 | — | Every existing member (optional facets such as `cache?` and `runners?.provide` still need a check) |
63
- | 1 | Unreleased | `minor`, `runners?.onDone` (see "Runner done event") |
63
+ | 1 | 0.11.0 | `minor`, `runners?.onDone` (see "Runner done event") |
64
+ | 2 | Unreleased | `resources?.register` / `resources?.list` (see "Host resources") |
65
+ | 3 | Unreleased | `session_start.uncleanEnd` (with `reason: "resume"`, #268) |
64
66
 
65
67
  ## HostApi
66
68
 
@@ -84,6 +86,8 @@ export function create(api) {
84
86
  | `cache?.onWarmingDecision(handler)` | Veto hook for cache warming (see "Cache warming"); an optional facet missing in older runtimes, so check `api.cache !== undefined` before use |
85
87
  | `runners?.provide(runner)` | Injects a sub-agent runner: `id` is the name in `task(agent=<id>)` and `description` goes into the task tool description; with a host, ama starts no external CLI of its own and only uses runners injected here; returns an unsubscribe function |
86
88
  | `runners?.onDone(handler)` | Called whenever a round of a host runner ends (see "Runner done event"); returns an unsubscribe function. Since host-api 1.1, so check `typeof api.runners?.onDone === "function"` before use |
89
+ | `resources?.register(resource)` | Registers a read-only resource namespace `scheme://…` that the built-in `read` reads (see "Host resources"); only callable inside `create()`. Since host-api 1.2, so check `api.resources !== undefined` before use |
90
+ | `resources?.list()` | The registered schemes, sorted by name |
87
91
  | `minor?` | `HOST_API_MINOR` (see "Versioning"); missing in older runtimes |
88
92
 
89
93
  During `create()` the session is not assembled yet: `session.*` returns the values fixed at startup, and `sendUser` is rejected with `busy`. To send a message at startup, wait for the `session_start` event.
@@ -124,24 +128,24 @@ The exported `ToolPermission` type gains `"network"` (used by the built-in `web_
124
128
 
125
129
  `events.on` handlers only observe: a throw is just logged and does not affect the run; handlers are called and awaited in order, and `session_shutdown` is awaited (so you can clean up before exit).
126
130
 
127
- | Event | Payload | Source |
128
- | ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------- |
129
- | `session_start` | `sessionId`, `sessionFile?`, `cwd`, `reason: startup \| resume \| new \| fork` | Startup and session switches |
130
- | `before_agent_start` | `prompt` | After the user prompt is expanded, before the run starts |
131
- | `agent_start` / `turn_start` / `turn_end` / `agent_before_settle` | `{}` | Runs and turns |
132
- | `agent_end` | `stopReason`, `willRetry` | |
133
- | `agent_settled` | `warning?` | The run has fully ended |
134
- | `tool_call` | `toolCallId`, `toolName`, `input` | A tool starts executing (permission already granted) |
135
- | `tool_result` | `toolCallId`, `toolName`, `isError` | A tool finished executing |
136
- | `tool_approval_requested` | `requestId`, `toolName` | Approval needed |
137
- | `tool_approval_resolved` | `requestId`, `decision` | Approval decided |
138
- | `session_compact` | `tokensBefore` | Compaction succeeded |
139
- | `model_select` | `model: { provider, id }` | Model switched |
140
- | `hook_executed` | `event`, `command`, `exitCode`, `durationMs` | Each command hook finished |
141
- | `cache_miss` | `missedTokens`, `missedCost?`, `reason`, `detail?`, `idleMs` | A cache miss (including those below the interface threshold) |
142
- | `context_pressure` | `percent`, `threshold: 70 \| 90`, `remainingTokens?`, `estimatedTurnsLeft?` | Context usage crossed 70% / 90% |
143
- | `quota_update` | `provider`, `planType?`, `primary?`, `secondary?` (`{ usedPercent, resetsAt?, windowMinutes? }`) | ChatGPT subscription quota updated ([W6-O]; an exhausted quota has its own error code `quota_exceeded`, an expired login `auth_expired`) |
144
- | `session_shutdown` | `{}` | Before exit (followed by the SessionEnd hook and `dispose`) |
131
+ | Event | Payload | Source |
132
+ | ----------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
133
+ | `session_start` | `sessionId`, `sessionFile?`, `cwd`, `reason: startup \| resume \| new \| fork`, `uncleanEnd?` (host-api 1.3: only with `reason: "resume"`; the previous turn did not end normally — dangling tool calls, an `aborted` stop that was not a user interrupt, or a turn without its end marker; decided from the session file alone, see [session-format.md](../../reference/session-format.md), Chinese) | Startup and session switches |
134
+ | `before_agent_start` | `prompt` | After the user prompt is expanded, before the run starts |
135
+ | `agent_start` / `turn_start` / `turn_end` / `agent_before_settle` | `{}` | Runs and turns |
136
+ | `agent_end` | `stopReason`, `willRetry` | |
137
+ | `agent_settled` | `warning?` | The run has fully ended |
138
+ | `tool_call` | `toolCallId`, `toolName`, `input` | A tool starts executing (permission already granted) |
139
+ | `tool_result` | `toolCallId`, `toolName`, `isError` | A tool finished executing |
140
+ | `tool_approval_requested` | `requestId`, `toolName` | Approval needed |
141
+ | `tool_approval_resolved` | `requestId`, `decision` | Approval decided |
142
+ | `session_compact` | `tokensBefore` | Compaction succeeded |
143
+ | `model_select` | `model: { provider, id }` | Model switched |
144
+ | `hook_executed` | `event`, `command`, `exitCode`, `durationMs` | Each command hook finished |
145
+ | `cache_miss` | `missedTokens`, `missedCost?`, `reason`, `detail?`, `idleMs` | A cache miss (including those below the interface threshold) |
146
+ | `context_pressure` | `percent`, `threshold: 70 \| 90`, `remainingTokens?`, `estimatedTurnsLeft?` | Context usage crossed 70% / 90% |
147
+ | `quota_update` | `provider`, `planType?`, `primary?`, `secondary?` (`{ usedPercent, resetsAt?, windowMinutes? }`) | ChatGPT subscription quota updated ([W6-O]; an exhausted quota has its own error code `quota_exceeded`, an expired login `auth_expired`) |
148
+ | `session_shutdown` | `{}` | Before exit (followed by the SessionEnd hook and `dispose`) |
145
149
 
146
150
  For token-level streaming content or the full event stream, use RPC or the SDK's `subscribe`; host events are a trimmed set.
147
151
 
@@ -197,8 +201,32 @@ interface RunnerDoneEvent {
197
201
  - Observe-only: handlers are not awaited; a throw (including a rejected Promise) is logged once at error level through `log` and affects neither the `wait()` result nor other handlers.
198
202
  - ama may call `wait()` several times in one round (the task entry and the registry each once); the event is sent once. Calling `wait()` again after the round settled, without a new `send` / `interrupt`, sends nothing. An `interrupt` while running is followed to the end by the current round instead of starting another.
199
203
  - Only host-injected runners are covered; ama's own sub-sessions (`general` / `explore` / `plan`) still report through `subagent_start` / `subagent_end`.
204
+ - (#269) `subagent_end` may carry `report?: { state: ready | blocked | failed | waiting, summary, humanAction? }`, the status a sub-agent gives through its `report` tool ([agents.md](../../guides/agents.md) "structured reports", Chinese); a host runner may put `report` on its result or emit a `{ type: "report", report }` progress event. Optional field; `HOST_API_VERSION` / `HOST_API_MINOR` unchanged.
200
205
  - Use: the host no longer needs to poll whether the coordinator is still waiting on a task — the event says ama's side of it has ended.
201
206
 
207
+ ## Host resources
208
+
209
+ `api.resources.register({ scheme, describe, read })` (host-api 1.2): the host exposes its own data (work items, events, source texts, …) as a read-only namespace, and the model reads it with the built-in `read` tool as `scheme://path`. No tool per kind of data, so the tool table and the prompt prefix do not grow with the data; paging, truncation and continuation are handled by ama in one place.
210
+
211
+ ```ts
212
+ api.resources.register({
213
+ scheme: "demo", // ^[a-z][a-z0-9+.-]{1,31}$; reserved names such as http / https / file / data are refused
214
+ describe: "Work items: demo://items, demo://items/<id>", // one line, at most 120 characters; goes into the system prompt
215
+ read(path, { offset, limit, signal }) {
216
+ // path is the text after "://"; offset is the 1-based first line, limit the maximum number of lines (optional)
217
+ if (path !== "items") return undefined; // no such path
218
+ return pageResourceText(allItemsText, { offset, limit }); // { text, next?, total? }
219
+ },
220
+ });
221
+ ```
222
+
223
+ - **Call contract**: when `read` receives `scheme://path` for a registered scheme it first validates `offset` / `limit` by its usual rules (integers ≥ 1), then calls the host's `read(path, { offset, limit, signal })`. The result is `{ text, next?, total? }`: `text` is the text starting at line `offset` (text only; a NUL byte is refused as binary), `next` is the line number of the next page when there is more, `total` the total number of lines when known. Returning `undefined` means the path does not exist. `@armadra/agent/host` exports `pageResourceText(text, { offset, limit })` for the slicing.
224
+ - **Result shape**: the first line is always `Content read from demo://items (untrusted):` (the same marking as `web_fetch` — host data is material, not instructions), followed by `cat -n` numbered lines; beyond 2000 lines or the session's result cap the output is head-truncated with a `Use offset=N to continue` note. Lines beyond `limit` that the host returned anyway are dropped.
225
+ - **Permissions**: this is a call of the `read` tool with permission class `read` — allowed in every mode, never asks, and the auto rule layer skips its secret-path check. The host's `read` therefore **must have no side effects**, and it may be called in parallel, from sub-agents and from codemode scripts (`tools.read({ path: "demo://…" })`). Permission rules `read(demo://**)` glob the normalized reference (lower-case scheme) and the scheme in the rule is case-insensitive too, so a deny rule can block a scheme; only **registered** schemes are treated as resource references, any other `xx://` goes through the file-path logic (secret-path check and file rules). Hook matchers `read(demo://*)` match the raw `input.path`.
226
+ - **Errors**: a throwing host, no answer within 30 seconds, an invalid result shape and an unregistered scheme (the error lists the registered ones; `http(s)://` additionally points to `web_fetch`) all come back to the model as `isError` tool results and do not affect the session. `signal` aborts when the session is interrupted or the deadline passes.
227
+ - **Timing and stability**: registration is only possible inside `create()`; the list is frozen once the host is activated (a later `register` throws `invalid_arguments`), with at most 12 schemes. The tools section of the system prompt gains one line, `Host resources (pass "scheme://path" to read; …): demo:// <describe>; …`, sorted by scheme and fixed at session start; a run without resources changes by zero bytes.
228
+ - Without any registered resource `read` does not parse `scheme://` and treats the path as a file path.
229
+
202
230
  ## Exit
203
231
 
204
232
  - Process exit: `session_shutdown` event (awaited) → SessionEnd hook (`reason: "exit"`) → `adapter.dispose()` → session dispose. A throw from `dispose` is only logged as a warning.
@@ -213,8 +213,8 @@ Events are the in-process `SessionEvent` (`src/agent/types.ts`); only `message_u
213
213
  | `auto_retry_start` | `attempt`, `maxAttempts`, `delayMs`, `errorMessage` |
214
214
  | `auto_retry_end` | `success`, `attempt`, `finalError?` |
215
215
  | `permission_request` | `requestId`, `toolName`, `input`, `reason: mode \| dangerous \| hook`, `hookReason?`, `timeoutMs`, `preview?`, `autoDecision?` (why auto mode asks), `context?` (origin, see "Sub-agent events") |
216
- | `permission_resolved` | `requestId`, `decision` |
217
- | `permission_mode_changed` | `mode` |
216
+ | `permission_resolved` | `requestId`, `decision`, `reason?: mode_changed` (answered automatically under the new mode after a permission-mode switch; clients close their approval UI) |
217
+ | `permission_mode_changed` | `mode`, `reevaluated?: { allowed, denied }` (pending approvals auto-allowed / auto-denied by the switch; absent when both are 0) |
218
218
  | `model_changed` | `model: { provider, id, channel? }` |
219
219
  | `thinking_level_changed` | `level` |
220
220
  | `entry_appended` | `entry` (the session entry just written) |
@@ -248,9 +248,11 @@ Sub-agents started by `task` / `task_ctl` (ama sub-sessions and external agents
248
248
  | Event | Fields |
249
249
  | --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
250
250
  | `subagent_start` | `taskId`, `parentToolCallId`, `agent`, `runner` (`ama` / `claude` / `codex` / `acp:<program>`), `description`, `background`, `model?`, `sessionFile?`, `cwd`; sent again when the same `taskId` is continued |
251
- | `subagent_update` | `taskId`, `kind: tool \| text \| turn`, `toolName?`, `textDelta?` (merged over ≥ 250 ms), `turn`, `usage?` |
251
+ | `subagent_update` | `taskId`, `kind: tool \| text \| turn \| report`, `toolName?`, `textDelta?` (merged over ≥ 250 ms), `turn`, `usage?`, `report?` (only with `kind: "report"`: the sub-agent called `report`, #269) |
252
252
  | `subagent_background` | `taskId`, `parentToolCallId`, `reason: user \| timeout \| host` (a foreground task moved to the background: by hand in the interactive UI, when `subagents.autoBackgroundAfterMs` elapses, or by an RPC / SDK call; wave 7) |
253
- | `subagent_end` | `taskId`, `status: completed \| failed \| aborted \| max_turns \| interrupted`, `usage?`, `cache?`, `outputFile?`, `worktree?: { branch, changed }` |
253
+ | `subagent_end` | `taskId`, `status: completed \| failed \| aborted \| max_turns \| interrupted`, `usage?`, `cache?`, `outputFile?`, `worktree?: { branch, changed }`, `report?` |
254
+
255
+ `report` (#269) is the structured status a sub-agent gives through its `report` tool, `{ state: ready | blocked | failed | waiting, summary, humanAction? }` ([agents.md](../../guides/agents.md) "structured reports", Chinese): `subagent_update{kind:"report"}` is sent after each call (the value folded so far in this run), `subagent_end.report` and `TaskInfo.report` from `get_tasks` carry the final value; all absent when the sub-agent did not report. `humanAction` is something only a person can decide; clients should show it to the person directly. These are new optional fields plus one new `kind` value; `RPC_PROTOCOL_VERSION` is unchanged and clients can ignore a `kind` they do not know.
254
256
 
255
257
  Approvals of sub-sessions and external agents are sent to this connection as `permission_request` as usual, with an optional `context` marking the origin (since wave 6, approvals of this session's own tool calls also carry `context.toolCallId`, the id of the tool call that triggered the approval, which traces use to compute approval wait time; external agent requests do not carry it): `depth` (1 = from a task sub-agent), `taskId` (the originating task), `origin` (permission requests from external agents: `agent`, `sessionId` (the external CLI's own session id), `toolCall: { title, kind, locations?, inputSummary? }`, `options`). Dialogs use it to show `[task:<agent>]` or `[claude · session abc1]`. For external agent requests `toolName` is `agent:<id>` and the answer applies to this one request only ("allow for this session" is remembered by the external agent itself); the first run of an external agent in a session additionally gets one confirmation with `toolName: "task"`, `input: { agent, mode, note }` (`context.taskId`). `test/fixtures/rpc/external.out.jsonl` is the golden record of the three approvals of `task(agent="acp:ama")` (the task tool, the first run, the child ama's bash), updated by `src/agents/external-rpc.test.ts` with `UPDATE_GOLDEN=1`. After a background task completes, the parent session receives a user message with `origin: "task"` (`<task-notification …>…</task-notification>`) and starts a new turn as usual. Task and type lists are returned by `get_tasks` / `get_agents` (shapes `TaskInfo` / `AgentInfo`; empty without the task tool), with data from the current session's `taskRegistryView(sessionId)` / `sessionAgents(sessionId)` (`src/agent/subagent-registry.ts`). `get_agents` also includes external agents (`installed` / `version` come from PATH and a `--version` probe, cached asynchronously when the session is created and refreshed when external tasks end or host injections change; before the cache is ready there is only the type catalog, see `cachedAgentInfos` in `src/agents/external.ts`). `test/fixtures/rpc/subagent.out.jsonl` is the golden record of a foreground `task(agent="explore")` plus `get_tasks` / `get_agents` (keeping only responses, `tool_execution_*`, `subagent_*` and `agent_settled`), updated by `src/agent/subagent-rpc.test.ts` with `UPDATE_GOLDEN=1`. `test/fixtures/rpc/background.out.jsonl` is the golden record of `background_task` moving a running foreground `task` to the background, the task ending and its notification turn, updated by `src/modes/rpc/rpc-background.test.ts`.
256
258
 
@@ -263,11 +265,11 @@ The main session has a telemetry extension (`src/agent/session-telemetry.ts`) th
263
265
 
264
266
  ### Budget, fallback and background command events (wave 5 W5-H2)
265
267
 
266
- | Event | Fields |
267
- | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
268
- | `limit_reached` | `kind: turns \| cost`, `value` (turns / USD of this run), `limit`; once per kind per run when `limits.*` (config; `-p` also has `--max-turns` / `--max-cost`) is reached, followed by `agent_settled{warning:"limit_reached"}` |
269
- | `model_fallback` | `from`, `to` (`{ provider, id, channel? }`), `reason` (the triggering error text); when a retryable error is overloaded or retries are exhausted, switches to `fallbackModel` for one retry and switches back after the reply (plus two `model_changed`) |
270
- | `background_job` | `jobId`, `phase: started \| exited \| stopped`, `command`, `pid?`, `outputPath?`, `exitCode?`; background commands started by `bash{background:true}` |
268
+ | Event | Fields |
269
+ | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
270
+ | `limit_reached` | `kind: turns \| cost`, `value` (turns / USD of this run), `limit`; once per kind per run when `limits.*` (config; `-p` also has `--max-turns` / `--max-cost`) is reached, followed by `agent_settled{warning:"limit_reached"}` |
271
+ | `model_fallback` | `from`, `to` (`{ provider, id, channel? }`), `reason` (the triggering error text); when a retryable error is overloaded or retries are exhausted, switches to `fallbackModel` for one retry and switches back after the reply (plus two `model_changed`) |
272
+ | `background_job` | `jobId`, `phase: started \| exited \| stopped`, `command`, `pid?`, `outputPath?`, `exitCode?`; background commands started by `bash{background:true}`, and foreground commands moved to the background after `tools.bashAutoBackgroundAfterMs` (`started` is sent at the move, #266); `stopped` is sent when `tools.bashBackgroundMaxMs` is reached (#267) |
271
273
 
272
274
  When repeated-call detection (the 5th call with the same name and arguments in one run) ends a run, it ends with `agent_settled{warning:"repeated_tool_call"}`.
273
275
 
@@ -360,6 +362,7 @@ It also carries `context: { tokens, window, percent }` (context used, window siz
360
362
  3. The client replies with `permission_response{requestId, decision}`. `allow_session` remembers the same tool and normalized input prefix within this session, without writing to disk. Answers arriving before their request are kept and used once the request appears.
361
363
  4. Order of answerers: host broker (`HostApi.approvals.setBroker`) → RPC client → deny when nobody answers. Approvals are serial: only one waits at a time.
362
364
  5. Timeout: without an answer within `timeoutMs` (default 600 000, i.e. 10 minutes; the `AMA_APPROVAL_TIMEOUT_MS` environment variable changes it), the server treats it as deny and sends `permission_resolved`. When the run is interrupted it is also deny, even if the client already allowed.
365
+ 6. Permission-mode switch (`set_permission_mode`, or the session switching on its own, e.g. plan approval): waiting and queued approvals are re-evaluated under the new mode — what it allows is answered allow automatically, what it denies is answered deny (the model's result names the switch), what it still asks about is left alone; automatically answered requests get `permission_resolved{reason:"mode_changed"}` and `permission_mode_changed` carries `reevaluated{allowed, denied}`. Requests taken by a host broker, dangerous commands and external-agent requests are not touched. See [permissions.md](../guides/permissions.md) "Pending approvals when the mode changes".
363
366
 
364
367
  ## Plan approval
365
368
 
@@ -10,6 +10,7 @@
10
10
  `task` 与 `task_ctl` 同进退:`default` 预设下只在 codemode 脚本里可调用,`--tools …,task` 或 `tools.default: ["+task"]`
11
11
  时直接暴露;嵌入宿主时宿主可以禁用。子 Agent 运行在同一进程的新会话里(全新上下文,看不到父对话,`prompt` 要写全),
12
12
  有自己的 JSONL(与父会话同目录,头的 `parentSession` 指回父文件)。深度最多 1:子 Agent 里调用 `task` / `task_ctl` 会被拒绝。
13
+ `report` 是第三个同进退的工具:子 Agent 用它向父会话报告结构化状态(见「结构化报告」),父会话里调用会被拒绝。
13
14
 
14
15
  ### 内置类型
15
16
 
@@ -20,7 +21,7 @@
20
21
  | `plan` | 父的活动集 | plan 模式 | 输出分步计划、关键文件与取舍,不修改文件 |
21
22
 
22
23
  只读靠权限层:只读类型的子会话用一条 plan 模式的权限管线(规则与父相同),需要确认的调用一律直接拒绝,**不弹审批**。
23
- 工具表与父会话逐字节相同(`task` / `task_ctl` 也在表里,运行时拒绝),子会话的首个请求能复用父会话已缓存的 tools + system
24
+ 工具表与父会话逐字节相同(`task` / `task_ctl` / `report` 都在表里,前两个在子会话、后一个在父会话运行时拒绝),子会话的首个请求能复用父会话已缓存的 tools + system
24
25
  前缀;角色说明是系统提示最后一个节(`role`),父会话的全部节都是它的前缀。只有类型声明了 `tools` / `disallowed-tools`
25
26
  (或调用时传了 `tools`)时工具表才不同,此时首个请求不命中父的缓存。
26
27
 
@@ -121,15 +122,71 @@ ama 再跑一轮、在消息里要求「不要调用工具、直接给最终报
121
122
 
122
123
  `task_ctl` 的动作:
123
124
 
124
- | `action` | 说明 |
125
- | -------- | ------------------------------------------------------------------------------------------------------- |
126
- | `list` | 列出本会话的任务:编号、类型、状态、轮数、token、耗时、是否后台、描述 |
127
- | `wait` | 等任务结束(`timeoutMs` 缺省 30 000,最多 600 000);超时说明仍在运行;被转后台时立即返回并说明不必再等 |
128
- | `stop` | 停止任务,返回终态 |
129
- | `output` | 运行中返回已有输出,结束后返回最终文本(同样有 50 KB 上限) |
130
- | `send` | 向任务追加一条消息并放到后台运行(等价于 `task{taskId, prompt, background:true}`) |
125
+ | `action` | 说明 |
126
+ | -------- | --------------------------------------------------------------------------------------------------------------------------------------- |
127
+ | `list` | 列出本会话的任务:编号、类型、状态、轮数、token、耗时、是否后台、描述 |
128
+ | `wait` | 等任务结束(`timeoutMs` 缺省 30 000,最多 600 000);超时说明仍在运行;被转后台时立即返回并说明不必再等;结果正文前带「结构化报告」的行 |
129
+ | `stop` | 停止任务,返回终态 |
130
+ | `output` | 运行中返回已有输出,结束后返回最终文本(同样有 50 KB 上限) |
131
+ | `send` | 向任务追加一条消息并放到后台运行(等价于 `task{taskId, prompt, background:true}`) |
132
+ | `extend` | 给后台任务续命一次(`timeoutMs` 为增量,缺省与上限相同,封顶一个上限);见「长命令与后台寿命」 |
131
133
 
132
- `coordinator` 预设下 `wait` 的超时封顶 5 000 毫秒(含缺省与更大的 `timeoutMs`),超时回复里说明被封顶、完成后会有通知;其它预设不变。
134
+ `coordinator` 预设下 `wait` 的超时封顶 5 000 毫秒(含缺省与更大的 `timeoutMs`),超时回复里说明被封顶、完成后会有通知;
135
+ `bash {job, action: "wait"}` 同样封顶(#242);其它预设不变。
136
+
137
+ ### 长命令与后台寿命
138
+
139
+ 前台 `bash` 最长会挂 120 秒(上限 600 秒),这期间插话与子任务通知都要等它结束。`tools.bashAutoBackgroundAfterMs` 大于 0 时,
140
+ 前台命令跑过这个时长还没结束就**原地转成后台任务**:进程不重启,交给后台任务表登记(发 `background_job{phase:"started"}`),
141
+ 工具立即返回 `{ jobId, outputPath, pid?, movedToBackground: true, output }`,正文是到此刻的输出尾部加一段说明;之后
142
+ `bash {job, action: "wait" | "output" | "stop"}` 照常可用,命令退出后经提醒通道告知模型。转后台之后原来的超时不再生效,父回合的
143
+ `Esc` 也不再杀它(与子 Agent 转后台同一语义),会话关闭时仍随会话回收。阈值不小于超时时超时先到,照旧杀掉、不转。
144
+
145
+ 缺省由运行方式决定:`--mode rpc` / `--mode acp`、嵌入宿主(有 profile)或 `coordinator` 预设下 15 000;独立交互界面与 `-p`
146
+ 下 0(关闭,人在终端前看得到输出)。显式写 `0` 即关闭。权限审批发生在启动前、沙箱包装与输出截断规则都不变。
147
+
148
+ 后台任务与后台子 Agent 有寿命上限:`tools.bashBackgroundMaxMs`(缺省 2 小时)到点杀掉后台命令的进程树(SIGTERM → 宽限 →
149
+ SIGKILL;Windows `taskkill /T /F`),`subagents.backgroundMaxMs`(缺省 1 小时)到点按 `stop` 处理后台子 Agent(终态 `aborted`,
150
+ 不发 `<task-notification>`);`0` 表示不限。到点后模型经提醒通道得知「后台任务 … 到达寿命上限被停止」,输出文件保留;前台转来的
151
+ 命令、转后台的任务都从转换时刻起算。每个任务可以续命一次:`bash {job, action: "extend", timeoutMs?}` /
152
+ `task_ctl {action: "extend", taskId, timeoutMs?}`,增量缺省与上限相同、最多再加一个上限,第二次续命被拒绝。
153
+
154
+ ### 结构化报告
155
+
156
+ 子 Agent 结束时父会话只拿到一段文字,「做完了」「卡住了」「要人拍板」都得从正文里猜;要人回答的问题埋在正文里时,父会话还可能自己编一个答案接着做。
157
+ `report` 工具(#269)把这三件事变成结构化字段:
158
+
159
+ ```text
160
+ report({ state: "blocked", summary: "Tests need a database account.", humanAction: "Which test account should I use?" })
161
+ ```
162
+
163
+ - `state`:`ready`(做完)/ `blocked`(缺了某样东西做不下去)/ `failed`(放弃)/ `waiting`(在等外部的事);`summary` ≤ 300 字符。
164
+ - `humanAction`(≤ 300 字符)是**单槽**:只放只有人能决定的事。一次运行里多次调用时,给出就替换、省略就保持、`null` 清空;`state` / `summary` 取最后一次。
165
+ - 槽按**一次运行**划定:每次 `task` 调用或 `taskId` 续聊开始时清空——续聊通常就是父会话带着人的回答回来,旧问题不会跨运行重复出现。
166
+ - 角色说明末尾要求子 Agent 结束前调用 `report`,但不强制:没调用时结果、通知与事件和原来逐字节相同。
167
+
168
+ 父会话看到的(`task` 结果、`<task-notification>`、`task_ctl wait` 三处一致)是在正文前加的固定英文行:
169
+
170
+ ```text
171
+ [report] blocked · Tests need a database account.
172
+ [needs a person] Which test account should I use?
173
+ Relay this question to the user verbatim; do not answer it yourself.
174
+
175
+ …子 Agent 的正文…
176
+ ```
177
+
178
+ `task` 结果的 `details.report`、`<task-notification>` 的 `report="blocked"` 属性、RPC `get_tasks` 的 `TaskInfo.report` 与事件
179
+ `subagent_update{kind:"report"}` / `subagent_end.report` 带同一份报告([rpc.md](../reference/rpc.md)「子 Agent 事件」)。
180
+ 规则句是对父模型的约束;对人的保证是界面:Agent 栏与 `/tasks` 的任务行带状态标签,留了待人决定的问题时整行警告色并带上问题,
181
+ 终端程序状态里该任务是 `blocked:question`,ACP 客户端在发起它的 `task` 调用上收到 `_meta.ama.report`——父模型就算把问题吞了,人也看得到。
182
+
183
+ 外部 Agent 没有 `report` 工具,驱动只映射能确定的原生状态:ACP `stopReason` 的 `refusal` → `failed`,`max_tokens` /
184
+ `max_turn_requests` → `blocked`(摘要是固定英文一句);`end_turn` 分不清做完与等人,不编造,行为与原来一样。宿主注入的 runner
185
+ 可以在结果里带 `report` 或发 `{ type: "report" }` 进度事件。
186
+
187
+ `report` 是 `task` 的伴随工具:父会话的工具表里也有它(否则子会话的工具表与父不同,缓存前缀从第一个字节起失效,fork 模式也就
188
+ 失去意义),只是父会话里调用会被拒绝。代价是开了 `task` 的会话前缀多一个短工具(`default + task` 预算从 2 150 放宽到 2 250 token,
189
+ `codemode-only` 从 1 900 到 1 950,见 [design.md](../design/design.md) §9.1)。
133
190
 
134
191
  ### 续聊、保留与 resume
135
192
 
@@ -192,24 +249,28 @@ fork 的成本不止首请求:子会话**每一回合**都重读整段父前
192
249
 
193
250
  ### 事件与统计
194
251
 
195
- RPC / SDK 事件 `subagent_start` / `subagent_update` / `subagent_background` / `subagent_end` 见 [rpc.md](../reference/rpc.md)「子 Agent 事件」。
252
+ RPC / SDK 事件 `subagent_start` / `subagent_update` / `subagent_background` / `subagent_end` 见 [rpc.md](../reference/rpc.md)「子 Agent 事件」;
253
+ 子 Agent 用 `report` 报告时另有 `subagent_update{kind:"report"}`,`subagent_end` 与 `get_tasks` 的 `TaskInfo` 带 `report`。
196
254
  `getStats().tasks` 给出任务总数、运行中数量与按状态的计数;子会话的缓存命中与重计费仍汇总在 `cache.subagents`。
197
255
  RPC `get_tasks` / `get_agents` 返回任务快照与可用类型(来源、定义文件路径)。交互界面的 `/tasks`、`/agents` 与 task 工具行的折叠显示见 [tui.md](tui.md)「子 Agent」。
198
256
 
199
257
  ### 配置
200
258
 
201
- | 键 | 说明 |
202
- | --------------------------------- | -------------------------------------------------------------------------------- |
203
- | `subagents.maxConcurrent` | 同时运行的子 Agent,缺省 4 |
204
- | `subagents.maxPending` | 排队上限,缺省 16 |
205
- | `subagents.retainSessions` | 保留在内存里的已结束子会话数(LRU),缺省 4,0 = 结束即释放;只认用户级 |
206
- | `subagents.defaultModel` | 子 Agent 缺省模型,不设继承父会话 |
207
- | `subagents.forkMaxContextRatio` | fork 回落比例(见「fork 模式」),0.05–0.95,缺省 0.5;只认用户级 |
208
- | `subagents.background` | `auto`(缺省)\| `always` \| `never`,见「前台与后台」;用户 / 项目 / 宿主级都认 |
209
- | `subagents.autoBackgroundAfterMs` | 前台任务运行超过该毫秒数自动转后台,缺省 0(关闭);用户 / 项目级都认 |
210
- | `agents.dirs` | 追加的定义目录 |
211
- | `agents.<类型>.model` | 某个类型的模型(如让 `explore` 用便宜模型) |
212
- | `models.aliases.fast` / `.strong` | 定义文件里 `model: fast / strong` 的映射 |
259
+ | 键 | 说明 |
260
+ | --------------------------------- | ---------------------------------------------------------------------------------------------------- |
261
+ | `subagents.maxConcurrent` | 同时运行的子 Agent,缺省 4 |
262
+ | `subagents.maxPending` | 排队上限,缺省 16 |
263
+ | `subagents.retainSessions` | 保留在内存里的已结束子会话数(LRU),缺省 4,0 = 结束即释放;只认用户级 |
264
+ | `subagents.defaultModel` | 子 Agent 缺省模型,不设继承父会话 |
265
+ | `subagents.forkMaxContextRatio` | fork 回落比例(见「fork 模式」),0.05–0.95,缺省 0.5;只认用户级 |
266
+ | `subagents.background` | `auto`(缺省)\| `always` \| `never`,见「前台与后台」;用户 / 项目 / 宿主级都认 |
267
+ | `subagents.autoBackgroundAfterMs` | 前台任务运行超过该毫秒数自动转后台,缺省 0(关闭);用户 / 项目级都认 |
268
+ | `subagents.backgroundMaxMs` | 后台任务的寿命上限(毫秒),缺省 3 600 000(1 小时),0 不限;只认用户级(见「长命令与后台寿命」) |
269
+ | `tools.bashAutoBackgroundAfterMs` | 前台 `bash` 运行超过该毫秒数原地转后台;不设时按运行方式定缺省(见「长命令与后台寿命」);只认用户级 |
270
+ | `tools.bashBackgroundMaxMs` | 后台 `bash` 任务的寿命上限(毫秒),缺省 7 200 000(2 小时),0 不限;只认用户级 |
271
+ | `agents.dirs` | 追加的定义目录 |
272
+ | `agents.<类型>.model` | 某个类型的模型(如让 `explore` 用便宜模型) |
273
+ | `models.aliases.fast` / `.strong` | 定义文件里 `model: fast / strong` 的映射 |
213
274
 
214
275
  按角色选模型只要三行配置(`config.json`):别名 `fast` 指向便宜模型,`explore` 类型用它,外部 Agent `claude` 用它自己的模型名(原样交给该 CLI):
215
276
 
@@ -92,6 +92,8 @@ stdin 是一个 JSON 对象,写完即关闭。所有事件共有:
92
92
  | `Notification` | `notification: { kind: approval \| settled \| error \| retry, message }` |
93
93
  | `PostRewind` | `entryId`(回滚到的用户消息)、`mode: both \| conversation \| code`、`files`(被恢复或删除的文件,仅对话时为空) |
94
94
 
95
+ **宿主资源引用**:`read` 的 `path` 若是已注册的宿主资源引用(见 [host-api.md](../reference/host-api.md)「宿主资源」),交给 matcher 与 Hook 脚本的 `toolInput.path` 都是规范形式 `小写scheme://path`(与权限规则、会话记忆和 read 实际读取看到的一致);未注册的 scheme 与普通文件路径保持原文,`write` / `edit` 等其它工具不做此处理。
96
+
95
97
  **codemode**:脚本里经 `tools.*` 发起的每次调用都单独经过 PreToolUse / PostToolUse,matcher 按**真实工具名**匹配(`bash`,不是 `codemode`),输入多两个字段:`viaCodemode: true` 与 `parentToolCallId`(外层 `codemode` 调用的 id)。`codemode` 调用本身也作为一次工具调用经过两个事件。模型直接发起的调用不带这两个字段。
96
98
 
97
99
  环境变量(便于 shell 脚本):`AMA_HOOK_EVENT`、`AMA_SESSION_ID`、`AMA_CWD`,工具事件另有 `AMA_TOOL_NAME`,`read` / `write` / `edit` 另有 `AMA_FILE`(目标路径)。
@@ -152,15 +154,16 @@ Hook 在权限管线之前,是因为它是用户策略(可以改输入、可
152
154
 
153
155
  只对 `PreToolUse` / `PostToolUse` 生效,其它事件忽略 matcher。
154
156
 
155
- | 写法 | 匹配 |
156
- | ------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
157
- | 缺省、`""`、`*` | 全部工具 |
158
- | `bash` | 精确匹配工具名 |
159
- | `write\|edit` | 多选(括号外的 `\|` 分隔) |
160
- | `canvas_*` | glob:`*` 任意字符串、`?` 单个字符 |
161
- | `bash(git push*)` | 先匹配工具名,再对参数文本做 glob:bash 是 `command`,文件类工具是 `path`,其它工具是输入的 JSON 文本 |
162
- | `web_fetch(*docs.example.org*)` | `web_fetch` 的参数文本是整个 `url`(含协议与查询串,`*` 跨 `/`);与权限规则 `web_fetch(<pattern>)` 的 `host/path` 语义不同 |
163
- | `/regex/flags` | 对工具名做正则 |
157
+ | 写法 | 匹配 |
158
+ | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
159
+ | 缺省、`""`、`*` | 全部工具 |
160
+ | `bash` | 精确匹配工具名 |
161
+ | `write\|edit` | 多选(括号外的 `\|` 分隔) |
162
+ | `canvas_*` | glob:`*` 任意字符串、`?` 单个字符 |
163
+ | `bash(git push*)` | 先匹配工具名,再对参数文本做 glob:bash 是 `command`,文件类工具是 `path`,其它工具是输入的 JSON 文本 |
164
+ | `web_fetch(*docs.example.org*)` | `web_fetch` 的参数文本是整个 `url`(含协议与查询串,`*` 跨 `/`);与权限规则 `web_fetch(<pattern>)` 的 `host/path` 语义不同 |
165
+ | `read(demo://*)` | `read` 的 `path` 若是**已注册**的宿主资源引用,先规范成 `小写scheme://path` 再匹配,`DEMO://x` 也命中;括号里的 scheme 同样不分大小写(`read(DEMO://*)` 等价),路径部分仍区分 |
166
+ | `/regex/flags` | 对工具名做正则 |
164
167
 
165
168
  ## 运行环境
166
169
 
@@ -32,6 +32,20 @@
32
32
  - `Shift+Tab` 循环:Manual → Accept edits → Plan → Auto → Bypass permissions → Manual。`Allowlist only` 不在循环里,只能显式选。
33
33
  - **进入 Bypass**:交互界面里切到 Bypass(Tab / Shift+Tab 循环、`/permission` 选择器、`/permission full-auto`)先弹确认框,缺省选中「取消」;循环时取消则跳过 Bypass 回到 Manual,选择器与命令取消则保持原模式。本次运行确认过一次后不再问。命令行 `--permission-mode full-auto`、用户级配置与 profile 指定的不弹(那是显式选择);line 模式问 `确认进入 Bypass?[y/N]`;管道输入、RPC `set_permission_mode`、ACP `session/set_mode` 由调用方负责,不弹。详见 [tui.md](tui.md)「进入 Bypass」。
34
34
 
35
+ ### 切换模式时的待审批
36
+
37
+ 切换模式对**之后**的调用立即生效;对切换那一刻**已经在等回答**的审批(弹出的那一条,以及排在它后面的子 Agent / codemode 的请求),ama 按新模式把同一调用重新过一遍管线(同一条管线、同样的 Hook 结论,不再调 auto 分类器):
38
+
39
+ | 重判结果 | 处理 |
40
+ | -------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
41
+ | 新模式放行(切到 Bypass;切到 Accept edits 时等的是写入;切到 Plan 时等的是只读命令…) | 自动答允许:对话框 / 停靠收起,消息区一行「已按 Bypass permissions 自动允许 N 个待审批」 |
42
+ | 新模式拒绝(切到 Plan 时等的是写入或非只读命令;切到 Allowlist only 时名单外的) | 自动答拒绝:对话框收起,消息区一行「已按 Plan 自动拒绝 N 个待审批」;模型收到的结果写明「the permission mode was switched to "plan" …」加管线的说明 |
43
+ | 新模式仍要问(Auto 下规则层 / 静态判定没定、要交分类器的也算) | 保持不动,继续等人 |
44
+
45
+ 不碰的:宿主 broker(`HostApi.approvals.setBroker`)已经接手、正在等它回答的请求(宿主自己决定);危险命令表命中的(切到 Bypass 也照旧要人确认);外部 Agent 的权限请求与首次运行确认(一律交给人)。自动作答只有允许 / 拒绝,不写 `allow_session` 记忆;切到 Auto 时由规则层 / 静态判定放行的,不记入 `/permissions` 的 auto 审计(审计只记首轮判定)。先到的回答为准:人已经按了键就按人的,之后才到的切换不再改它。
46
+
47
+ 来源不限:交互界面 Shift+Tab / `/permission`、RPC `set_permission_mode`、ACP `session/set_mode`、计划批准切回执行模式都走同一条路。审批对话框打开时 Shift+Tab 仍能切模式(Tab 归对话框);切到 Bypass 照旧先弹确认框,确认之后才重判。RPC / ACP 客户端收到被自动作答请求的 `permission_resolved`,`reason: "mode_changed"`,据此收起自己的审批界面([rpc.md](../reference/rpc.md)「审批」)。
48
+
35
49
  ### 审批对话框的来源标注
36
50
 
37
51
  审批不只来自主会话。对话框(以及 RPC `permission_request.context`)标出请求从哪来,选项都只有「允许 / 本会话允许同类 / 拒绝」(`web_fetch` 的第二项是「本会话允许 `<主机>`」):