@armadra/agent 0.15.1 → 0.17.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 +3 -3
@@ -1,33 +1,31 @@
1
1
  /**
2
2
  * 子 Agent 任务注册表(docs/history/wave5-plan.md §7.3–§7.6,D13、D23–D24)。[W5-G]
3
3
  *
4
- * 每个根会话一份(按会话 id 登记;compose-agents.ts 的扩展在会话构造时建,SDK / 测试直接构造的
5
- * 会话在首次 task 时以缺省环境懒建)。职责:
6
- * - 解析类型(catalog)→ 选 runner:ama 子会话(session-subagent.ts 的工厂)或外部 runner(W5-E /
7
- * 宿主,经 `env.runners`);同一 `task(agent=…)` 入口;
8
- * - 并发池(`subagents.maxConcurrent`,缺省 4)+ 排队上限(`maxPending`,缺省 16,超出报错不要重试);
9
- * - 前台(等结果)/ 后台(立即返回 taskId,完成后 `<task-notification>` 走父会话 followUp 队列);
10
- * - `taskId` 续聊:句柄保留 4 个(`subagents.retainSessions`,LRU,释放的只是内存,JSONL 永在),被释放或 resume 后按会话
11
- * 文件 / 外部会话 id 重新接上;
12
- * - 结果 > 50 KB 保留头尾并全文落 `outputs/`;轮数耗尽加说明;worktree 隔离;
13
- * - 事件 `subagent_start / update / end`;父会话 `custom{ama.task}` 记任务快照(带 `status`),
14
- * resume 时据此重建(未完成标 `interrupted`)。
15
- * - [W6-A] 子 Agent 视图的 `live()` / `message()`(实现在 subagent-direct.ts)。
16
- * - [W7-B1] 缺省后台、前台转后台 `background()`、通知投递与 `settled()`(subagent-background.ts)。
4
+ * 每个根会话一份(按会话 id 登记;compose-agents.ts 的扩展在会话构造时建,SDK / 测试直接构造的会话在首次
5
+ * task 时以缺省环境懒建)。职责:解析类型(catalog)→ 选 runner(ama 子会话或 `env.runners` 的外部 / 宿主
6
+ * runner);并发池(`subagents.maxConcurrent`,缺省 4)+ 排队上限(`maxPending`,缺省 16,超出报错不要重试);
7
+ * 前台(等结果)/ 后台(立即返回 taskId,完成后 `<task-notification>` 走父会话 followUp 队列);`taskId` 续聊
8
+ * (句柄保留 `subagents.retainSessions` 个,LRU,JSONL 永在,释放后按会话文件 / 外部会话 id 重接);结果 > 50 KB
9
+ * 保留头尾并全文落 `outputs/`;worktree 隔离;事件 `subagent_start / update / end`,父会话 `custom{ama.task}` 记
10
+ * 快照、resume 时重建(未完成标 `interrupted`)。[W6-A] 视图 `live()` / `message()`(subagent-direct.ts);
11
+ * [W7-B1] 缺省后台、转后台 `background()`、通知与 `settled()`(subagent-background.ts);[#267] 后台寿命上限
12
+ * `extend()` / `takeExpired()`(subagent-lifetime.ts);[#269] 结构化报告:运行开始清 `info.report`,runner 的
13
+ * `report` 事件即时进快照并发 `subagent_update`,结束时以结果为准加 `[report]` 行(agents/report.ts)。
17
14
  */
18
15
  import { tmpdir } from "node:os";
19
16
  import { join } from "node:path";
20
17
  import { AmaError } from "../errors.js";
21
18
  import { DEFAULT_AGENT } from "../agents/builtin.js";
22
19
  import { AgentCatalog, resolveAgentModel } from "../agents/catalog.js";
23
- import { MAX_TURNS_NOTE, capTaskText, writeTaskOutput } from "../agents/result.js";
24
- import { SubagentPool, TASK_CUSTOM_TYPE, applyRunnerEvent, flushText, newRecord, rebuildRecords, recordData, startEvent, taskStats, } from "../agents/task-record.js";
20
+ import { capTaskText, decorateTaskText, writeTaskOutput } from "../agents/result.js";
21
+ import { SubagentPool, TASK_CUSTOM_TYPE, TERMINAL_STATUSES, failedResult as failed, flushText, newRecord, rebuildRecords, recordData, taskStats, } from "../agents/task-record.js";
25
22
  import { registerTaskControl, unregisterTaskControl, } from "../agents/task-control.js";
26
- import { ZERO_USAGE } from "./loop.js";
27
23
  import { createWorktree, finishWorktree } from "./worktree.js";
28
24
  import { appendTraceEntry } from "./session-trace-writer.js";
29
25
  import { directMessage, drainDirect, liveOf } from "./subagent-direct.js";
30
26
  import { TaskNotifier, WaitDetach, backgroundRecords, blockingTasks, foregroundWaiter, settleTasks, startedResult, waitForTask, } from "./subagent-background.js";
27
+ import { startHandle } from "./subagent-handle.js";
28
+ import { armLifetime, clearLifetime, extendLifetime, takeExpiredTasks, } from "./subagent-lifetime.js";
31
29
  export const DEFAULT_SUBAGENT_CONCURRENCY = 4;
32
30
  export const DEFAULT_MAX_PENDING = 16;
33
31
  export const DEFAULT_RETAINED = 4;
@@ -54,16 +52,6 @@ export function subagentRegistryFor(host, env = { catalog: new AgentCatalog() })
54
52
  registerTaskControl(host.manager.id, registry);
55
53
  return registry;
56
54
  }
57
- function failed(text) {
58
- return { text, usage: { ...ZERO_USAGE }, stopReason: "error", isError: true, status: "failed" };
59
- }
60
- const TERMINAL = [
61
- "completed",
62
- "failed",
63
- "aborted",
64
- "max_turns",
65
- "interrupted",
66
- ];
67
55
  export class SubagentRegistry {
68
56
  host;
69
57
  env;
@@ -88,6 +76,27 @@ export class SubagentRegistry {
88
76
  now() {
89
77
  return this.env.now?.() ?? Date.now();
90
78
  }
79
+ lifetimeEnv() {
80
+ const env = { now: () => this.now() };
81
+ if (this.env.backgroundMaxMs !== undefined)
82
+ env.backgroundMaxMs = this.env.backgroundMaxMs;
83
+ if (this.env.timers !== undefined)
84
+ env.timers = this.env.timers;
85
+ return env;
86
+ }
87
+ /** [#267] 后台任务起寿命计时(从此刻起算);到点按 stop 处理。 */
88
+ armLifetime(record) {
89
+ armLifetime(record, this.lifetimeEnv(), () => record.controller?.abort());
90
+ }
91
+ /** [#267] 续命一次(task_ctl extend)。 */
92
+ extend(taskId, ms) {
93
+ const record = this.tasks.get(taskId);
94
+ return extendLifetime(record, this.lifetimeEnv(), () => record?.controller?.abort(), ms);
95
+ }
96
+ /** [#267] 到点被停止、尚未经提醒通道通知的任务。 */
97
+ takeExpired() {
98
+ return takeExpiredTasks(this.tasks.values());
99
+ }
91
100
  // -------------------------------------------------------------------------
92
101
  // 视图
93
102
  // -------------------------------------------------------------------------
@@ -136,6 +145,12 @@ export class SubagentRegistry {
136
145
  afterMs: this.env.autoBackgroundAfterMs ?? 0,
137
146
  outputFile: (id) => this.outputFileFor(id),
138
147
  });
148
+ // [#267] 转后台的任务从转换时刻起算寿命
149
+ for (const id of moved) {
150
+ const record = this.tasks.get(id);
151
+ if (record !== undefined)
152
+ this.armLifetime(record);
153
+ }
139
154
  return [...new Set([...moved, ...this.waits.detach(taskId)])];
140
155
  }
141
156
  /** [W7-B1] `-p` 收尾:等到没有运行中的任务、通知回合也已跑完;会话关闭立即返回。 */
@@ -219,6 +234,13 @@ export class SubagentRegistry {
219
234
  record.info.status = "running";
220
235
  record.info.background = background;
221
236
  delete record.info.endedAt;
237
+ // [#269] 报告槽按运行划定:续聊开始时清空上一次运行的报告
238
+ delete record.info.report;
239
+ // [#267] 上一次运行到点被停止的标记不带进这次续聊(否则这次正常结束会被误报);还没报告的保留并标 relaunched
240
+ if (record.expired?.taken === true)
241
+ delete record.expired;
242
+ else if (record.expired !== undefined)
243
+ record.expired.relaunched = true;
222
244
  record.text = "";
223
245
  if (background)
224
246
  delete record.onUpdate;
@@ -234,6 +256,7 @@ export class SubagentRegistry {
234
256
  let timer;
235
257
  const running = this.execute(record, request, ama, controller.signal).finally(() => {
236
258
  clearTimeout(timer);
259
+ clearLifetime(record, this.lifetimeEnv());
237
260
  parentSignal?.removeEventListener("abort", onParentAbort);
238
261
  delete record.foregroundWaiter;
239
262
  delete record.running;
@@ -244,6 +267,7 @@ export class SubagentRegistry {
244
267
  record.running = running;
245
268
  const file = this.outputFileFor(record.info.taskId);
246
269
  if (background) {
270
+ this.armLifetime(record);
247
271
  void running.then((result) => this.notifier.notify(record, result));
248
272
  return startedResult(record, file, running);
249
273
  }
@@ -299,56 +323,14 @@ export class SubagentRegistry {
299
323
  this.pool.release();
300
324
  }
301
325
  }
302
- async handleFor(record, request, ama, signal) {
303
- const live = record.handle;
304
- const direct = record.directNext === true;
305
- delete record.directNext;
306
- if (live !== undefined) {
307
- this.touch(record.info.taskId);
308
- this.emitStart(record, live);
309
- if (direct && live.message !== undefined)
310
- await live.message(request.prompt, "send");
311
- else
312
- await live.send(request.prompt);
313
- return live;
314
- }
315
- const ref = record.info.sessionRef;
316
- const runner = record.agent.runner === "ama"
317
- ? ama({
318
- taskId: record.info.taskId,
319
- agent: record.agent,
320
- request,
321
- ...(record.modelRef === undefined ? {} : { modelRef: record.modelRef }),
322
- cwd: record.cwd,
323
- ...(ref?.sessionFile === undefined ? {} : { resumeFile: ref.sessionFile }),
324
- isolated: record.worktree !== undefined,
325
- ...(direct ? { origin: "direct" } : {}),
326
- })
327
- : this.env.runners?.(record.agent);
328
- if (runner === undefined)
329
- throw new Error(`runner ${record.agent.runner} is not available`);
330
- const handle = await runner.start({
331
- prompt: request.prompt,
332
- cwd: record.cwd,
326
+ handleFor(record, request, ama, signal) {
327
+ return startHandle(record, request, ama, signal, {
328
+ runners: (agent) => this.env.runners?.(agent),
333
329
  mode: this.host.options.permission?.mode ?? "default",
334
- ...(record.modelRef === undefined ? {} : { model: record.modelRef }),
335
- ...(ref !== undefined && record.agent.runner !== "ama" ? { resume: ref.sessionId } : {}),
336
- ...(request.budgetUsd === undefined ? {} : { budgetUsd: request.budgetUsd }),
337
- taskId: record.info.taskId,
338
- signal,
339
- onEvent: (event) => applyRunnerEvent(record, event, this.sink()),
330
+ touch: (taskId) => this.touch(taskId),
331
+ emit: (event) => this.host.emit(event),
332
+ sink: () => this.sink(),
340
333
  });
341
- record.handle = handle;
342
- record.info.sessionRef = {
343
- runner: record.agent.runner,
344
- sessionId: handle.id,
345
- ...(handle.sessionFile === undefined ? {} : { sessionFile: handle.sessionFile }),
346
- };
347
- this.emitStart(record, handle);
348
- return handle;
349
- }
350
- emitStart(record, handle) {
351
- this.host.emit(startEvent(record, handle));
352
334
  }
353
335
  sink() {
354
336
  return {
@@ -362,7 +344,7 @@ export class SubagentRegistry {
362
344
  flushText(record, this.sink());
363
345
  const status = aborted
364
346
  ? "aborted"
365
- : result.status !== undefined && TERMINAL.includes(result.status)
347
+ : result.status !== undefined && TERMINAL_STATUSES.includes(result.status)
366
348
  ? result.status
367
349
  : result.isError
368
350
  ? "failed"
@@ -391,15 +373,16 @@ export class SubagentRegistry {
391
373
  if (outputFile !== undefined)
392
374
  info.outputFile = outputFile;
393
375
  }
394
- let text = capped.text.trim() === "" ? "(the sub-agent returned no text)" : capped.text;
395
- if (status === "max_turns")
396
- text = `${MAX_TURNS_NOTE}\n\n${text}`;
376
+ // [#269] 结构化报告:runner 给的为准(这次运行折叠后的值);没有就清掉运行中记下的
377
+ const report = result.report;
378
+ if (report === undefined)
379
+ delete info.report;
380
+ else
381
+ info.report = report;
397
382
  const outcome = record.worktreeOutcome;
398
- if (outcome?.changed === true)
399
- text += `\n\n[worktree kept: branch ${outcome.branch} at ${outcome.path ?? "?"}]\n${outcome.diffStat ?? ""}`;
400
383
  const final = {
401
384
  ...result,
402
- text,
385
+ text: decorateTaskText(capped.text, status, report, outcome),
403
386
  taskId: info.taskId,
404
387
  status,
405
388
  isError: status === "failed" || status === "aborted",
@@ -408,6 +391,8 @@ export class SubagentRegistry {
408
391
  final.outputFile = outputFile;
409
392
  if (info.sessionRef !== undefined)
410
393
  final.sessionRef = info.sessionRef;
394
+ if (report !== undefined)
395
+ final.report = report;
411
396
  record.last = final;
412
397
  this.persist(record);
413
398
  const end = {
@@ -423,6 +408,8 @@ export class SubagentRegistry {
423
408
  end.outputFile = outputFile;
424
409
  if (outcome !== undefined)
425
410
  end.worktree = { branch: outcome.branch, changed: outcome.changed };
411
+ if (report !== undefined)
412
+ end.report = report;
426
413
  this.host.emit(end);
427
414
  this.retain(info.taskId);
428
415
  return final;
@@ -36,6 +36,14 @@ export interface SystemPromptInput {
36
36
  cwd: string;
37
37
  /** 宿主 instructions(已读入的文本),按添加顺序。 */
38
38
  hostInstructions?: readonly string[];
39
+ /**
40
+ * [#270] 宿主注册的资源(`api.resources.register`):tools 节末尾追加一行列出 `scheme:// describe`,
41
+ * 按 scheme 排序;会话开始时固定(之后不再注册)。没有时零字节变化。
42
+ */
43
+ hostResources?: readonly {
44
+ scheme: string;
45
+ describe: string;
46
+ }[];
39
47
  /** [W5-G] task 子会话的角色说明(子 Agent 通用说明 + 类型正文);主会话没有。 */
40
48
  role?: string;
41
49
  /** [W6-C0] 预渲染的 `<memory_index>` 节(W6-M 的 memory/section.ts);未开启记忆时不给。 */
@@ -12,6 +12,7 @@
12
12
  import { replaySystem } from "../session/projection.js";
13
13
  import { escapeXml } from "../skills/index-prompt.js";
14
14
  import { baseRules } from "./prompt-rules.js";
15
+ import { formatResourceLine } from "../tools/resource-ref.js";
15
16
  export const SECTION_ORDER = [
16
17
  "preamble",
17
18
  "tools",
@@ -44,6 +45,9 @@ export function assembleSections(input) {
44
45
  // 内置工具的 promptSnippet 已以「name: 」开头(B3 约定),不再重复工具名。
45
46
  return snippet.startsWith(`${tool.name}:`) ? `- ${snippet}` : `- ${tool.name}: ${snippet}`;
46
47
  });
48
+ const resourceLine = formatResourceLine(input.hostResources ?? []);
49
+ if (resourceLine !== undefined)
50
+ toolLines.push(`- ${resourceLine}`);
47
51
  const rules = [
48
52
  ...baseRules(tools),
49
53
  ...tools.flatMap((tool) => tool.promptGuidelines ?? []),
@@ -9,8 +9,8 @@
9
9
  */
10
10
  import type { ModelRef, Usage } from "../ai/types.js";
11
11
  import type { PermissionMode } from "../permissions/types.js";
12
- import type { SubagentStatus } from "../tools/types.js";
13
- export type { SubagentStatus } from "../tools/types.js";
12
+ import type { SubagentReport, SubagentStatus } from "../tools/types.js";
13
+ export type { SubagentReport, SubagentReportState, SubagentStatus } from "../tools/types.js";
14
14
  /** 一次 `purpose: "turn"` 请求的速率数据。 */
15
15
  export interface RequestTelemetry {
16
16
  requestAt: number;
@@ -56,12 +56,15 @@ export interface SubagentStartEvent {
56
56
  export interface SubagentUpdateEvent {
57
57
  type: "subagent_update";
58
58
  taskId: string;
59
- kind: "tool" | "text" | "turn";
59
+ /** [#269] `report`:子 Agent 调用了 `report`,`report` 字段是这次运行当前折叠后的报告。 */
60
+ kind: "tool" | "text" | "turn" | "report";
60
61
  toolName?: string;
61
62
  /** 文本增量(节流 ≥ 250 ms 合并)。 */
62
63
  textDelta?: string;
63
64
  turn: number;
64
65
  usage?: Usage;
66
+ /** [#269] 只随 `kind: "report"`。 */
67
+ report?: SubagentReport;
65
68
  }
66
69
  export interface SubagentEndEvent {
67
70
  type: "subagent_end";
@@ -79,6 +82,8 @@ export interface SubagentEndEvent {
79
82
  branch: string;
80
83
  changed: boolean;
81
84
  };
85
+ /** [#269] 这次运行折叠后的报告;子 Agent 没报告时缺省。 */
86
+ report?: SubagentReport;
82
87
  }
83
88
  /**
84
89
  * [W7-B1] 前台任务转后台(docs/history/agents-concurrency-plan.md §2.5):`user` = 人(TUI `Ctrl+B` 等),
@@ -233,9 +233,16 @@ export type SessionEvent = {
233
233
  type: "permission_resolved";
234
234
  requestId: string;
235
235
  decision: ApprovalDecision;
236
+ /** [#271] 切换权限模式时按新模式自动作答(客户端据此收起审批界面)。 */
237
+ reason?: "mode_changed";
236
238
  } | {
237
239
  type: "permission_mode_changed";
238
240
  mode: PermissionMode;
241
+ /** [#271] 切换时按新模式自动放行 / 拒绝的待审批条数;都为 0 时不带。 */
242
+ reevaluated?: {
243
+ allowed: number;
244
+ denied: number;
245
+ };
239
246
  } | {
240
247
  type: "entry_appended";
241
248
  entry: SessionEntry;
@@ -6,7 +6,7 @@
6
6
  * 被拒绝且不弹审批(session-subagent.ts)。正文是追加到子会话系统提示末尾的角色说明(`role` 节)。
7
7
  */
8
8
  import type { AgentDefinition } from "./types.js";
9
- /** 所有 ama 子会话共有的角色说明(类型正文追加在它后面)。 */
9
+ /** 所有 ama 子会话共有的角色说明(类型正文追加在它后面);[#269] 末句要求结束前用 `report` 报告状态。 */
10
10
  export declare const SUBAGENT_ROLE_PREAMBLE: string;
11
11
  export declare const BUILTIN_AGENTS: readonly AgentDefinition[];
12
12
  export declare const DEFAULT_AGENT = "general";
@@ -5,10 +5,11 @@
5
5
  * `explore` / `plan` 的 `permissionMode: "plan"` 让子会话用 plan 模式的管线,写类工具与非只读 bash
6
6
  * 被拒绝且不弹审批(session-subagent.ts)。正文是追加到子会话系统提示末尾的角色说明(`role` 节)。
7
7
  */
8
- /** 所有 ama 子会话共有的角色说明(类型正文追加在它后面)。 */
8
+ import { REPORT_ROLE_HINT } from "./report.js";
9
+ /** 所有 ama 子会话共有的角色说明(类型正文追加在它后面);[#269] 末句要求结束前用 `report` 报告状态。 */
9
10
  export const SUBAGENT_ROLE_PREAMBLE = "You are a sub-agent: the main agent delegated one task to you. It cannot see your work, only " +
10
11
  "your final reply. Complete the task directly; do not delegate further. End with a concise " +
11
- "report: what you did, key findings, and files changed (if any).";
12
+ `report: what you did, key findings, and files changed (if any). ${REPORT_ROLE_HINT}`;
12
13
  function builtin(name, description, prompt, permissionMode) {
13
14
  return {
14
15
  name,
@@ -0,0 +1,25 @@
1
+ /**
2
+ * 子 Agent 的结构化报告(#269):`report` 工具的折叠语义与父会话看到的固定英文文本。
3
+ *
4
+ * - 报告槽按「一次运行」(一次 `task` 调用或一次 `taskId` 续聊)划定:运行开始清空,运行内每次 `report`
5
+ * 调用折叠进去——`state` / `summary` 取最后一次,`humanAction` 是单槽:给出替换、省略保持、`null` 清空;
6
+ * 运行结束取折叠后的值(session-subagent.ts 的 ama runner、drivers/runner.ts 的外部映射)。
7
+ * - 父会话的 `task` 结果、`<task-notification>` 与 `task_ctl wait` 都在正文前加 `[report] state · summary`;
8
+ * 有 `humanAction` 时再加 `[needs a person] …` 与固定规则句(注册表 `finish()` 统一拼,subagent-registry.ts)。
9
+ * - 发给模型的文本全部固定英文;没有报告时所有文本与原来逐字节相同。
10
+ */
11
+ import type { SubagentReport, SubagentReportState, SubagentReportUpdate } from "../tools/types.js";
12
+ export declare const REPORT_STATES: readonly SubagentReportState[];
13
+ /** `summary` 与 `humanAction` 的上限(字符)。 */
14
+ export declare const REPORT_TEXT_MAX = 300;
15
+ /** 父会话工具结果里跟在 `[needs a person]` 之后的规则句。 */
16
+ export declare const HUMAN_ACTION_RULE = "Relay this question to the user verbatim; do not answer it yourself.";
17
+ /** 子会话角色说明(`SUBAGENT_ROLE_PREAMBLE`、fork 的 `<task>`)末尾的一句。 */
18
+ export declare const REPORT_ROLE_HINT: string;
19
+ export declare function isReportState(value: unknown): value is SubagentReportState;
20
+ /** 单槽折叠:`state` / `summary` 取本次;`humanAction` 给出替换、省略保持、`null` 清空。 */
21
+ export declare function foldReport(previous: SubagentReport | undefined, update: SubagentReportUpdate): SubagentReport;
22
+ /** 正文前的报告行(固定英文)。 */
23
+ export declare function reportLines(report: SubagentReport): string[];
24
+ /** 报告行 + 空行 + 正文;没有报告时原样返回。 */
25
+ export declare function withReportLines(text: string, report: SubagentReport | undefined): string;
@@ -0,0 +1,51 @@
1
+ /**
2
+ * 子 Agent 的结构化报告(#269):`report` 工具的折叠语义与父会话看到的固定英文文本。
3
+ *
4
+ * - 报告槽按「一次运行」(一次 `task` 调用或一次 `taskId` 续聊)划定:运行开始清空,运行内每次 `report`
5
+ * 调用折叠进去——`state` / `summary` 取最后一次,`humanAction` 是单槽:给出替换、省略保持、`null` 清空;
6
+ * 运行结束取折叠后的值(session-subagent.ts 的 ama runner、drivers/runner.ts 的外部映射)。
7
+ * - 父会话的 `task` 结果、`<task-notification>` 与 `task_ctl wait` 都在正文前加 `[report] state · summary`;
8
+ * 有 `humanAction` 时再加 `[needs a person] …` 与固定规则句(注册表 `finish()` 统一拼,subagent-registry.ts)。
9
+ * - 发给模型的文本全部固定英文;没有报告时所有文本与原来逐字节相同。
10
+ */
11
+ export const REPORT_STATES = [
12
+ "ready",
13
+ "blocked",
14
+ "failed",
15
+ "waiting",
16
+ ];
17
+ /** `summary` 与 `humanAction` 的上限(字符)。 */
18
+ export const REPORT_TEXT_MAX = 300;
19
+ /** 父会话工具结果里跟在 `[needs a person]` 之后的规则句。 */
20
+ export const HUMAN_ACTION_RULE = "Relay this question to the user verbatim; do not answer it yourself.";
21
+ /** 子会话角色说明(`SUBAGENT_ROLE_PREAMBLE`、fork 的 `<task>`)末尾的一句。 */
22
+ export const REPORT_ROLE_HINT = "Before your final reply, call report with your state (ready, blocked, failed or waiting); put " +
23
+ "anything only a person can decide in humanAction instead of assuming an answer.";
24
+ export function isReportState(value) {
25
+ return typeof value === "string" && REPORT_STATES.includes(value);
26
+ }
27
+ /** 单槽折叠:`state` / `summary` 取本次;`humanAction` 给出替换、省略保持、`null` 清空。 */
28
+ export function foldReport(previous, update) {
29
+ const report = { state: update.state, summary: update.summary };
30
+ const action = update.humanAction === undefined
31
+ ? previous?.humanAction
32
+ : update.humanAction === null
33
+ ? undefined
34
+ : update.humanAction;
35
+ if (action !== undefined && action !== "")
36
+ report.humanAction = action;
37
+ return report;
38
+ }
39
+ /** 正文前的报告行(固定英文)。 */
40
+ export function reportLines(report) {
41
+ const lines = [`[report] ${report.state} · ${report.summary}`];
42
+ if (report.humanAction !== undefined)
43
+ lines.push(`[needs a person] ${report.humanAction}`, HUMAN_ACTION_RULE);
44
+ return lines;
45
+ }
46
+ /** 报告行 + 空行 + 正文;没有报告时原样返回。 */
47
+ export function withReportLines(text, report) {
48
+ if (report === undefined)
49
+ return text;
50
+ return `${reportLines(report).join("\n")}\n\n${text}`;
51
+ }
@@ -5,10 +5,16 @@
5
5
  * - 后台任务完成后以 `<task-notification>` 作为 followUp 投递给父会话(系统提示 rules 里由 task
6
6
  * 工具的 guideline 说明这不是用户发言)。
7
7
  */
8
+ import type { WorktreeOutcome } from "../agent/worktree.js";
8
9
  import type { Usage } from "../ai/types.js";
9
- import type { SubagentStatus } from "../tools/types.js";
10
+ import type { SubagentReport, SubagentStatus } from "../tools/types.js";
10
11
  export declare const TASK_RESULT_LIMIT_BYTES: number;
11
12
  export declare const MAX_TURNS_NOTE = "[Turn limit reached; the sub-agent's last output follows.]";
13
+ /**
14
+ * 结果正文的装饰(注册表 `finish()`):空文本占位 → 轮数耗尽说明 → [#269] 报告行(agents/report.ts)→
15
+ * 保留的 worktree 说明。没有报告、没保留 worktree、未耗尽时与原文相同。
16
+ */
17
+ export declare function decorateTaskText(capped: string, status: SubagentStatus, report: SubagentReport | undefined, outcome: WorktreeOutcome | undefined): string;
12
18
  /** 超过上限时保留头尾;返回 `truncated` 供调用方决定是否落盘。 */
13
19
  export declare function capTaskText(text: string, outputFile: string | undefined, limit?: number): {
14
20
  text: string;
@@ -24,6 +30,8 @@ export interface NotificationInput {
24
30
  turns?: number;
25
31
  usage?: Usage;
26
32
  outputFile?: string;
33
+ /** [#269] 结构化报告的状态(正文前已有 `[report]` 行;属性便于界面一眼看到)。 */
34
+ reportState?: SubagentReport["state"];
27
35
  /** 已按上限截断的最终报告。 */
28
36
  report: string;
29
37
  }
@@ -7,9 +7,23 @@
7
7
  */
8
8
  import { mkdirSync, writeFileSync } from "node:fs";
9
9
  import { join } from "node:path";
10
+ import { withReportLines } from "./report.js";
10
11
  export const TASK_RESULT_LIMIT_BYTES = 50 * 1024;
11
12
  const HEAD_SHARE = 0.7;
12
13
  export const MAX_TURNS_NOTE = "[Turn limit reached; the sub-agent's last output follows.]";
14
+ /**
15
+ * 结果正文的装饰(注册表 `finish()`):空文本占位 → 轮数耗尽说明 → [#269] 报告行(agents/report.ts)→
16
+ * 保留的 worktree 说明。没有报告、没保留 worktree、未耗尽时与原文相同。
17
+ */
18
+ export function decorateTaskText(capped, status, report, outcome) {
19
+ let text = capped.trim() === "" ? "(the sub-agent returned no text)" : capped;
20
+ if (status === "max_turns")
21
+ text = `${MAX_TURNS_NOTE}\n\n${text}`;
22
+ text = withReportLines(text, report);
23
+ if (outcome?.changed === true)
24
+ text += `\n\n[worktree kept: branch ${outcome.branch} at ${outcome.path ?? "?"}]\n${outcome.diffStat ?? ""}`;
25
+ return text;
26
+ }
13
27
  /** 去掉按字节切开时残留的半个字符(U+FFFD)。 */
14
28
  function trimReplacement(text, side) {
15
29
  return side === "end" ? text.replace(/�+$/, "") : text.replace(/^�+/, "");
@@ -61,6 +75,8 @@ export function taskNotification(input) {
61
75
  attrs.push(`tokens="${formatTokens(input.usage.totalTokens)}"`);
62
76
  if (input.outputFile !== undefined)
63
77
  attrs.push(`outputFile="${attr(input.outputFile)}"`);
78
+ if (input.reportState !== undefined)
79
+ attrs.push(`report="${input.reportState}"`);
64
80
  return `<task-notification ${attrs.join(" ")}>\n${input.report}\n</task-notification>`;
65
81
  }
66
82
  // [W7-B1] 后台任务的固定英文文案(docs/history/agents-concurrency-plan.md §2.5;工具结果不进缓存前缀,但要
@@ -4,7 +4,15 @@
4
4
  * 注册表(agent/subagent-registry.ts)建好后登记、会话 dispose 时注销。单独成文件是为了让
5
5
  * tools/task-ctl.ts 不 import agent/ 的实现(agent/tool-runner → tools/registry → task-ctl 会成环)。
6
6
  */
7
+ import type { ExtendOutcome } from "../tools/background-jobs.js";
7
8
  import type { SubagentResult, TaskRegistryView } from "../tools/types.js";
9
+ /** [#267] 到达寿命上限被停止的后台任务(提醒通道取走一次)。 */
10
+ export interface ExpiredTask {
11
+ taskId: string;
12
+ agent: string;
13
+ maxMs: number;
14
+ outputFile?: string;
15
+ }
8
16
  export interface TaskControl extends TaskRegistryView {
9
17
  /** 运行中是已有输出,结束后是最终文本。 */
10
18
  output(taskId: string): string | undefined;
@@ -22,6 +30,10 @@ export interface TaskControl extends TaskRegistryView {
22
30
  detachSignal(taskId: string): AbortSignal;
23
31
  /** [W7-B1] 正在阻塞父回合的任务(前台运行中、或有 `task_ctl wait` 在等)。 */
24
32
  blocking(): string[];
33
+ /** [#267] 给后台任务续命一次:加 `min(ms, 上限)`(ms 不给 = 一个上限)。 */
34
+ extend(taskId: string, ms?: number): ExtendOutcome;
35
+ /** [#267] 取走到达寿命上限、已停止且尚未通知的任务(提醒通道用)。 */
36
+ takeExpired(): ExpiredTask[];
25
37
  }
26
38
  export declare function registerTaskControl(sessionId: string, control: TaskControl): void;
27
39
  export declare function unregisterTaskControl(sessionId: string, control: TaskControl): void;
@@ -9,12 +9,16 @@ import type { SessionEvent } from "../agent/types.js";
9
9
  import type { TraceExternalTurnData } from "../trace/types.js";
10
10
  import type { Worktree, WorktreeOutcome } from "../agent/worktree.js";
11
11
  import type { SessionEntry } from "../session/types.js";
12
- import type { RunnerHandle, SubagentEvent, SubagentRequest, SubagentResult, TaskInfo } from "../tools/types.js";
12
+ import type { RunnerHandle, SubagentEvent, SubagentRequest, SubagentResult, SubagentStatus, TaskInfo } from "../tools/types.js";
13
13
  import type { AgentCatalog } from "./catalog.js";
14
14
  import type { AgentDefinition } from "./types.js";
15
15
  export declare const TASK_CUSTOM_TYPE = "ama.task";
16
16
  /** `subagent_update{kind:"text"}` 的合并间隔。 */
17
17
  export declare const TEXT_THROTTLE_MS = 250;
18
+ /** 任务的终态(注册表据此认 runner 给的 status)。 */
19
+ export declare const TERMINAL_STATUSES: readonly SubagentStatus[];
20
+ /** 注册表层面的失败结果(没起来、找不到任务、会话已关闭)。 */
21
+ export declare function failedResult(text: string): SubagentResult;
18
22
  /** 计数信号量;`waiting` 供排队上限判断;排队中 abort → 抛 aborted 并让出位置。 */
19
23
  export declare class SubagentPool {
20
24
  private readonly limit;
@@ -138,6 +142,25 @@ export interface TaskRecord {
138
142
  resolve(result: SubagentResult): void;
139
143
  detachParent(): void;
140
144
  };
145
+ /**
146
+ * [#267] 后台寿命上限(agent/subagent-lifetime.ts):后台启动或转后台时起计时,到点按 stop 处理;
147
+ * `extended` 后不能再续。结束时清掉。
148
+ */
149
+ lifetime?: {
150
+ maxMs: number;
151
+ extended: boolean;
152
+ since: number;
153
+ timer?: unknown;
154
+ };
155
+ /**
156
+ * [#267] 到达寿命上限被停止;`taken` = 提醒通道已取走;`relaunched` = 取走前又被续聊重启(此时不等它结束就
157
+ * 报告,报告的是上一次运行)。重启时已取走的标记直接清掉。
158
+ */
159
+ expired?: {
160
+ maxMs: number;
161
+ taken: boolean;
162
+ relaunched?: true;
163
+ };
141
164
  }
142
165
  export declare function newRecord(info: TaskInfo, agent: AgentDefinition, parentToolCallId: string, cwd: string, isolation?: "none" | "worktree"): TaskRecord;
143
166
  export interface ProgressSink {
@@ -4,10 +4,23 @@
4
4
  * 编排在 agent/subagent-registry.ts。
5
5
  */
6
6
  import { AmaError } from "../errors.js";
7
+ import { ZERO_USAGE } from "../agent/loop.js";
7
8
  import { DEFAULT_AGENT } from "./builtin.js";
8
9
  export const TASK_CUSTOM_TYPE = "ama.task";
9
10
  /** `subagent_update{kind:"text"}` 的合并间隔。 */
10
11
  export const TEXT_THROTTLE_MS = 250;
12
+ /** 任务的终态(注册表据此认 runner 给的 status)。 */
13
+ export const TERMINAL_STATUSES = [
14
+ "completed",
15
+ "failed",
16
+ "aborted",
17
+ "max_turns",
18
+ "interrupted",
19
+ ];
20
+ /** 注册表层面的失败结果(没起来、找不到任务、会话已关闭)。 */
21
+ export function failedResult(text) {
22
+ return { text, usage: { ...ZERO_USAGE }, stopReason: "error", isError: true, status: "failed" };
23
+ }
11
24
  /** 计数信号量;`waiting` 供排队上限判断;排队中 abort → 抛 aborted 并让出位置。 */
12
25
  export class SubagentPool {
13
26
  limit;
@@ -174,6 +187,17 @@ export function applyRunnerEvent(record, event, sink) {
174
187
  case "context":
175
188
  record.info.context = event.mode;
176
189
  return;
190
+ case "report":
191
+ // [#269] 这次运行当前折叠后的报告:进快照并即时发出(Agent 栏 / RPC / ACP 在父模型回答前就能看到)
192
+ record.info.report = event.report;
193
+ sink.emit({
194
+ type: "subagent_update",
195
+ taskId,
196
+ kind: "report",
197
+ turn: record.info.turns ?? 0,
198
+ report: event.report,
199
+ });
200
+ return;
177
201
  case "turn_trace":
178
202
  sink.appendTrace?.({
179
203
  kind: "external_turn",