@armadra/agent 0.15.1 → 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 +30 -0
  2. package/CHANGELOG.zh-CN.md +30 -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 +1 -1
package/CHANGELOG.md CHANGED
@@ -5,6 +5,36 @@ English · [简体中文](CHANGELOG.zh-CN.md)
5
5
  > This file is in English starting with 0.6.0. Release notes for 0.1 through 0.5.1 are in Chinese in
6
6
  > [CHANGELOG.zh-CN.md](CHANGELOG.zh-CN.md). New entries go into both files.
7
7
 
8
+ ## 0.16.0 (2026-11-09)
9
+
10
+ ### Sessions
11
+
12
+ - **Recovery reminder after an unclean end**: when a session is resumed (`--resume` / `--continue`, `/resume`, RPC `switch_session`, ACP `session/load`, a `taskId` continuation reopening a sub-agent session) and its last turn did not end normally — tool calls without results, an `aborted` stop that was not a user interrupt, or a turn without its end marker — a one-time reminder goes out through the reminder channel (`ama.reminder` with `details.recovery`, not the system prompt, so the prompt prefix is unchanged) before the first new prompt: it lists the tool calls of that turn (bash: first word of the command; write / edit: the path; never outputs) and asks the model to inspect the workspace, git history and external state before repeating any external action. The decision reads only the session file; a clean exit, an Esc interrupt or a crash before any tool ran does not trigger it, and a second resume does not repeat it. Interrupted sub-agent tasks carry the same note in `task_ctl` `list` / `output` / `wait`. See [docs/reference/session-format.md](docs/reference/session-format.md) (#268).
13
+
14
+ ### Host
15
+
16
+ - **Host resource namespace, read through the built-in `read`** (host-api 1.2): `api.resources.register({ scheme, describe, read })` exposes host data as `scheme://path`; the model pages it with `read`'s `offset` / `limit`, the result carries the `(untrusted)` marking of `web_fetch`, obeys the same truncation and session caps, and runs as permission class `read` (never asks, so the host's `read` must be side-effect free). The system prompt's tools section gains one sorted line listing the schemes, fixed at session start; an unregistered scheme returns an error listing the registered ones, `http(s)://` points to `web_fetch`, and codemode scripts can call `tools.read({ path: "scheme://…" })`. `@armadra/agent/host` exports `pageResourceText`. See [docs/reference/host-api.md](docs/reference/host-api.md) "Host resources" (#270).
17
+ - **host-api 1.3**: the `session_start` event carries `uncleanEnd` when `reason` is `resume`, using the same decision (#268).
18
+
19
+ ### Permissions
20
+
21
+ - **Switching the permission mode re-evaluates approvals that are already waiting**: Shift+Tab / `/permission`, RPC `set_permission_mode`, ACP `session/set_mode` and plan approval all re-run the waiting and queued approvals through the pipeline under the new mode. What the new mode allows is answered allow automatically (the dialog or dock closes, one line "Auto-allowed N pending approvals under <mode>"), what it denies is answered deny with a reason that names the switch, the rest keep waiting. Never touched: requests a host broker has taken, dangerous-command hits (still ask under Bypass), external-agent requests, `allow_session` memory. Shift+Tab still cycles while the approval dialog is open (Tab stays with the dialog; Bypass still asks to confirm first). RPC / ACP clients get `permission_resolved{reason:"mode_changed"}` and `permission_mode_changed.reevaluated{allowed, denied}`. See [docs/guides/permissions.md](docs/guides/permissions.md) (#271).
22
+
23
+ ### Hooks
24
+
25
+ - **Hook matchers see the normalised resource reference**: for a `read` call whose `path` is a registered host resource reference, `toolInput.path` is normalised to `lowercase-scheme://path` before the matcher runs and before the hook script receives it, so a `PreToolUse` hook with matcher `read(demo://*)` also catches `DEMO://…` and `Demo://…` — the same form the permission rules, session memory and the actual read use. The scheme in the matcher pattern is case-insensitive as well (`read(DEMO://*)` keeps working; the path part stays case-sensitive). Unregistered schemes and plain file paths stay verbatim; other tools are untouched. See [docs/guides/hooks.md](docs/guides/hooks.md) "matcher" (#277).
26
+
27
+ ### Tools and permissions
28
+
29
+ - **A foreground `bash` command moves to the background after a threshold** (`tools.bashAutoBackgroundAfterMs`): when it is still running after the threshold, the process is handed to the background job table without being restarted and the tool returns at once with `{ jobId, outputPath, movedToBackground: true, output }` (the output so far); steering messages and task notifications no longer wait for the command, the exit is reported through the reminder channel as for any background job, and `bash {job, action}` works as usual. The default is 15 s under `--mode rpc` / `--mode acp`, in an embedding host (with a profile) and with the `coordinator` preset, and off (`0`) in a standalone terminal and with `-p`. Permission checks, sandbox wrapping, output truncation and the Windows process tree are unchanged; the 120 s / 600 s timeout no longer applies to a moved command, which is governed by the lifetime cap instead (#266).
30
+ - **Lifetime caps for background jobs and background sub-agents**: `tools.bashBackgroundMaxMs` (default 2 hours) kills a background command's process tree when it is reached (SIGTERM → grace → SIGKILL; `taskkill /T` on Windows) and `subagents.backgroundMaxMs` (default 1 hour) stops a background sub-agent; `0` means unlimited. The model is told through the reminder channel ("stopped at its lifetime cap") and the output file is kept. A command moved from the foreground, or a task moved to the background, counts from the move. One extension per job or task: `bash {job, action: "extend", timeoutMs?}` and `task_ctl {action: "extend", taskId, timeoutMs?}` add at most one more cap; caps are limited to 2^31 − 1 ms (#267).
31
+ - **`bash {job, action: "wait"}` is capped at 5 s under the `coordinator` preset**, like `task_ctl wait`; the capped reply says so (#242).
32
+
33
+ ### Sub-agents
34
+
35
+ - **Structured sub-agent reports** (#269): sub-sessions get a `report` tool, `{ state: ready | blocked | failed | waiting, summary, humanAction? }`. `humanAction` is a single slot for things only a person can decide (given replaces, omitted keeps, `null` clears; reset at each run, so a `taskId` follow-up starts clean). The parent's `task` result, `<task-notification>` and `task_ctl wait` text start with a `[report] state · summary` line and, with a human action, `[needs a person] …` plus the fixed rule "Relay this question to the user verbatim; do not answer it yourself."; `details.report`, `TaskInfo.report`, `subagent_update{kind:"report"}` and `subagent_end.report` carry the same value (optional fields, `RPC_PROTOCOL_VERSION` unchanged). The agent bar, `/tasks`, the tool-row status line and the terminal program status (`blocked:question`) show the state and the question so a person sees it even if the main agent does not relay it; ACP clients get it as `_meta.ama.report` on the originating `task` call. External agents map `refusal` → failed and `max_tokens` / `max_turn_requests` → blocked; `end_turn` is not mapped. Without a `report` call everything is byte-identical to before. `report` is a companion of `task` (present but rejected in the parent, so sub-session tool tables stay identical to the parent's and cache prefixes keep working); the `default + task` and `codemode-only` prompt budgets widen to 2300 / 1950 tokens (2300 includes the `extend` actions of #266 / #267). See [docs/guides/agents.md](docs/guides/agents.md).
36
+ - **Fixed: continuing a stopped sub-agent no longer ends as `aborted`**: after `task_ctl stop` or a lifetime-cap stop, a `taskId` continuation of an ama sub-session that completes normally now reports `completed` (and sends its `<task-notification>`); before, the runner kept judging the new run by the first run's already-aborted signal. Each run now has its own abort signal: `stop` and a parent-turn abort only end the current run, and a later continuation starts clean (#278).
37
+
8
38
  ## 0.15.1 (2026-11-06)
9
39
 
10
40
  ### Maintenance
@@ -4,6 +4,36 @@
4
4
 
5
5
  > 从 0.6.0 起 [CHANGELOG.md](CHANGELOG.md) 为英文,本文件保留中文记录(0.1–0.5.1 的完整历史在此)。新条目两份都要加。
6
6
 
7
+ ## 0.16.0(2026-11-09)
8
+
9
+ ### 会话
10
+
11
+ - **异常中断后恢复会话时的恢复提醒**:恢复会话(`--resume` / `--continue`、`/resume`、RPC `switch_session`、ACP `session/load`、`taskId` 续聊重开子会话)时,上一轮若没有正常结束——工具调用缺结果、不是人主动中断的 `aborted`、回合没有结束标记——在第一个新提示前经提醒通道(`ama.reminder`,带 `details.recovery`;不进系统提示,前缀不变)注入一次恢复提醒:列出那一轮调用过的工具(bash 只给命令第一个词,write / edit 给路径,不带输出),要求先检查工作区、git 历史和外部状态再决定要不要重复外部动作。判定只读会话文件;干净退出、Esc 中断、还没跑任何工具就崩溃的不触发,第二次恢复不重复。被打断的子 Agent 任务在 `task_ctl` 的 `list` / `output` / `wait` 里附同一句说明。见 [docs/reference/session-format.md](docs/reference/session-format.md)(#268)。
12
+
13
+ ### 宿主
14
+
15
+ - **宿主资源命名空间,内置 `read` 读 `scheme://path`**(host-api 1.2):`api.resources.register({ scheme, describe, read })` 把宿主数据暴露成 `scheme://path`;模型用 `read` 的 `offset` / `limit` 分页,结果带与 `web_fetch` 同一套的 `(untrusted)` 标注,走同一截断规则与会话结果上限,权限类 `read`(从不询问,所以宿主的 `read` 不得有副作用)。系统提示工具节多一行按 scheme 排序的资源清单,会话开始时固定;未注册的 scheme 报错并列出已注册的,`http(s)://` 指向 `web_fetch`,codemode 脚本里同样可以 `tools.read({ path: "scheme://…" })`。`@armadra/agent/host` 导出 `pageResourceText`。见 [docs/reference/host-api.md](docs/reference/host-api.md)「宿主资源」(#270)。
16
+ - **host-api 1.3**:`session_start` 事件在 `reason` 为 `resume` 时带 `uncleanEnd`,用同一个判定(#268)。
17
+
18
+ ### 权限
19
+
20
+ - **切换权限模式时重新判定正在等的审批**:Shift+Tab / `/permission`、RPC `set_permission_mode`、ACP `session/set_mode` 与计划批准都会把在等的与排队的审批按新模式重新过一遍管线。新模式放行的自动允许(对话框或停靠收起,消息区一行「已按 <模式> 自动允许 N 个待审批」),拒绝的自动拒绝并在给模型的结果里写明切换,仍要问的继续等。不碰:宿主 broker 已接手的请求、危险命令(切到 Bypass 也照旧要人确认)、外部 Agent 的请求、`allow_session` 记忆。审批对话框打开时 Shift+Tab 仍能切模式(Tab 归对话框;进入 Bypass 照旧先确认)。RPC / ACP 客户端收到 `permission_resolved{reason:"mode_changed"}` 与 `permission_mode_changed.reevaluated{allowed, denied}`。见 [docs/guides/permissions.md](docs/guides/permissions.md)(#271)。
21
+
22
+ ### Hook
23
+
24
+ - **Hook matcher 看到的是规范化后的资源引用**:`read` 调用的 `path` 若是已注册的宿主资源引用,先规范成 `小写scheme://path` 再交给 matcher 与 Hook 脚本,matcher 为 `read(demo://*)` 的 `PreToolUse` Hook 也能挡住 `DEMO://…`、`Demo://…`——与权限规则、会话记忆和 read 实际读取看到的形式一致。matcher 括号里的 scheme 同样不分大小写(`read(DEMO://*)` 照常生效,路径部分仍区分)。未注册的 scheme 与普通文件路径保持原文,其它工具不受影响。见 [docs/guides/hooks.md](docs/guides/hooks.md)「matcher」(#277)。
25
+
26
+ ### 工具与权限
27
+
28
+ - **前台 `bash` 超过阈值原地转后台**(`tools.bashAutoBackgroundAfterMs`):命令跑过阈值还没结束时,进程不重启、直接交给后台任务表登记,工具立即返回 `{ jobId, outputPath, movedToBackground: true, output }`(到此刻的输出);插话与子任务通知不再被长命令挡住,退出沿用后台命令的提醒通道,`bash {job, action}` 照常可用。缺省:`--mode rpc` / `--mode acp`、嵌入宿主(有 profile)与 `coordinator` 预设下 15 秒,独立终端与 `-p` 下关闭(`0`)。权限管线、沙箱包装、输出截断与 Windows 进程树处理不变;转后台的命令不再受 120 / 600 秒超时约束,改受寿命上限约束(#266)。
29
+ - **后台任务与后台子 Agent 的寿命上限**:`tools.bashBackgroundMaxMs`(缺省 2 小时)到点杀掉后台命令的进程树(SIGTERM → 宽限 → SIGKILL;Windows `taskkill /T`),`subagents.backgroundMaxMs`(缺省 1 小时)到点停止后台子 Agent;`0` 不限。模型经提醒通道得知「到达寿命上限被停止」,输出文件保留。前台转来的命令、转后台的任务从转换时刻起算。每个任务可续命一次:`bash {job, action: "extend", timeoutMs?}` 与 `task_ctl {action: "extend", taskId, timeoutMs?}`,最多再加一个上限;上限不超过 2^31 − 1 毫秒(#267)。
30
+ - **`coordinator` 预设下 `bash {job, action: "wait"}` 封顶 5 秒**,与 `task_ctl wait` 一致,被封顶时回复里说明(#242)。
31
+
32
+ ### 子 Agent
33
+
34
+ - **子 Agent 的结构化报告**(#269):子会话多一个 `report` 工具,`{ state: ready | blocked | failed | waiting, summary, humanAction? }`。`humanAction` 是单槽,只放只有人能决定的事(给出替换、省略保持、`null` 清空;每次运行开始清空,`taskId` 续聊从头算)。父会话的 `task` 结果、`<task-notification>` 与 `task_ctl wait` 正文前多一行 `[report] state · summary`,有待人决定的问题时再加 `[needs a person] …` 与固定规则句「Relay this question to the user verbatim; do not answer it yourself.」;`details.report`、`TaskInfo.report`、`subagent_update{kind:"report"}` 与 `subagent_end.report` 带同一份值(都是可选字段,`RPC_PROTOCOL_VERSION` 不变)。Agent 栏、`/tasks`、工具行下的状态行与终端程序状态(`blocked:question`)显示状态与问题,父模型没转达人也看得到;ACP 客户端在发起的 `task` 调用上收到 `_meta.ama.report`。外部 Agent 映射 `refusal` → failed、`max_tokens` / `max_turn_requests` → blocked,`end_turn` 不映射。没调用 `report` 时一切与原来逐字节相同。`report` 是 `task` 的伴随工具(父会话里也在表里、运行时拒绝,子会话工具表与父保持一致、缓存前缀照常复用);`default + task` 与 `codemode-only` 的提示预算放宽到 2300 / 1950 token(2300 含 #266 / #267 的 `extend` 动作)。见 [docs/guides/agents.md](docs/guides/agents.md)。
35
+ - **修复:停止过的子 Agent 续聊后不再误报 `aborted`**:`task_ctl stop` 或到达寿命上限被停止后,用 `taskId` 续聊 ama 子会话、这次正常完成时结果是 `completed`(并发 `<task-notification>`);此前 runner 一直拿第一次运行那个已经中止的信号判定新一次运行。现在每次运行有自己的中止信号:`stop` 与父回合中止只结束当前这一次,之后的续聊从头开始(#278)。
36
+
7
37
  ## 0.15.1(2026-11-06)
8
38
 
9
39
  ### 维护
@@ -0,0 +1,23 @@
1
+ /**
2
+ * 异常中断后的恢复提醒(#268):判定在 `session/unclean-end.ts`,这里只管「何时注入、注入什么」。
3
+ *
4
+ * - 会话构造时取样一次(`armed`):文件刚打开、还没有新条目;新会话分支为空永不命中,运行中 `/tree`
5
+ * 挪叶子也不会触发。
6
+ * - 第一次 `beforePrompts` 时重新判定当前分支(resume 后先 `/compact`、`/tree` 仍能对上),仍不干净且
7
+ * T 里没有带 `details.recovery` 的提醒 → 给出正文;无论结果如何之后不再尝试。
8
+ * - 文本固定英文,不 import i18n;经 `ama.reminder` 通道追加在尾部,系统提示与工具表不变。
9
+ */
10
+ import type { SessionManager } from "../session/manager.js";
11
+ import { type UncleanEnd } from "../session/unclean-end.js";
12
+ /** 注入的 `custom_message{ama.reminder}` 的 `details`(判定据此识别「已提醒」)。 */
13
+ export declare const RECOVERY_DETAILS: {
14
+ readonly recovery: true;
15
+ };
16
+ export declare function recoveryReminderText(unclean: UncleanEnd): string;
17
+ export declare class RecoveryReminder {
18
+ private readonly manager;
19
+ private armed;
20
+ constructor(manager: SessionManager);
21
+ /** 新提示前调用一次;返回要追加的提醒正文(只在第一次、且仍不干净时有)。 */
22
+ take(): string | undefined;
23
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * 异常中断后的恢复提醒(#268):判定在 `session/unclean-end.ts`,这里只管「何时注入、注入什么」。
3
+ *
4
+ * - 会话构造时取样一次(`armed`):文件刚打开、还没有新条目;新会话分支为空永不命中,运行中 `/tree`
5
+ * 挪叶子也不会触发。
6
+ * - 第一次 `beforePrompts` 时重新判定当前分支(resume 后先 `/compact`、`/tree` 仍能对上),仍不干净且
7
+ * T 里没有带 `details.recovery` 的提醒 → 给出正文;无论结果如何之后不再尝试。
8
+ * - 文本固定英文,不 import i18n;经 `ama.reminder` 通道追加在尾部,系统提示与工具表不变。
9
+ */
10
+ import { detectUncleanEnd } from "../session/unclean-end.js";
11
+ /** 注入的 `custom_message{ama.reminder}` 的 `details`(判定据此识别「已提醒」)。 */
12
+ export const RECOVERY_DETAILS = { recovery: true };
13
+ export function recoveryReminderText(unclean) {
14
+ const listed = unclean.tools.length === 0
15
+ ? "No tool calls were recorded in that turn."
16
+ : `Tool calls in that turn: ${unclean.tools.join("; ")}${unclean.more > 0 ? `; …and ${unclean.more} more` : ""}.`;
17
+ return ("The previous turn of this session ended abruptly (the process stopped before the turn finished; " +
18
+ `this was not a user interrupt). ${listed} ` +
19
+ "Calls marked (no result) may or may not have taken effect. Before repeating any action with " +
20
+ "external effects (pushes, PRs, comments, migrations, deployments, messages), inspect the workspace, " +
21
+ "the git history and the external state to see what already happened, then continue from there. " +
22
+ "Do not mention this reminder.");
23
+ }
24
+ export class RecoveryReminder {
25
+ manager;
26
+ armed;
27
+ constructor(manager) {
28
+ this.manager = manager;
29
+ const found = detectUncleanEnd(manager.branch());
30
+ this.armed = found !== undefined && !found.reminded;
31
+ }
32
+ /** 新提示前调用一次;返回要追加的提醒正文(只在第一次、且仍不干净时有)。 */
33
+ take() {
34
+ if (!this.armed)
35
+ return undefined;
36
+ this.armed = false;
37
+ const found = detectUncleanEnd(this.manager.branch());
38
+ if (found === undefined || found.reminded)
39
+ return undefined;
40
+ return recoveryReminderText(found);
41
+ }
42
+ }
@@ -16,10 +16,15 @@
16
16
  * 压缩后回落再重新计;
17
17
  * 4. `budget`:limits 的回合或费用用掉 ≥ 80%(剩余 < 20%)时每次运行各一次;
18
18
  * 5. 后台命令退出(不可关):`bash{background}` 的任务退出且模型还没经 wait / output 看到 →
19
- * 「后台命令 bgN 已退出(码 N)」。
19
+ * 「后台命令 bgN 已退出(码 N)」;[#267] 到达寿命上限被停止的后台命令与后台子 Agent也在这里报告
20
+ * (发起停止的不是模型,所以不像 stop 那样视为已知)。
21
+ *
22
+ * 6. 异常中断恢复(#268,recovery-reminder.ts,不可关):resume 时上一轮没有正常结束(判定见
23
+ * session/unclean-end.ts)→ 第一次新提示前提醒一次,列出上一轮的工具与目标,要求先核实现场再重复
24
+ * 外部动作;消息带 `details.recovery`,第二次 resume 据此不重复。
20
25
  *
21
26
  * 后台任务表的生命周期也挂在这里:任务事件转成 `background_job`,会话 dispose 时回收进程树。
22
- * task 子会话(depth > 0)只装后台任务部分。
27
+ * task 子会话(depth > 0)只装后台任务与恢复提醒。
23
28
  */
24
29
  import type { RemindersConfig } from "../config/types-w5.js";
25
30
  import type { AgentMessage } from "../session/types.js";
@@ -52,8 +57,9 @@ export interface RemindersDeps {
52
57
  } | undefined;
53
58
  }
54
59
  export declare function jobExitText(job: Job): string;
55
- export declare function reminderMessage(text: string): AgentMessage;
60
+ export declare function reminderMessage(text: string, details?: unknown): AgentMessage;
56
61
  /**
57
- * 提醒扩展。主会话:全部提醒 + 后台任务生命周期;子会话:只管后台任务(事件与回收)。
62
+ * 提醒扩展。主会话:全部提醒 + 后台任务生命周期;子会话:只管后台任务(事件与回收)与恢复提醒
63
+ * (`taskId` 续聊重开被打断的子会话时,子会话自己拿到它)。
58
64
  */
59
65
  export declare function createRemindersExtension(core: SessionCore, settings?: RemindersSettings, deps?: RemindersDeps): SessionExtension;
@@ -16,19 +16,28 @@
16
16
  * 压缩后回落再重新计;
17
17
  * 4. `budget`:limits 的回合或费用用掉 ≥ 80%(剩余 < 20%)时每次运行各一次;
18
18
  * 5. 后台命令退出(不可关):`bash{background}` 的任务退出且模型还没经 wait / output 看到 →
19
- * 「后台命令 bgN 已退出(码 N)」。
19
+ * 「后台命令 bgN 已退出(码 N)」;[#267] 到达寿命上限被停止的后台命令与后台子 Agent也在这里报告
20
+ * (发起停止的不是模型,所以不像 stop 那样视为已知)。
21
+ *
22
+ * 6. 异常中断恢复(#268,recovery-reminder.ts,不可关):resume 时上一轮没有正常结束(判定见
23
+ * session/unclean-end.ts)→ 第一次新提示前提醒一次,列出上一轮的工具与目标,要求先核实现场再重复
24
+ * 外部动作;消息带 `details.recovery`,第二次 resume 据此不重复。
20
25
  *
21
26
  * 后台任务表的生命周期也挂在这里:任务事件转成 `background_job`,会话 dispose 时回收进程树。
22
- * task 子会话(depth > 0)只装后台任务部分。
27
+ * task 子会话(depth > 0)只装后台任务与恢复提醒。
23
28
  */
24
29
  import { execFileSync } from "node:child_process";
25
30
  import { statSync } from "node:fs";
26
31
  import { resolve } from "node:path";
27
32
  import { estimateProjectedTokens } from "../compaction/estimate.js";
33
+ import { taskControl } from "../agents/task-control.js";
28
34
  import { buildProjection } from "../session/projection.js";
29
35
  import { disposeSessionJobs, jobsForSession } from "../tools/background-jobs.js";
30
36
  import { TODO_CUSTOM_TYPE, parseTodoState, renderTodoList } from "../tools/todo.js";
31
37
  import { budgetOf } from "./limits.js";
38
+ import { expiredTaskText } from "./subagent-lifetime.js";
39
+ import { minutesOf } from "../tools/timers.js";
40
+ import { RECOVERY_DETAILS, RecoveryReminder } from "./recovery-reminder.js";
32
41
  import { setBatchSuffixSource } from "./tool-runner.js";
33
42
  export const REMINDER_CUSTOM_TYPE = "ama.reminder";
34
43
  export const DEFAULT_TODO_REMINDER_TURNS = 10;
@@ -102,6 +111,8 @@ class Reminders {
102
111
  baseline = new Map();
103
112
  /** toolCallId → 文件工具的绝对路径。 */
104
113
  pendingPaths = new Map();
114
+ /** [#268] resume 后的一次性恢复提醒。 */
115
+ recovery;
105
116
  constructor(core, settings, deps) {
106
117
  this.core = core;
107
118
  const r = settings.reminders ?? {};
@@ -114,6 +125,7 @@ class Reminders {
114
125
  this.todoEvery = settings.todoEvery ?? DEFAULT_TODO_REMINDER_TURNS;
115
126
  this.stat = deps.stat ?? defaultStat;
116
127
  this.diffStat = deps.diffStat ?? defaultDiffStat;
128
+ this.recovery = new RecoveryReminder(core.manager);
117
129
  }
118
130
  onEvent(event) {
119
131
  switch (event.type) {
@@ -123,7 +135,7 @@ class Reminders {
123
135
  case "agent_start": {
124
136
  const signal = this.core.agent.signal;
125
137
  if (signal !== undefined)
126
- setBatchSuffixSource(signal, () => this.collect(true));
138
+ setBatchSuffixSource(signal, () => this.collect(true)?.text);
127
139
  return;
128
140
  }
129
141
  case "message_end":
@@ -161,24 +173,34 @@ class Reminders {
161
173
  return;
162
174
  }
163
175
  }
164
- /** 到期提醒的正文(没有返回 undefined);`inRun` = 工具批次尾部(预算提醒只在 run 中有意义)。 */
176
+ /**
177
+ * 到期提醒的正文(没有返回 undefined);`inRun` = 工具批次尾部(预算提醒只在 run 中有意义,
178
+ * 恢复提醒只在新提示前)。`recovery` 表示正文含恢复提醒(消息要带 `details.recovery`)。
179
+ */
165
180
  collect(inRun) {
166
181
  const lines = [];
182
+ const recovery = inRun ? undefined : this.recovery.take();
167
183
  const jobs = this.jobLines();
168
184
  const todo = this.todoLine();
169
185
  const files = this.fileLine();
170
186
  const context = this.contextLine();
171
187
  const budget = inRun ? this.budgetLine() : undefined;
172
- for (const line of [jobs, todo, files, context, budget])
188
+ for (const line of [recovery, jobs, todo, files, context, budget])
173
189
  if (line !== undefined)
174
190
  lines.push(line);
175
- return lines.length === 0 ? undefined : wrap(lines);
191
+ if (lines.length === 0)
192
+ return undefined;
193
+ return { text: wrap(lines), recovery: recovery !== undefined };
176
194
  }
177
195
  jobLines() {
178
- const exited = jobsForSession(this.core.manager.id).takeExited();
179
- if (exited.length === 0)
180
- return undefined;
181
- return exited.map((job) => jobExitText(job)).join("\n");
196
+ const sessionId = this.core.manager.id;
197
+ const lines = jobsForSession(sessionId)
198
+ .takeExited()
199
+ .map((job) => jobExitText(job));
200
+ // [#267] 到点被停止的后台子 Agent(TaskNotifier 不投递 aborted,这里补一句)
201
+ for (const task of taskControl(sessionId)?.takeExpired() ?? [])
202
+ lines.push(expiredTaskText(task));
203
+ return lines.length === 0 ? undefined : lines.join("\n");
182
204
  }
183
205
  todoLine() {
184
206
  if (!this.on.todo || this.todoEvery <= 0 || this.sinceTodo < this.todoEvery)
@@ -279,20 +301,32 @@ class Reminders {
279
301
  }
280
302
  }
281
303
  export function jobExitText(job) {
282
- const how = job.status === "stopped" ? "was stopped" : `exited with code ${job.exitCode ?? "unknown"}`;
304
+ const how = job.status === "stopped"
305
+ ? job.expired === true
306
+ ? `was stopped at its lifetime cap (${minutesOf(job.lifetime?.maxMs ?? 0)}, tools.bashBackgroundMaxMs)`
307
+ : "was stopped"
308
+ : `exited with code ${job.exitCode ?? "unknown"}`;
283
309
  return `Background job ${job.id} (\`${job.command}\`) ${how}; output: ${job.outputPath} (bash {"job":"${job.id}","action":"output"}).`;
284
310
  }
285
- export function reminderMessage(text) {
311
+ export function reminderMessage(text, details) {
286
312
  return {
287
313
  role: "custom",
288
314
  customType: REMINDER_CUSTOM_TYPE,
289
315
  content: text,
290
316
  display: false,
317
+ ...(details === undefined ? {} : { details }),
291
318
  timestamp: Date.now(),
292
319
  };
293
320
  }
321
+ /** [#268] 把 `collect(false)` 的结果变成要追加的消息(含恢复提醒时带 `details.recovery`)。 */
322
+ function promptReminders(collected) {
323
+ if (collected === undefined)
324
+ return [];
325
+ return [reminderMessage(collected.text, collected.recovery ? RECOVERY_DETAILS : undefined)];
326
+ }
294
327
  /**
295
- * 提醒扩展。主会话:全部提醒 + 后台任务生命周期;子会话:只管后台任务(事件与回收)。
328
+ * 提醒扩展。主会话:全部提醒 + 后台任务生命周期;子会话:只管后台任务(事件与回收)与恢复提醒
329
+ * (`taskId` 续聊重开被打断的子会话时,子会话自己拿到它)。
296
330
  */
297
331
  export function createRemindersExtension(core, settings = {}, deps = {}) {
298
332
  const sessionId = core.manager.id;
@@ -312,16 +346,22 @@ export function createRemindersExtension(core, settings = {}, deps = {}) {
312
346
  offJobs();
313
347
  void disposeSessionJobs(sessionId);
314
348
  };
315
- if (core.depth > 0)
316
- return { id: "reminders", dispose };
349
+ if (core.depth > 0) {
350
+ const recovery = new RecoveryReminder(core.manager);
351
+ return {
352
+ id: "reminders",
353
+ beforePrompts() {
354
+ const text = recovery.take();
355
+ return promptReminders(text === undefined ? undefined : { text: wrap([text]), recovery: true });
356
+ },
357
+ dispose,
358
+ };
359
+ }
317
360
  const reminders = new Reminders(core, settings, deps);
318
361
  return {
319
362
  id: "reminders",
320
363
  onEvent: (event) => reminders.onEvent(event),
321
- beforePrompts() {
322
- const text = reminders.collect(false);
323
- return text === undefined ? [] : [reminderMessage(text)];
324
- },
364
+ beforePrompts: () => promptReminders(reminders.collect(false)),
325
365
  dispose,
326
366
  };
327
367
  }
@@ -25,6 +25,7 @@ import { PLAN_APPROVED_PROMPT, PLAN_APPROVED_TYPE, PLAN_MODE_BRIEF, PLAN_MODE_EX
25
25
  import { PLAN_CUSTOM_TYPE, PLAN_STATE_CUSTOM_TYPE, currentTodos, executionMode, latestPlan, latestPlanState, maxPlanVersion, resolvePlanDirectory, writePlanFile, } from "../plan/store.js";
26
26
  import { APPROVE_REPLY, PLAN_NOTICE_TYPE, registerPlanController, } from "../plan/controller.js";
27
27
  import { TODO_CUSTOM_TYPE } from "../tools/todo.js";
28
+ import { applyPermissionMode } from "./session-settings.js";
28
29
  import { msg } from "../i18n/index.js";
29
30
  export function createPlanExtensionFactory(options) {
30
31
  return ({ core }) => (core.depth > 0 ? undefined : new PlanExtension(core, options));
@@ -422,10 +423,8 @@ class PlanExtension {
422
423
  const session = this.handle();
423
424
  if (session !== undefined)
424
425
  session.setPermissionMode(mode);
425
- else {
426
- this.permission?.setMode(mode);
427
- this.core.emit({ type: "permission_mode_changed", mode });
428
- }
426
+ else
427
+ applyPermissionMode(this.core.options, mode, this.core);
429
428
  }
430
429
  }
431
430
  finally {
@@ -17,6 +17,11 @@ import type { SystemPromptInput } from "./system-prompt.js";
17
17
  */
18
18
  export declare function providerStream(providers: ProviderRegistryApi): StreamFn;
19
19
  export type StaticSystemInput = Omit<SystemPromptInput, "tools" | "cwd">;
20
+ /**
21
+ * [#271] 切换权限模式:管线改模式 → 审批链按新模式重判在等的与排队的审批 → 发 `permission_mode_changed`
22
+ * (带自动放行 / 拒绝的条数)。被自动作答的请求随后各自发 `permission_resolved{reason:"mode_changed"}`。
23
+ */
24
+ export declare function applyPermissionMode(options: Pick<AgentSessionOptions, "permission" | "brokers">, mode: PermissionMode, core: Pick<SessionCore, "emit">): void;
20
25
  export interface SessionSettingsDeps {
21
26
  /** 会话本身(构造完成后才会被调用)。 */
22
27
  core: SessionCore;
@@ -7,6 +7,7 @@
7
7
  */
8
8
  import { followChatGptLogin } from "../auth/chatgpt/follow.js";
9
9
  import { AmaError } from "../errors.js";
10
+ import { reevaluatePendingApprovals } from "../permissions/broker.js";
10
11
  import { appendModelChange, findModelOrThrow, sessionStartEvent } from "./session-sync.js";
11
12
  /**
12
13
  * 按模型的协议分派到已注册的实现(会话流的最内层)。ChatGPT 订阅模型先按本次 token 的登录方式改渠道
@@ -22,6 +23,19 @@ export function providerStream(providers) {
22
23
  return api.stream(model, context, streamOptions);
23
24
  };
24
25
  }
26
+ /**
27
+ * [#271] 切换权限模式:管线改模式 → 审批链按新模式重判在等的与排队的审批 → 发 `permission_mode_changed`
28
+ * (带自动放行 / 拒绝的条数)。被自动作答的请求随后各自发 `permission_resolved{reason:"mode_changed"}`。
29
+ */
30
+ export function applyPermissionMode(options, mode, core) {
31
+ options.permission?.setMode(mode);
32
+ const { allowed, denied } = reevaluatePendingApprovals(options.brokers, mode);
33
+ core.emit({
34
+ type: "permission_mode_changed",
35
+ mode,
36
+ ...(allowed + denied > 0 ? { reevaluated: { allowed, denied } } : {}),
37
+ });
38
+ }
25
39
  export class SessionSettings {
26
40
  options;
27
41
  deps;
@@ -66,8 +80,7 @@ export class SessionSettings {
66
80
  this.deps.core.emit({ type: "thinking_level_changed", level });
67
81
  }
68
82
  setPermissionMode(mode) {
69
- this.options.permission?.setMode(mode);
70
- this.deps.core.emit({ type: "permission_mode_changed", mode });
83
+ applyPermissionMode(this.options, mode, this.deps.core);
71
84
  }
72
85
  setActiveTools(names) {
73
86
  const unknown = names.filter((name) => !this.allTools.has(name));
@@ -20,6 +20,9 @@
20
20
  * [RW-B] 父的检查点钩子(worktree 里运行时不记);[W3-C1b] 子会话命中与重计费汇总进父。
21
21
  * - [W6-A] 句柄外露 `observe` / `entries`(子 Agent 视图跟随)与 `message`(视图里直接发的消息,
22
22
  * `origin: "direct"`:运行中 followUp,空闲开新一轮);一轮收尾时才入队、没赶上的 followUp 接着再跑一轮。
23
+ * - [#269] `report` 工具总在子会话可用(`CHILD_ONLY_TOOLS`,白名单 / 黑名单与 fork 的 `unavailableTools`
24
+ * 都不去掉);每次 `report` 调用(含 codemode 内层)按运行折叠成槽,发 `report` 进度事件,运行结束放进
25
+ * `SubagentResult.report`(agents/report.ts)。
23
26
  */
24
27
  import type { CheckpointHooks } from "../checkpoints/types.js";
25
28
  import type { PermissionPipelineApi } from "../permissions/types.js";
@@ -35,6 +38,8 @@ export { DEFAULT_SUBAGENT_CONCURRENCY, SubagentPool, TASK_CUSTOM_TYPE };
35
38
  export declare const DEFAULT_SUBAGENT_MAX_TURNS = 30;
36
39
  /** 子会话里保留在工具表、运行时拒绝的名字(深度 ≤ 1)。 */
37
40
  export declare const PARENT_ONLY_TOOLS: readonly string[];
41
+ /** [#269] 子会话总是可用的工具(类型白名单 / 黑名单不能去掉;父会话里它运行时被拒)。 */
42
+ export declare const CHILD_ONLY_TOOLS: readonly string[];
38
43
  export declare const FINAL_REPORT_PROMPT: string;
39
44
  export interface SubagentParent extends RegistryHost {
40
45
  readonly options: AgentSessionOptions;
@@ -20,11 +20,16 @@
20
20
  * [RW-B] 父的检查点钩子(worktree 里运行时不记);[W3-C1b] 子会话命中与重计费汇总进父。
21
21
  * - [W6-A] 句柄外露 `observe` / `entries`(子 Agent 视图跟随)与 `message`(视图里直接发的消息,
22
22
  * `origin: "direct"`:运行中 followUp,空闲开新一轮);一轮收尾时才入队、没赶上的 followUp 接着再跑一轮。
23
+ * - [#269] `report` 工具总在子会话可用(`CHILD_ONLY_TOOLS`,白名单 / 黑名单与 fork 的 `unavailableTools`
24
+ * 都不去掉);每次 `report` 调用(含 codemode 内层)按运行折叠成槽,发 `report` 进度事件,运行结束放进
25
+ * `SubagentResult.report`(agents/report.ts)。
23
26
  */
24
27
  import { AmaError } from "../errors.js";
25
28
  import { PermissionPipeline } from "../permissions/pipeline.js";
26
29
  import { SessionManager } from "../session/manager.js";
30
+ import { REPORT_TOOL } from "../tools/report.js";
27
31
  import { agentRole } from "../agents/builtin.js";
32
+ import { foldReport } from "../agents/report.js";
28
33
  import { ZERO_USAGE } from "./loop.js";
29
34
  import { forkBrief, forkPlan, requestedContext } from "./subagent-fork.js";
30
35
  import { DEFAULT_SUBAGENT_CONCURRENCY, SubagentPool, TASK_CUSTOM_TYPE, subagentRegistryFor, } from "./subagent-registry.js";
@@ -32,6 +37,8 @@ export { DEFAULT_SUBAGENT_CONCURRENCY, SubagentPool, TASK_CUSTOM_TYPE };
32
37
  export const DEFAULT_SUBAGENT_MAX_TURNS = 30;
33
38
  /** 子会话里保留在工具表、运行时拒绝的名字(深度 ≤ 1)。 */
34
39
  export const PARENT_ONLY_TOOLS = ["task", "task_ctl"];
40
+ /** [#269] 子会话总是可用的工具(类型白名单 / 黑名单不能去掉;父会话里它运行时被拒)。 */
41
+ export const CHILD_ONLY_TOOLS = [REPORT_TOOL];
35
42
  export const FINAL_REPORT_PROMPT = "You have reached the turn limit for this task. Do not call any tools. Reply now with your " +
36
43
  "final report: what you did, key findings, and what is left unfinished.";
37
44
  /** 子会话的 broker:请求带上发起方上下文(对话框标 `[task:<agent>]`),其余原样交给父链。 */
@@ -82,18 +89,30 @@ export async function runSubagent(parent, request, _pool, createChild) {
82
89
  const registry = subagentRegistryFor(parent);
83
90
  return registry.run(request, (spec) => createAmaRunner(parent, spec, createChild));
84
91
  }
85
- /** 活动集:缺省 = 父活动集(含 task / task_ctl,工具表对齐);白名单 / 黑名单时按名过滤。 */
92
+ /**
93
+ * 活动集:缺省 = 父活动集(含 task / task_ctl,工具表对齐);白名单 / 黑名单时按名过滤。
94
+ * [#269] `report` 只要父注册了就总在(白名单 / 黑名单都不能去掉)。
95
+ */
86
96
  function childToolNames(parent, spec, base) {
87
97
  const available = new Set((parent.options.tools ?? []).map((tool) => tool.name));
88
98
  const all = [...(base ?? available)].filter((name) => available.has(name));
89
99
  const allow = spec.request.tools ?? spec.agent.tools;
90
- if (allow !== undefined)
91
- return allow.filter((name) => available.has(name) && !PARENT_ONLY_TOOLS.includes(name));
100
+ if (allow !== undefined) {
101
+ return withChildOnly(allow.filter((name) => available.has(name) && !PARENT_ONLY_TOOLS.includes(name)), available);
102
+ }
92
103
  const deny = spec.agent.disallowedTools;
93
- if (deny !== undefined)
94
- return all.filter((name) => !deny.includes(name) && !PARENT_ONLY_TOOLS.includes(name));
104
+ if (deny !== undefined) {
105
+ return withChildOnly(all.filter((name) => !deny.includes(name) && !PARENT_ONLY_TOOLS.includes(name)), available);
106
+ }
95
107
  return all;
96
108
  }
109
+ /** [#269] 白名单 / 黑名单过滤之后补回子会话总是可用的工具(父注册了才补)。 */
110
+ function withChildOnly(names, available) {
111
+ for (const name of CHILD_ONLY_TOOLS)
112
+ if (available.has(name) && !names.includes(name))
113
+ names.push(name);
114
+ return names;
115
+ }
97
116
  /** ama 自己的子会话 runner(同进程)。 */
98
117
  export function createAmaRunner(parent, spec, createChild) {
99
118
  return {
@@ -150,7 +169,9 @@ async function startAmaChild(parent, spec, createChild, run) {
150
169
  const allowed = childToolNames(parent, spec, base.activeTools);
151
170
  // fork:工具表 = 父活动集(前缀不变),类型限制的工具在执行层拒绝
152
171
  const inherited = base.activeTools ?? (parent.options.tools ?? []).map((tool) => tool.name);
153
- const unavailable = inherited.filter((name) => !allowed.includes(name) && !PARENT_ONLY_TOOLS.includes(name));
172
+ const unavailable = inherited.filter((name) => !allowed.includes(name) &&
173
+ !PARENT_ONLY_TOOLS.includes(name) &&
174
+ !CHILD_ONLY_TOOLS.includes(name));
154
175
  // #150:<task> 里也列出按深度拒绝的 task / task_ctl(执行层的拒绝文案不变)
155
176
  const briefUnavailable = [
156
177
  ...unavailable,
@@ -184,9 +205,20 @@ async function startAmaChild(parent, spec, createChild, run) {
184
205
  const child = createChild(options);
185
206
  let turns = 0;
186
207
  let toolUse = false;
208
+ /** [#269] 这次运行的报告槽(runOnce 开始清空;codemode 内层调用的 report 同样折叠)。 */
209
+ let report;
187
210
  const unsubscribe = child.subscribe((event) => {
188
211
  if (event.type === "tool_execution_start" && event.parentToolCallId === undefined)
189
212
  run.onEvent({ type: "tool", toolName: event.toolName, status: "started" });
213
+ else if (event.type === "tool_execution_end" &&
214
+ event.toolName === REPORT_TOOL &&
215
+ !event.isError) {
216
+ const details = event.result.details;
217
+ if (details?.report !== undefined) {
218
+ report = foldReport(report, details.report);
219
+ run.onEvent({ type: "report", report });
220
+ }
221
+ }
190
222
  else if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta")
191
223
  run.onEvent({ type: "text", delta: event.assistantMessageEvent.delta });
192
224
  else if (event.type === "turn_end") {
@@ -204,7 +236,18 @@ async function startAmaChild(parent, spec, createChild, run) {
204
236
  });
205
237
  if (mode !== undefined)
206
238
  run.onEvent({ type: "context", mode });
207
- const onAbort = () => void child.abort();
239
+ /**
240
+ * [#278] 每次运行一个 controller:`stop()` 只中止当前这一次。`run.signal` 是首次启动那次运行的信号,
241
+ * 续聊(句柄复用)时注册表换了新 controller 并经 `stop()` 传达,所以终态只看本次运行的信号,
242
+ * 不再读已经陈旧的 `run.signal`(否则被停过一次的任务续聊后永远是 aborted)。
243
+ */
244
+ let runController;
245
+ let firstRun = true;
246
+ const stopRun = () => {
247
+ runController?.abort();
248
+ return child.abort();
249
+ };
250
+ const onAbort = () => void stopRun().catch(() => undefined);
208
251
  run.signal.addEventListener("abort", onAbort, { once: true });
209
252
  let billed = { cacheRead: 0, prompt: 0, reBilled: 0 };
210
253
  let active = false;
@@ -213,9 +256,17 @@ async function startAmaChild(parent, spec, createChild, run) {
213
256
  const runOnce = async (prompt, origin) => {
214
257
  const startTurns = turns;
215
258
  let error;
259
+ report = undefined;
216
260
  active = true;
261
+ const controller = new AbortController();
262
+ runController = controller;
263
+ const { signal } = controller;
264
+ // 首次运行前请求信号就已中止:按 aborted 收尾;之后的运行不再看 run.signal
265
+ if (firstRun && run.signal.aborted)
266
+ controller.abort();
267
+ firstRun = false;
217
268
  try {
218
- if (run.signal.aborted)
269
+ if (signal.aborted)
219
270
  throw new AmaError("aborted", "aborted");
220
271
  await child.prompt(prompt, origin === undefined ? {} : { origin });
221
272
  // [W6-A] 收尾阶段才入队的 followUp(只可能来自视图)留在队列里:接着再跑一轮
@@ -223,7 +274,7 @@ async function startAmaChild(parent, spec, createChild, run) {
223
274
  while (forced.length > 0)
224
275
  await forced.shift();
225
276
  const left = child.clearQueue?.().followUp ?? [];
226
- if (left.length === 0 || run.signal.aborted)
277
+ if (left.length === 0 || signal.aborted)
227
278
  break;
228
279
  await child.prompt(left.join("\n\n"), { origin: "direct" });
229
280
  }
@@ -232,7 +283,7 @@ async function startAmaChild(parent, spec, createChild, run) {
232
283
  error = caught instanceof Error ? caught.message : String(caught);
233
284
  }
234
285
  active = false;
235
- const exhausted = error === undefined && !run.signal.aborted && turns - startTurns >= maxTurns && toolUse;
286
+ const exhausted = error === undefined && !signal.aborted && turns - startTurns >= maxTurns && toolUse;
236
287
  if (exhausted) {
237
288
  options.maxTurns = 1;
238
289
  try {
@@ -245,9 +296,11 @@ async function startAmaChild(parent, spec, createChild, run) {
245
296
  options.maxTurns = maxTurns;
246
297
  }
247
298
  }
248
- const result = collect(child, error, exhausted, run.signal.aborted);
299
+ const result = collect(child, error, exhausted, signal.aborted);
249
300
  if (mode !== undefined)
250
301
  result.context = mode;
302
+ if (report !== undefined)
303
+ result.report = report;
251
304
  billed = addCache(parent, child.getStats(), billed);
252
305
  const file = manager.file();
253
306
  if (file !== undefined)
@@ -287,7 +340,7 @@ async function startAmaChild(parent, spec, createChild, run) {
287
340
  await child.followUp(text, { origin: "direct" });
288
341
  },
289
342
  wait: () => current,
290
- stop: () => child.abort(),
343
+ stop: stopRun,
291
344
  dispose: async () => {
292
345
  run.signal.removeEventListener("abort", onAbort);
293
346
  unsubscribe();
@@ -11,13 +11,15 @@
11
11
  * `preview`,RPC 客户端可直接显示。
12
12
  */
13
13
  import type { ToolCallBlock } from "../ai/types.js";
14
- import type { ApprovalDecision, ApprovalRequest } from "../permissions/types.js";
14
+ import type { ApprovalDecision, ApprovalRequest, ModeReevaluationOutcome } from "../permissions/types.js";
15
15
  import type { ToolContext, ToolResult } from "../tools/types.js";
16
16
  import type { SessionCore } from "./session-core.js";
17
17
  import { type ToolRunnerOptions } from "./tool-runner.js";
18
18
  import type { NestedCallInfo, ToolCallGate, ToolCallGateContext } from "./types.js";
19
19
  /** 审批链:依次问每个 broker,第一个给出决定的为准;全部弃权 → deny。 */
20
20
  export declare function requestApproval(core: SessionCore, request: ApprovalRequest, signal: AbortSignal): Promise<ApprovalDecision>;
21
+ /** [#271] 模式切换导致拒绝时给模型的说明(固定英文):切到了哪个模式 + 管线的说明。 */
22
+ export declare function modeChangedDenial(toolName: string, outcome: ModeReevaluationOutcome): string;
21
23
  export declare function gateToolCall(core: SessionCore, call: ToolCallBlock, ctx: ToolCallGateContext): Promise<ToolCallGate>;
22
24
  export declare function afterToolCall(core: SessionCore, call: ToolCallBlock, result: ToolResult, parent?: NestedCallInfo): Promise<ToolResult>;
23
25
  export declare function createToolContext(core: SessionCore, runner: ToolRunnerOptions, call: ToolCallBlock, signal: AbortSignal, onUpdate: (partial: string) => void): ToolContext;