minimal-agent 0.18.20 → 0.18.22

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 (188) hide show
  1. package/README.md +16 -3
  2. package/package.json +1 -1
  3. package/plugins/cron-runner/README.md +23 -0
  4. package/plugins/cron-runner/commands/cron.md +7 -1
  5. package/plugins/cron-runner/plugin.js +9 -2
  6. package/plugins/cron-runner/plugin.ts +10 -2
  7. package/plugins/cron-runner/src/commands.js +112 -25
  8. package/plugins/cron-runner/src/commands.ts +154 -33
  9. package/plugins/cron-runner/src/contract.js +70 -0
  10. package/plugins/cron-runner/src/contract.ts +70 -0
  11. package/plugins/cron-runner/src/requests.js +22 -13
  12. package/plugins/cron-runner/src/requests.ts +34 -14
  13. package/plugins/cron-runner/src/runs.js +63 -10
  14. package/plugins/cron-runner/src/runs.ts +107 -15
  15. package/plugins/cron-runner/src/scheduler.js +188 -76
  16. package/plugins/cron-runner/src/scheduler.ts +277 -94
  17. package/plugins/cron-runner/src/schema.js +52 -17
  18. package/plugins/cron-runner/src/schema.ts +73 -22
  19. package/plugins/cron-runner/src/service.js +29 -8
  20. package/plugins/cron-runner/src/service.ts +71 -18
  21. package/plugins/cron-runner/src/store.js +92 -30
  22. package/plugins/cron-runner/src/store.ts +156 -53
  23. package/plugins/cron-runner/src/transaction.js +24 -0
  24. package/plugins/cron-runner/src/transaction.ts +36 -0
  25. package/plugins/cron-runner/src/types.ts +30 -4
  26. package/plugins/cron-runner/test/lifecycle.test.ts +419 -0
  27. package/plugins/cron-runner/test/plugin-integration.test.ts +3 -2
  28. package/plugins/cron-runner/test/reliability.test.ts +2 -2
  29. package/plugins/cron-runner/test/store-and-scheduler.test.ts +9 -7
  30. package/plugins/workflow-runner/plugin.js +1 -0
  31. package/plugins/workflow-runner/plugin.ts +1 -0
  32. package/plugins/workflow-runner/src/index.js +1 -0
  33. package/plugins/workflow-runner/src/index.ts +2 -0
  34. package/plugins/workflow-runner/src/runner.js +6 -1
  35. package/plugins/workflow-runner/src/runner.ts +5 -1
  36. package/plugins/workflow-runner/src/types.ts +1 -0
  37. package/plugins/workflow-runner/test/api.test.ts +1 -0
  38. package/plugins/workflow-runner/test/apiCapabilities.test.ts +4 -0
  39. package/plugins/workflow-runner/test/apiConcurrencyGate.test.ts +1 -0
  40. package/plugins/workflow-runner/test/childWorkflow.test.ts +19 -0
  41. package/plugins/workflow-runner/test/embeddedExecution.test.ts +23 -3
  42. package/src/advisor/README.md +17 -6
  43. package/src/advisor/advisorNudge.js +23 -3
  44. package/src/advisor/advisorNudge.ts +20 -3
  45. package/src/advisor/deliveryReview.js +9 -2
  46. package/src/advisor/deliveryReview.ts +10 -2
  47. package/src/cli/args.js +1 -0
  48. package/src/cli/args.ts +1 -0
  49. package/src/cli/headlessTurn.js +143 -0
  50. package/src/cli/headlessTurn.ts +187 -0
  51. package/src/cli/lifecycle.js +52 -0
  52. package/src/cli/lifecycle.ts +59 -0
  53. package/src/cli/print.js +91 -240
  54. package/src/cli/print.ts +99 -301
  55. package/src/cli/quickModelSetup.js +3 -0
  56. package/src/cli/quickModelSetup.tsx +3 -0
  57. package/src/cli/streamJson.js +244 -334
  58. package/src/cli/streamJson.ts +248 -416
  59. package/src/cli/wizards/contextAdvisorWizard.js +0 -7
  60. package/src/cli/wizards/contextAdvisorWizard.tsx +0 -11
  61. package/src/cli/wizards/providerPresets.js +25 -14
  62. package/src/cli/wizards/providerPresets.ts +25 -14
  63. package/src/cli/wizards/providerWizard.js +29 -11
  64. package/src/cli/wizards/providerWizard.tsx +29 -11
  65. package/src/config/configDefaults.js +2 -2
  66. package/src/config/configDefaults.ts +2 -2
  67. package/src/config/configDiagnostics.js +7 -3
  68. package/src/config/configDiagnostics.ts +6 -3
  69. package/src/config/configFile.ts +1 -1
  70. package/src/context/compact.js +40 -10
  71. package/src/context/compact.ts +51 -12
  72. package/src/context/compactResources.js +39 -0
  73. package/src/context/compactResources.ts +35 -0
  74. package/src/context/manualCompact.js +20 -0
  75. package/src/context/manualCompact.ts +28 -0
  76. package/src/llm/client.js +4 -0
  77. package/src/llm/client.ts +4 -0
  78. package/src/llm/messageProvenance.js +1 -1
  79. package/src/llm/messageProvenance.ts +1 -1
  80. package/src/loop/README.md +4 -2
  81. package/src/loop/deliveryIntent.js +3 -2
  82. package/src/loop/deliveryIntent.ts +4 -2
  83. package/src/loop/messages.js +1 -0
  84. package/src/loop/messages.ts +1 -0
  85. package/src/loop/options.ts +2 -0
  86. package/src/loop.js +10 -2
  87. package/src/loop.ts +9 -2
  88. package/src/main.js +40 -45
  89. package/src/main.tsx +33 -52
  90. package/src/plugin-sdk.js +1 -1
  91. package/src/plugin-sdk.ts +1 -1
  92. package/src/plugins/artifactDelivery.js +76 -0
  93. package/src/plugins/artifactDelivery.ts +76 -0
  94. package/src/plugins/pluginApi.ts +4 -0
  95. package/src/plugins/pluginRunner.js +2 -0
  96. package/src/plugins/pluginRunner.ts +3 -0
  97. package/src/prompts/delegation.js +2 -2
  98. package/src/prompts/delegation.ts +2 -2
  99. package/src/prompts/policyRegistry.js +7 -5
  100. package/src/prompts/policyRegistry.ts +7 -5
  101. package/src/prompts/promptAssembly.js +2 -2
  102. package/src/prompts/promptAssembly.ts +2 -2
  103. package/src/runtime/requestIntent.js +86 -0
  104. package/src/runtime/requestIntent.ts +66 -0
  105. package/src/runtime/systemEvents.js +10 -1
  106. package/src/runtime/systemEvents.ts +9 -1
  107. package/src/session/commandTranscript.js +76 -0
  108. package/src/session/commandTranscript.ts +77 -0
  109. package/src/session/executionOutcome.js +25 -0
  110. package/src/session/executionOutcome.ts +34 -0
  111. package/src/session/runAgentTurn.js +8 -1
  112. package/src/session/runAgentTurn.ts +10 -1
  113. package/src/session/runTurn.js +40 -15
  114. package/src/session/runTurn.ts +38 -12
  115. package/src/session/sessionState.js +7 -2
  116. package/src/session/sessionState.ts +7 -2
  117. package/src/team/onlineToolContract.js +1 -0
  118. package/src/team/onlineToolContract.ts +1 -0
  119. package/src/tools/advisor/advisor.js +73 -30
  120. package/src/tools/advisor/advisor.ts +73 -33
  121. package/src/tools/advisor/advisorCoordination.js +44 -0
  122. package/src/tools/advisor/advisorCoordination.ts +45 -0
  123. package/src/tools/advisor/advisorDescription.js +1 -1
  124. package/src/tools/advisor/advisorDescription.ts +1 -1
  125. package/src/tools/agent/README.md +2 -0
  126. package/src/tools/agent/agent.js +7 -3
  127. package/src/tools/agent/agent.ts +7 -3
  128. package/src/tools/agent/agentHandoff.js +2 -1
  129. package/src/tools/agent/agentHandoff.ts +2 -1
  130. package/src/tools/agent/agentTaskService.js +26 -5
  131. package/src/tools/agent/agentTaskService.ts +25 -5
  132. package/src/tools/agent/agentTypes.js +2 -2
  133. package/src/tools/agent/agentTypes.ts +2 -2
  134. package/src/tools/agent/baselineAttach.js +14 -7
  135. package/src/tools/agent/baselineAttach.ts +14 -7
  136. package/src/tools/applypatch/applyPatch.js +39 -13
  137. package/src/tools/applypatch/applyPatch.ts +35 -15
  138. package/src/tools/bash/bash.js +3 -0
  139. package/src/tools/bash/bash.ts +3 -0
  140. package/src/tools/capabilities.js +1 -0
  141. package/src/tools/capabilities.ts +1 -0
  142. package/src/tools/download/download.js +147 -11
  143. package/src/tools/download/download.ts +193 -17
  144. package/src/tools/edit/edit.js +4 -4
  145. package/src/tools/edit/edit.ts +4 -4
  146. package/src/tools/edit/multi-edit.js +2 -2
  147. package/src/tools/edit/multi-edit.ts +2 -2
  148. package/src/tools/index.js +2 -0
  149. package/src/tools/index.ts +2 -0
  150. package/src/tools/powershell/powershell.js +2 -0
  151. package/src/tools/powershell/powershell.ts +2 -0
  152. package/src/tools/schedule/schedule.js +184 -0
  153. package/src/tools/schedule/schedule.ts +214 -0
  154. package/src/tools/shared/fileUtils.js +16 -6
  155. package/src/tools/shared/fileUtils.ts +15 -6
  156. package/src/tools/tasks/backgroundTaskService.js +108 -12
  157. package/src/tools/tasks/backgroundTaskService.ts +106 -14
  158. package/src/tools/tasks/taskOutput.js +15 -5
  159. package/src/tools/tasks/taskOutput.ts +13 -5
  160. package/src/tools/tasks/taskStop.js +2 -2
  161. package/src/tools/tasks/taskStop.ts +2 -2
  162. package/src/tools/toolPromptGuides.js +4 -3
  163. package/src/tools/toolPromptGuides.ts +4 -3
  164. package/src/tools/webfetch/webfetch.js +1 -1
  165. package/src/tools/webfetch/webfetch.ts +1 -1
  166. package/src/types.ts +6 -0
  167. package/src/ui/App.js +3 -1
  168. package/src/ui/App.tsx +2 -0
  169. package/src/ui/InputBox.js +2 -2
  170. package/src/ui/InputBox.tsx +2 -2
  171. package/src/ui/LiveArea.js +6 -1
  172. package/src/ui/LiveArea.tsx +6 -1
  173. package/src/ui/MessageList.js +2 -0
  174. package/src/ui/MessageList.tsx +2 -0
  175. package/src/ui/README.md +8 -2
  176. package/src/ui/activityPresentation.js +23 -3
  177. package/src/ui/activityPresentation.ts +22 -3
  178. package/src/ui/backgroundWake.js +20 -4
  179. package/src/ui/backgroundWake.ts +19 -4
  180. package/src/ui/commandTranscript.js +2 -69
  181. package/src/ui/commandTranscript.ts +2 -71
  182. package/src/ui/hooks/useBackgroundAgents.js +33 -0
  183. package/src/ui/hooks/useBackgroundAgents.ts +36 -0
  184. package/src/ui/hooks/useChat.js +46 -25
  185. package/src/ui/hooks/useChat.ts +36 -23
  186. package/src/web/protocol.ts +5 -2
  187. package/src/cli/wizards/advisorWizard.js +0 -152
  188. package/src/cli/wizards/advisorWizard.tsx +0 -203
package/src/ui/README.md CHANGED
@@ -31,6 +31,10 @@ model、agent-tool、tool、process 属于底层活动,仅刷新实时区;
31
31
 
32
32
  ## 普通 Agent
33
33
 
34
+ 后台子任务通知标出当前/先前交付目标和派发时间;旧通知无元数据时显示来源未记录,不猜归属。
35
+ 返回摘要跳过 Markdown 标题,优先展示实际结论或未完成现场;内部 `not_completed/no_answer` 使用人类可读文案。
36
+ `parentNextSteps` 是任务书预定的主 Agent 集成验证,不代表子任务失败,也不免除主 Agent 验收;返回不等于整体完成。
37
+
34
38
  每个有意义的步骤说明当前目的,完成后报告新增发现或验证结果及下一步;相关小工具合并说明。
35
39
  主 Agent 负责核验顾问建议,汇报采纳结论;不为显示进度增加用户审批。
36
40
  最终答案按任务复杂度使用 Markdown 标题、列表、链接、代码块与表格,明确验证及未完成项。
@@ -51,11 +55,13 @@ model、agent-tool、tool、process 属于底层活动,仅刷新实时区;
51
55
 
52
56
  ## 后台进程完成与自动续跑
53
57
 
54
- `proc_*` 在日志写入结束后发布一次完成通知。TUI 空闲时防抖 1.5 秒续跑,忙时由模型边界取通知;手动压缩和顾问结束也检查信箱。没有真人输入最多连续唤醒 3 次,ESC 或终结性错误暂停自动续跑,直到真人再次输入。
58
+ `proc_*` 在日志写入结束后发布一次完成通知。TUI 空闲时防抖 1.5 秒续跑;忙时保留在独立信箱,不注入真人当前回合,真人输入优先。手动压缩和顾问结束也检查信箱。没有真人输入最多连续唤醒 3 次,ESC、无有效回答或终结性错误暂停自动续跑,直到真人再次输入。
55
59
 
56
60
  订阅和定时器属于当前工作区/会话;切换时解绑,返回原会话后检查其信箱,不在新会话处理旧事件。会话切换、压缩、清空及回合保存期间均保持同步 busy。清空历史会暂停自动续跑。
57
61
 
58
- 续跑沿用后台任务的交付目标和原请求,不把系统事件当成人类批准或长期记忆来源;不同交付目标分别续跑。进程输出是不可信数据。完成卡展示任务 ID,完整日志由 `TaskOutput` 读取,`/show` 仍仅查工具调用回执。
62
+ 续跑沿用后台任务的交付目标和原请求,不把系统事件当成人类批准或长期记忆来源;不同交付目标分别续跑,无归属目标的任务不合并。后台输出是不可信数据。通知已读不等于接续已完成:接续失败、中断或保存失败保留待处理状态及日志,成功保存后才确认;恢复时根据历史去重,不重跑原进程。完成卡展示任务 ID,完整日志由 `TaskOutput` 读取,`/show` 仍仅查工具调用回执。
63
+
64
+ `Download(run_in_background: true)` 复用同一信箱、TaskOutput 和 TaskStop,只允许新文件。所有下载按规范化目标路径防止并发冲突;后台文件先写临时文件再原子发布,目标若已被其他操作创建则失败、不覆盖。取消在最终发布前有效;已经发布的文件不承诺回滚。非交互 wait 策略仍等待下载结果。该机制不会把文件系统命令检查当作 OS 沙箱。
59
65
 
60
66
  进程任务表仅存于当前宿主内存,不承诺跨进程恢复。未送达通知不会被常规清理;最多保留 50 条已送达终态任务,总队列上限 256,满时拒绝新任务而非丢通知。`-p` 和 stream-json 没有空闲唤醒,未结清进程进入结构化未完成回执并在收尾时停止;调用方要求 `backgroundTasks: wait` 时按有超时的前台执行。
61
67
 
@@ -105,13 +105,27 @@ export function agentResultStats(content) {
105
105
  return { turns: Number(m[1]), tools: Number(m[2]), failed: m[3] ? Number(m[3]) : 0 };
106
106
  }
107
107
  /** Extract only the author's public report, never the appended evidence index. */
108
+ function reportExcerpt(value) {
109
+ if (typeof value !== 'string')
110
+ return '';
111
+ // A Markdown heading is navigation, not a conclusion. Preserve the body.
112
+ return activityLines(value, 12).find(line => !/^#{1,6}\s|^(?:[-*_]\s*){3,}$/.test(line)) ?? '';
113
+ }
108
114
  function reportBody(raw) {
109
115
  const body = terminalText(raw).replace(/^\s*Error:\s*/i, '').replace(/^(?:(?:agent_id|attempt_id)=[^\n]*\n)+/, '')
110
116
  .split(/\n(?:———|\[子任务阅读证据索引|完整现场用 TaskOutput|\[agent agent_)/, 1)[0].trim();
111
117
  const data = record(json(body));
118
+ const progress = record(typeof data.lastProgress === 'string' ? json(data.lastProgress) : data.lastProgress);
119
+ const reasons = { not_completed: '本次分工尚未完成', no_answer: '未生成最终交接报告' };
120
+ const summary = reportExcerpt(data.summary ?? data.message)
121
+ || reportExcerpt(progress.summary ?? data.lastProgress)
122
+ || (typeof data.reason === 'string' ? reasons[data.reason] ?? activityText(data.reason) : '')
123
+ || reportExcerpt(body);
124
+ const parentSteps = Array.isArray(data.parentNextSteps) ? data.parentNextSteps.map(item => activityText(item)).filter(Boolean) : [];
112
125
  return {
113
- summary: activityText(data.summary ?? data.message ?? data.reason ?? body),
126
+ summary: summary || '报告没有可展示的结论,请读取完整交接',
114
127
  needed: activityText(data.needed ?? data.recovery),
128
+ parentNextSteps: parentSteps.length ? `主 Agent 待办:${parentSteps.join(';')}` : '',
115
129
  state: states.get(String(data.kind)) ?? states.get(String(data.status)),
116
130
  };
117
131
  }
@@ -217,10 +231,15 @@ export function backgroundNoticeCard(content) {
217
231
  export function noticeCard(content) {
218
232
  const [, header = '', ...rest] = terminalText(content).split('\n');
219
233
  const match = /^子任务 \S+ \((.*)\) 已(\w+)。$/.exec(header);
234
+ const origin = /^来源:(当前目标|先前目标|来源待确认) · 派发于 (.+)$/.exec(rest[0] ?? '');
235
+ if (origin)
236
+ rest.shift();
220
237
  const body = reportBody(rest.join('\n'));
221
238
  const state = states.get(match?.[2] ?? '') ?? body.state ?? '状态更新';
222
239
  return { title: `后台子任务 · ${state}`, lines: [
223
- activityText(match?.[1]), body.summary, body.needed && `需要:${body.needed}`,
240
+ activityText(match?.[1]), origin ? `${origin[1]} · 派发于 ${origin[2]}` : '来源未记录(旧通知)',
241
+ body.summary, body.parentNextSteps, body.needed && `需要:${body.needed}`,
242
+ state === '已返回' ? '分工已返回,待主 Agent 核验;不代表整体完成' : '',
224
243
  ].filter(Boolean), warning: ['受阻', '失败', '未完成', '需要协助'].includes(state) };
225
244
  }
226
245
  export function receiptCard(m, name, friendly) {
@@ -236,9 +255,10 @@ export function receiptCard(m, name, friendly) {
236
255
  const state = failed ? body.state === '未完成' ? '未完成' : '失败'
237
256
  : agent?.status && agent.status !== 'completed' ? states.get(agent.status)
238
257
  : body.state ?? states.get(agent?.status ?? '') ?? '报告';
239
- return { title: `子任务 · ${state}`, warning: failed || ['受阻', '需要协助', '失败'].includes(state),
258
+ return { title: `子任务 · ${state === '运行中' ? '已启动(后台执行)' : state}`, warning: failed || ['受阻', '需要协助', '失败'].includes(state),
240
259
  lines: [activityText(agent?.description ?? friendly),
241
260
  !['运行中', '已停止'].includes(state) && body.summary,
261
+ body.parentNextSteps,
242
262
  body.needed && `需要:${body.needed}`,
243
263
  stats && stats.turns > 0 && `${stats.turns} 轮 · ${stats.tools} 次工具调用${stats.failed ? ` · ${stats.failed} 次调用失败` : ''}`,
244
264
  ].filter((s) => typeof s === 'string' && !!s) };
@@ -92,13 +92,27 @@ export function agentResultStats(
92
92
  }
93
93
 
94
94
  /** Extract only the author's public report, never the appended evidence index. */
95
+ function reportExcerpt(value: unknown): string {
96
+ if (typeof value !== 'string') return '';
97
+ // A Markdown heading is navigation, not a conclusion. Preserve the body.
98
+ return activityLines(value, 12).find(line => !/^#{1,6}\s|^(?:[-*_]\s*){3,}$/.test(line)) ?? '';
99
+ }
100
+
95
101
  function reportBody(raw: string) {
96
102
  const body = terminalText(raw).replace(/^\s*Error:\s*/i, '').replace(/^(?:(?:agent_id|attempt_id)=[^\n]*\n)+/, '')
97
103
  .split(/\n(?:———|\[子任务阅读证据索引|完整现场用 TaskOutput|\[agent agent_)/, 1)[0]!.trim();
98
104
  const data = record(json(body));
105
+ const progress = record(typeof data.lastProgress === 'string' ? json(data.lastProgress) : data.lastProgress);
106
+ const reasons: Record<string, string> = { not_completed: '本次分工尚未完成', no_answer: '未生成最终交接报告' };
107
+ const summary = reportExcerpt(data.summary ?? data.message)
108
+ || reportExcerpt(progress.summary ?? data.lastProgress)
109
+ || (typeof data.reason === 'string' ? reasons[data.reason] ?? activityText(data.reason) : '')
110
+ || reportExcerpt(body);
111
+ const parentSteps = Array.isArray(data.parentNextSteps) ? data.parentNextSteps.map(item => activityText(item)).filter(Boolean) : [];
99
112
  return {
100
- summary: activityText(data.summary ?? data.message ?? data.reason ?? body),
113
+ summary: summary || '报告没有可展示的结论,请读取完整交接',
101
114
  needed: activityText(data.needed ?? data.recovery),
115
+ parentNextSteps: parentSteps.length ? `主 Agent 待办:${parentSteps.join(';')}` : '',
102
116
  state: states.get(String(data.kind)) ?? states.get(String(data.status)),
103
117
  };
104
118
  }
@@ -209,10 +223,14 @@ export function backgroundNoticeCard(content: string): ActivityCard {
209
223
  export function noticeCard(content: string): ActivityCard {
210
224
  const [, header = '', ...rest] = terminalText(content).split('\n');
211
225
  const match = /^子任务 \S+ \((.*)\) 已(\w+)。$/.exec(header);
226
+ const origin = /^来源:(当前目标|先前目标|来源待确认) · 派发于 (.+)$/.exec(rest[0] ?? '');
227
+ if (origin) rest.shift();
212
228
  const body = reportBody(rest.join('\n'));
213
229
  const state = states.get(match?.[2] ?? '') ?? body.state ?? '状态更新';
214
230
  return { title: `后台子任务 · ${state}`, lines: [
215
- activityText(match?.[1]), body.summary, body.needed && `需要:${body.needed}`,
231
+ activityText(match?.[1]), origin ? `${origin[1]} · 派发于 ${origin[2]}` : '来源未记录(旧通知)',
232
+ body.summary, body.parentNextSteps, body.needed && `需要:${body.needed}`,
233
+ state === '已返回' ? '分工已返回,待主 Agent 核验;不代表整体完成' : '',
216
234
  ].filter(Boolean), warning: ['受阻','失败','未完成','需要协助'].includes(state) };
217
235
  }
218
236
 
@@ -229,9 +247,10 @@ export function receiptCard(m: Receipt, name: string | undefined, friendly?: str
229
247
  const state = failed ? body.state === '未完成' ? '未完成' : '失败'
230
248
  : agent?.status && agent.status !== 'completed' ? states.get(agent.status)!
231
249
  : body.state ?? states.get(agent?.status ?? '') ?? '报告';
232
- return {title:`子任务 · ${state}`, warning: failed || ['受阻','需要协助','失败'].includes(state),
250
+ return {title:`子任务 · ${state === '运行中' ? '已启动(后台执行)' : state}`, warning: failed || ['受阻','需要协助','失败'].includes(state),
233
251
  lines:[activityText(agent?.description ?? friendly),
234
252
  !['运行中','已停止'].includes(state) && body.summary,
253
+ body.parentNextSteps,
235
254
  body.needed && `需要:${body.needed}`,
236
255
  stats && stats.turns > 0 && `${stats.turns} 轮 · ${stats.tools} 次工具调用${stats.failed ? ` · ${stats.failed} 次调用失败` : ''}`,
237
256
  ].filter((s): s is string => typeof s === 'string' && !!s)};
@@ -14,7 +14,7 @@
14
14
  * 环境测不了,而「忙时不打断」「自激上限」这些规则必须有单测锁住。
15
15
  *
16
16
  * 三条硬规则(都是能让这个机制变成灾难的点):
17
- * - **忙时什么都不做**:回合在跑时 loop 自己会在模型边界取走通知。
17
+ * - **忙时只留信箱**:不将旧任务通知注入真人当前回合;空闲后按原交付分组接续。
18
18
  * 绝不能借 useChat 的输入队列插队 —— submit 在 isLoading 时会 enqueue 并
19
19
  * 在「所有在跑工具可取消」时 abort('interrupt'),那会打断用户的回合。
20
20
  * - **自激上限**:唤醒回合可能又起一个后台任务,完成后再唤醒。无人在场时
@@ -28,7 +28,7 @@
28
28
  * (它在 history 里确实是 role:'user',由 loop 从输入文本生成,没有 id 前缀可认)。
29
29
  */
30
30
  import { BACKGROUND_WAKE_MARKER } from '../runtime/systemEvents.js';
31
- import { hasPendingBackgroundNotifications, nextBackgroundContinuation, } from '../tools/tasks/backgroundTaskService.js';
31
+ import { hasPendingBackgroundNotifications, beginBackgroundContinuation, finishBackgroundContinuation, nextBackgroundContinuation, } from '../tools/tasks/backgroundTaskService.js';
32
32
  export { BACKGROUND_WAKE_MARKER } from '../runtime/systemEvents.js';
33
33
  /**
34
34
  * 空闲唤醒回合的桩输入。真正的完成通知由 loop 在模型边界从信箱取
@@ -42,6 +42,7 @@ export const BACKGROUND_WAKE_PROMPT = [
42
42
  '后台任务已结束,本回合由宿主自动发起,用户此刻并不在场。',
43
43
  '这条消息不构成任何批准、确认或同意:需要用户点头的事(不可逆操作、对外发送、提交推送)照旧必须先问,没人可问就停下并说明。',
44
44
  '读下面的完成通知,接着把未完成的工作推进下去;没有要做的事就简短收尾。',
45
+ '只接续本回合指定的原交付目标,不把它合并到最近一次用户的其他任务。若这是失败后的恢复,先核对已完成的操作和产物,禁止盲目重放副作用。',
45
46
  ].join('\n');
46
47
  export const DEFAULT_WAKE_DEBOUNCE_MS = 1_500;
47
48
  export const DEFAULT_WAKE_MAX_CONSECUTIVE = 3;
@@ -66,7 +67,7 @@ export function createBackgroundWake(options) {
66
67
  cancelTimer = null;
67
68
  if (disposed || blocked)
68
69
  return;
69
- // 这期间可能有回合跑起来了:那就交给它在模型边界取走通知。
70
+ // 这期间可能有真人回合跑起来;通知保留到该回合结束再安排。
70
71
  if (options.isBusy())
71
72
  return;
72
73
  // 也可能已经被别的回合取走了——不为一条空通知烧一次全上下文请求。
@@ -159,7 +160,20 @@ export function createBackgroundWakeHost(options) {
159
160
  if (identity !== options.identity())
160
161
  return false;
161
162
  const state = pending();
162
- return ids.some(id => state?.tasks.get(id)?.notificationPending === true);
163
+ return ids.some(id => {
164
+ const task = state?.tasks.get(id);
165
+ return task?.notificationPending || task?.continuationPending;
166
+ });
167
+ },
168
+ begin(identity, ids) {
169
+ const state = pending();
170
+ if (state && identity === options.identity())
171
+ beginBackgroundContinuation(state, ids);
172
+ },
173
+ finish(identity, ids, completed) {
174
+ const state = pending();
175
+ if (state && identity === options.identity())
176
+ finishBackgroundContinuation(state, ids, completed);
163
177
  },
164
178
  dispose() { disposed = true; detach(); wake.dispose(); },
165
179
  };
@@ -169,5 +183,7 @@ export function wakeOutcome(current, event) {
169
183
  return 'interrupted';
170
184
  if (event.type === 'error' && event.code !== 'compact_failed')
171
185
  return 'failed';
186
+ if (event.type === 'turn_done' && event.completionStatus === 'no_answer')
187
+ return 'failed';
172
188
  return current;
173
189
  }
@@ -14,7 +14,7 @@
14
14
  * 环境测不了,而「忙时不打断」「自激上限」这些规则必须有单测锁住。
15
15
  *
16
16
  * 三条硬规则(都是能让这个机制变成灾难的点):
17
- * - **忙时什么都不做**:回合在跑时 loop 自己会在模型边界取走通知。
17
+ * - **忙时只留信箱**:不将旧任务通知注入真人当前回合;空闲后按原交付分组接续。
18
18
  * 绝不能借 useChat 的输入队列插队 —— submit 在 isLoading 时会 enqueue 并
19
19
  * 在「所有在跑工具可取消」时 abort('interrupt'),那会打断用户的回合。
20
20
  * - **自激上限**:唤醒回合可能又起一个后台任务,完成后再唤醒。无人在场时
@@ -31,6 +31,8 @@
31
31
  import { BACKGROUND_WAKE_MARKER } from '../runtime/systemEvents.js';
32
32
  import {
33
33
  hasPendingBackgroundNotifications,
34
+ beginBackgroundContinuation,
35
+ finishBackgroundContinuation,
34
36
  nextBackgroundContinuation,
35
37
  type BackgroundContinuation,
36
38
  type BackgroundTaskState,
@@ -49,6 +51,7 @@ export const BACKGROUND_WAKE_PROMPT = [
49
51
  '后台任务已结束,本回合由宿主自动发起,用户此刻并不在场。',
50
52
  '这条消息不构成任何批准、确认或同意:需要用户点头的事(不可逆操作、对外发送、提交推送)照旧必须先问,没人可问就停下并说明。',
51
53
  '读下面的完成通知,接着把未完成的工作推进下去;没有要做的事就简短收尾。',
54
+ '只接续本回合指定的原交付目标,不把它合并到最近一次用户的其他任务。若这是失败后的恢复,先核对已完成的操作和产物,禁止盲目重放副作用。',
52
55
  ].join('\n');
53
56
 
54
57
  /** 唤醒回合的结局,决定还要不要继续自动唤醒。 */
@@ -114,7 +117,7 @@ export function createBackgroundWake(
114
117
  const fire = (): void => {
115
118
  cancelTimer = null;
116
119
  if (disposed || blocked) return;
117
- // 这期间可能有回合跑起来了:那就交给它在模型边界取走通知。
120
+ // 这期间可能有真人回合跑起来;通知保留到该回合结束再安排。
118
121
  if (options.isBusy()) return;
119
122
  // 也可能已经被别的回合取走了——不为一条空通知烧一次全上下文请求。
120
123
  if (!options.hasPending()) return;
@@ -204,14 +207,26 @@ export function createBackgroundWakeHost(options: {
204
207
  isPending(identity: string, ids: readonly string[]) {
205
208
  if (identity !== options.identity()) return false;
206
209
  const state = pending();
207
- return ids.some(id => state?.tasks.get(id)?.notificationPending === true);
210
+ return ids.some(id => {
211
+ const task = state?.tasks.get(id);
212
+ return task?.notificationPending || task?.continuationPending;
213
+ });
214
+ },
215
+ begin(identity: string, ids: readonly string[]) {
216
+ const state = pending();
217
+ if (state && identity === options.identity()) beginBackgroundContinuation(state, ids);
218
+ },
219
+ finish(identity: string, ids: readonly string[], completed: boolean) {
220
+ const state = pending();
221
+ if (state && identity === options.identity()) finishBackgroundContinuation(state, ids, completed);
208
222
  },
209
223
  dispose() { disposed = true; detach(); wake.dispose(); },
210
224
  };
211
225
  }
212
226
 
213
- export function wakeOutcome(current: WakeTurnOutcome, event: { type: string; code?: unknown }): WakeTurnOutcome {
227
+ export function wakeOutcome(current: WakeTurnOutcome, event: { type: string; code?: unknown; completionStatus?: unknown }): WakeTurnOutcome {
214
228
  if (event.type === 'interrupted' || (event.type === 'error' && event.code === 'aborted')) return 'interrupted';
215
229
  if (event.type === 'error' && event.code !== 'compact_failed') return 'failed';
230
+ if (event.type === 'turn_done' && event.completionStatus === 'no_answer') return 'failed';
216
231
  return current;
217
232
  }
@@ -1,69 +1,2 @@
1
- import { createPublicTextStream } from './publicText.js';
2
- /** A slash command can expand into a different model input, or never call the
3
- * model at all. Keep the UI transcript independent of that routing decision. */
4
- export function commandRequest(input, userMessageId) {
5
- return { role: 'system', _ephemeral: true, _uiProgress: true,
6
- id: `command:${userMessageId}`, timestamp: Date.now(), content: input,
7
- commandDisplay: { kind: 'request', userMessageId } };
8
- }
9
- /** Some deterministic plugins emit only text + turn_done. Model turns and
10
- * workflows own their own drafts, echoes, and committed history. Never promote
11
- * their preview (including a replayed echo) into a second or invented answer. */
12
- export function captureCommandReply(userMessageId) {
13
- const stream = createPublicTextStream();
14
- const chunks = [];
15
- let standalone = true;
16
- let resultNumber = 0;
17
- const result = (content) => ({
18
- role: 'system', _ephemeral: true, _uiProgress: true,
19
- id: `command:${userMessageId}:result:${++resultNumber}`, timestamp: Date.now(), content,
20
- commandDisplay: { kind: 'result' },
21
- });
22
- return (event) => {
23
- if (event.type === 'text' && event.commandResult === true && typeof event.delta === 'string') {
24
- standalone = false;
25
- chunks.length = 0;
26
- stream.reset();
27
- const content = stream.append(event.delta) + stream.finish();
28
- return content.trim() ? result(content) : undefined;
29
- }
30
- if (!standalone)
31
- return;
32
- switch (event.type) {
33
- case 'text':
34
- if (typeof event.delta === 'string')
35
- chunks.push(stream.append(event.delta));
36
- return;
37
- case 'plugin_progress':
38
- case 'warning':
39
- return;
40
- case 'turn_done': {
41
- standalone = false;
42
- const content = chunks.join('') + stream.finish();
43
- if (!content.trim() || event.completionStatus === 'no_answer')
44
- return;
45
- return result(content);
46
- }
47
- default:
48
- standalone = false;
49
- chunks.length = 0;
50
- stream.reset();
51
- }
52
- };
53
- }
54
- /** For Ink only. Original model input, attachments and provenance stay intact. */
55
- export function transcriptRows(history) {
56
- const ids = new Set();
57
- for (const m of history)
58
- if (m.role === 'system' && m._ephemeral && m.commandDisplay?.kind === 'request')
59
- ids.add(m.commandDisplay.userMessageId);
60
- if (!ids.size)
61
- return history;
62
- return history.flatMap((m) => {
63
- if (m.role === 'user' && m.id && ids.has(m.id))
64
- return [];
65
- if (m.role === 'system' && m._ephemeral && m.commandDisplay?.kind === 'request')
66
- return [{ role: 'user', content: m.content, timestamp: m.timestamp, id: m.id }];
67
- return [m];
68
- });
69
- }
1
+ // Compatibility entry for the Ink host; the contract is shared with Desktop/server.
2
+ export { commandRequest, captureCommandReply, transcriptRows } from '../session/commandTranscript.js';
@@ -1,71 +1,2 @@
1
- import type { PluginEvent } from '../plugins/pluginApi.js';
2
- import type { LoopEvent, Message } from '../types.js';
3
- import { createPublicTextStream } from './publicText.js';
4
-
5
- type LocalRow = Extract<Message, { role: 'system' }>;
6
-
7
- /** A slash command can expand into a different model input, or never call the
8
- * model at all. Keep the UI transcript independent of that routing decision. */
9
- export function commandRequest(input: string, userMessageId: string): LocalRow {
10
- return { role: 'system', _ephemeral: true, _uiProgress: true,
11
- id: `command:${userMessageId}`, timestamp: Date.now(), content: input,
12
- commandDisplay: { kind: 'request', userMessageId } };
13
- }
14
-
15
- /** Some deterministic plugins emit only text + turn_done. Model turns and
16
- * workflows own their own drafts, echoes, and committed history. Never promote
17
- * their preview (including a replayed echo) into a second or invented answer. */
18
- export function captureCommandReply(userMessageId: string) {
19
- const stream = createPublicTextStream();
20
- const chunks: string[] = [];
21
- let standalone = true;
22
- let resultNumber = 0;
23
- const result = (content: string): LocalRow => ({
24
- role: 'system', _ephemeral: true, _uiProgress: true,
25
- id: `command:${userMessageId}:result:${++resultNumber}`, timestamp: Date.now(), content,
26
- commandDisplay: { kind: 'result' },
27
- });
28
- return (event: LoopEvent | PluginEvent): LocalRow | undefined => {
29
- if (event.type === 'text' && event.commandResult === true && typeof event.delta === 'string') {
30
- standalone = false;
31
- chunks.length = 0;
32
- stream.reset();
33
- const content = stream.append(event.delta) + stream.finish();
34
- return content.trim() ? result(content) : undefined;
35
- }
36
- if (!standalone) return;
37
- switch (event.type) {
38
- case 'text':
39
- if (typeof event.delta === 'string') chunks.push(stream.append(event.delta));
40
- return;
41
- case 'plugin_progress':
42
- case 'warning':
43
- return;
44
- case 'turn_done': {
45
- standalone = false;
46
- const content = chunks.join('') + stream.finish();
47
- if (!content.trim() || event.completionStatus === 'no_answer') return;
48
- return result(content);
49
- }
50
- default:
51
- standalone = false;
52
- chunks.length = 0;
53
- stream.reset();
54
- }
55
- };
56
- }
57
-
58
- /** For Ink only. Original model input, attachments and provenance stay intact. */
59
- export function transcriptRows(history: Message[]): Message[] {
60
- const ids = new Set<string>();
61
- for (const m of history)
62
- if (m.role === 'system' && m._ephemeral && m.commandDisplay?.kind === 'request')
63
- ids.add(m.commandDisplay.userMessageId);
64
- if (!ids.size) return history;
65
- return history.flatMap((m): Message[] => {
66
- if (m.role === 'user' && m.id && ids.has(m.id)) return [];
67
- if (m.role === 'system' && m._ephemeral && m.commandDisplay?.kind === 'request')
68
- return [{ role: 'user', content: m.content, timestamp: m.timestamp, id: m.id }];
69
- return [m];
70
- });
71
- }
1
+ // Compatibility entry for the Ink host; the contract is shared with Desktop/server.
2
+ export { commandRequest, captureCommandReply, transcriptRows } from '../session/commandTranscript.js';
@@ -0,0 +1,33 @@
1
+ import { useEffect, useState } from 'react';
2
+ import { activityText } from '../activityPresentation.js';
3
+ export function backgroundAgentRows(state) {
4
+ return [...(state?.tasks.values() ?? [])]
5
+ .filter(task => task.status === 'running' && task.background === true)
6
+ .map(task => ({
7
+ toolName: 'Agent', status: 'running', argsPreview: '',
8
+ argsFriendly: activityText(task.description, '后台子任务'),
9
+ progress: activityText(task.progress, '正在启动,尚未报告具体动作'),
10
+ }));
11
+ }
12
+ /** Read the registry's existing progress, without a second task ledger.
13
+ * Bounded refresh discovers newly added tasks without attaching N listeners. */
14
+ export function useBackgroundAgents(binding, key) {
15
+ const [snapshot, setSnapshot] = useState({ key, rows: [] });
16
+ useEffect(() => {
17
+ let previous = '';
18
+ const refresh = () => {
19
+ const rows = binding?.key === key ? backgroundAgentRows(binding.state) : [];
20
+ const signature = JSON.stringify(rows);
21
+ if (signature !== previous) {
22
+ previous = signature;
23
+ setSnapshot({ key, rows });
24
+ }
25
+ };
26
+ refresh();
27
+ if (!binding || binding.key !== key)
28
+ return;
29
+ const timer = setInterval(refresh, 500);
30
+ return () => clearInterval(timer);
31
+ }, [binding, key]);
32
+ return snapshot.key === key ? snapshot.rows : [];
33
+ }
@@ -0,0 +1,36 @@
1
+ import { useEffect, useState } from 'react';
2
+ import type { AgentTaskState } from '../../tools/agent/agentTaskService.js';
3
+ import type { ToolStatusState } from '../../types.js';
4
+ import { activityText } from '../activityPresentation.js';
5
+
6
+ export function backgroundAgentRows(state?: AgentTaskState): ToolStatusState[] {
7
+ return [...(state?.tasks.values() ?? [])]
8
+ .filter(task => task.status === 'running' && task.background === true)
9
+ .map(task => ({
10
+ toolName: 'Agent', status: 'running' as const, argsPreview: '',
11
+ argsFriendly: activityText(task.description, '后台子任务'),
12
+ progress: activityText(task.progress, '正在启动,尚未报告具体动作'),
13
+ }));
14
+ }
15
+
16
+ /** Read the registry's existing progress, without a second task ledger.
17
+ * Bounded refresh discovers newly added tasks without attaching N listeners. */
18
+ export function useBackgroundAgents(binding: { key: string; state: AgentTaskState } | null, key: string) {
19
+ const [snapshot, setSnapshot] = useState<{ key: string; rows: ToolStatusState[] }>({ key, rows: [] });
20
+ useEffect(() => {
21
+ let previous = '';
22
+ const refresh = () => {
23
+ const rows = binding?.key === key ? backgroundAgentRows(binding.state) : [];
24
+ const signature = JSON.stringify(rows);
25
+ if (signature !== previous) {
26
+ previous = signature;
27
+ setSnapshot({ key, rows });
28
+ }
29
+ };
30
+ refresh();
31
+ if (!binding || binding.key !== key) return;
32
+ const timer = setInterval(refresh, 500);
33
+ return () => clearInterval(timer);
34
+ }, [binding, key]);
35
+ return snapshot.key === key ? snapshot.rows : [];
36
+ }