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/cli/print.ts CHANGED
@@ -23,11 +23,6 @@
23
23
  * ============================================================
24
24
  */
25
25
 
26
- import { previousUserRequest } from '../memory/recallQuery.js';
27
- import { backgroundCompletionFields, type PendingBackgroundTask } from '../runtime/backgroundCompletion.js';
28
- import { getContextPath, saveContext } from '../context/persistContext.js';
29
- import { updateSessionMetadata } from '../context/sessionRegistry.js';
30
- import { workspaceIndexService } from '../context/workspaceIndex.js';
31
26
  import { normalizeImageDetail } from '../multimodal.js';
32
27
  import type {
33
28
  DeliverableManifest,
@@ -41,30 +36,10 @@ import type {
41
36
  TextGenerationStatus,
42
37
  } from '../types.js';
43
38
  import type { PendingRequiredTask } from '../runtime/deliveryGate.js';
44
- import { runWithPlugins } from '../plugins/pluginRunner.js';
45
- import { buildTransientPromptBundle, browserPromptRuntime } from '../prompts/system.js';
46
- import { refreshStableSystemPrompt } from '../prompts/stableSystemPrompt.js';
47
- import {
48
- getOrCreateSessionState,
49
- sessionStateKey,
50
- } from '../session/sessionState.js';
51
- import {
52
- type BackgroundTaskState,
53
- listRunningBackgroundTasks,
54
- stopAllBackgroundTasks,
55
- } from '../tools/tasks/backgroundTaskService.js';
56
- import { hydrateSessionWorktree } from '../tools/worktree/sessionWorktree.js';
57
- import { ALL_TOOLS } from '../tools/index.js';
58
- import { classifyComputerAutomationIntent } from '../tools/computeruse/computerIntent.js';
59
- import { createPromptCacheContext } from '../llm/promptCache.js';
60
- import {
61
- createAgentRuntimeContext,
62
- filterToolsForRuntime,
63
- memoryContextFromRuntime,
64
- } from '../runtime/agentRuntimeContext.js';
65
- import type { ComputerUseCliMode } from './computerUse.js';
66
- import { createCliComputerRun } from './computerUse.js';
67
- import { resolveLocalBrowserRun, disposeLocalBrowsers, type BrowserCliMode } from './browser.js';
39
+ import type { PendingBackgroundTask } from '../runtime/backgroundCompletion.js';
40
+ import { getContextPath } from '../context/persistContext.js';
41
+ import { runHeadlessTurn, type HeadlessOptions } from './headlessTurn.js';
42
+ import { createCliLifecycle, flushCliOutput } from './lifecycle.js';
68
43
  import {
69
44
  BOOLEAN_FLAGS,
70
45
  VALUE_FLAGS,
@@ -83,29 +58,9 @@ type HandleableEvent = LoopEvent;
83
58
  /** 输出格式:text(向后兼容,纯文本)/ json(结构化结局契约,一行 JSON)。 */
84
59
  export type OutputFormat = 'text' | 'json';
85
60
 
86
- interface PrintOptions {
61
+ interface PrintOptions extends HeadlessOptions {
87
62
  verbose: boolean;
88
- /** 输出格式;缺省 'text'(向后兼容)。 */
89
63
  outputFormat?: OutputFormat;
90
- /** 透传给 runQuery 的最大轮数;缺省走 loop 内默认(50)。 */
91
- maxTurns?: number;
92
- /**
93
- * `--session <id>` 解析出的会话文件路径(main.tsx 算好传入)。
94
- * 缺省时退回 `getContextPath()`(= default session),向后兼容。
95
- *
96
- * 必须和 initialHistory 的加载路径保持同一份解析结果——否则会出现
97
- * "从 session A 读、写回 default"的读写分裂(load 用了 --session,
98
- * save 却各自重新调用无参的 getContextPath())。
99
- */
100
- sessionFile?: string;
101
- workspace?: { cwd: string; sessionId: string };
102
- /** 本机长期记忆权限,由 main.tsx 按输出格式 + `--memory-access` 判定后传入(见 resolveMemoryAccess)。 */
103
- memoryAccess?: import('../runtime/agentRuntimeContext.js').MemoryAccessInput;
104
- /** 非交互 Computer Use 必须显式启用;缺省 disabled。 */
105
- computerUseMode?: ComputerUseCliMode;
106
- /** Explicit opt-in directory for chronological Computer Use diagnostics. */
107
- computerUseTraceDir?: string;
108
- browserMode?: BrowserCliMode;
109
64
  }
110
65
 
111
66
  /**
@@ -183,14 +138,6 @@ function warnUnknownEventType(type: unknown): void {
183
138
  );
184
139
  }
185
140
 
186
- function handleEPIPE(
187
- stream: NodeJS.WriteStream,
188
- ): (err: NodeJS.ErrnoException) => void {
189
- return (err) => {
190
- if (err.code === 'EPIPE') stream.destroy();
191
- };
192
- }
193
-
194
141
  export function truncateForDisplay(
195
142
  content: string,
196
143
  max = TOOL_OUTPUT_PREVIEW_MAX,
@@ -315,7 +262,9 @@ export function emitJsonResult(
315
262
  ...(result.pendingRequired?.length
316
263
  ? { pending_required: result.pendingRequired }
317
264
  : {}),
318
- ...(result.pendingBackground?.length ? { pending_background: result.pendingBackground } : {}),
265
+ ...(result.pendingBackground?.length
266
+ ? { pending_background: result.pendingBackground }
267
+ : {}),
319
268
  deliverables,
320
269
  verification: allVerified
321
270
  ? 'passed'
@@ -356,230 +305,65 @@ function trySessionFile(override?: string): string | undefined {
356
305
  export async function runPrintMode(
357
306
  provider: Provider,
358
307
  args: string[],
359
- initialHistory: Message[],
308
+ _initialHistory: Message[],
360
309
  options: PrintOptions,
361
- ): Promise<void> {
362
- // EPIPE 保护:管道断开时不崩溃(如 `bun -p "..." | head -1`)
363
- process.stdout.on('error', handleEPIPE(process.stdout));
364
- process.stderr.on('error', handleEPIPE(process.stderr));
365
-
366
- const outputFormat: OutputFormat = options.outputFormat ?? 'text';
367
- const isJson = outputFormat === 'json';
368
- const imageOptions = extractImageOptions(args);
369
-
370
- const promptArgs = extractPromptArgs(args);
371
- let prompt: string;
372
- if (promptArgs.length > 0) {
373
- prompt = promptArgs.join(' ');
374
- } else if (!process.stdin.isTTY) {
375
- prompt = await readFromStdin();
376
- } else {
377
- console.error('错误: 请提供提示文本或使用管道输入');
378
- process.exit(1);
379
- }
380
-
381
- if (!prompt.trim()) {
382
- console.error('错误: 提示不能为空');
383
- process.exit(1);
384
- }
385
- if (options.workspace) {
386
- await updateSessionMetadata(
387
- options.workspace.cwd,
388
- options.workspace.sessionId,
389
- {
390
- lastMessagePreview: prompt.trim(),
391
- },
392
- ).catch(() => {});
393
- }
394
-
395
- const abortController = new AbortController();
396
- let interrupted = false;
397
-
398
- const history = initialHistory;
399
- // text 模式只关心 buffer;json 模式还要 numTurns / stopReason / error。
400
- // 用同一个对象承载,handleEvent 按 outputFormat 决定写哪些字段。
310
+ ): Promise<number> {
311
+ const lifecycle = createCliLifecycle();
312
+ const format = options.outputFormat ?? 'text';
401
313
  const result: PrintResult = {
402
314
  buffer: '',
403
315
  numTurns: 0,
404
316
  stopReason: undefined,
405
317
  error: null,
406
318
  };
407
-
408
- // 收尾守卫:saveContext + (json) emit 只执行一次,所有退出路径 await 同一个
409
- // promise 再 process.exit。
410
- // 没有它的话:SIGINT 触发 abort 后,SIGINT handler 与 for-await 的 AbortError
411
- // catch 会同时奔向收尾 → 双写 session 文件 + 往 stdout 打两行 JSON(破坏「一行契约」)。
412
- // 用「缓存 promise」而非「布尔 once」是关键:后到的路径必须 await 到 emit 真正
413
- // 完成再退出,否则可能抢先把进程杀掉、导致那一行 JSON 根本没发出。
414
- // 本回合的后台任务表,收尾时如实报告还在跑的那些(见下)。
415
- // 用可变引用而不是直接引 sessionState:那个 const 声明在 finalizeOnce 之后。
416
- let liveBackgroundTasks: BackgroundTaskState | undefined;
417
-
418
- let finalizePromise: Promise<void> | null = null;
419
- function finalizeOnce(): Promise<void> {
420
- if (!finalizePromise) {
421
- finalizePromise = (async () => {
422
- // `-p` 没有空闲唤醒者:进程一退,backgroundTaskService 的 exit 钩子就把
423
- // 还在跑的后台任务杀了。不说出来,宿主拿到的 JSON 与一切正常时逐字节相同,
424
- // 而那个「已在后台开始构建」的结论其实没有任何结果支撑。
425
- const running = listRunningBackgroundTasks(liveBackgroundTasks);
426
- if (running.length > 0) {
427
- result.pendingBackground = backgroundCompletionFields(liveBackgroundTasks).pendingBackground;
428
- result.deliveryStatus = 'delivery_incomplete';
429
- const note =
430
- `${running.length} 个后台任务在本次结束时仍在运行,进程退出会终止它们,其结果未经验证:` +
431
- running.map((task) => `${task.id}(${task.command.slice(0, 80)})`).join(';');
432
- (result.warnings ??= []).push(note);
433
- console.error(`[minimal-agent] ${note}`);
434
- }
435
- if (liveBackgroundTasks) await stopAllBackgroundTasks(liveBackgroundTasks);
436
- await disposeLocalBrowsers();
437
- await saveContext(history, options.sessionFile);
438
- if (isJson) emitJsonResult(result, trySessionFile(options.sessionFile));
439
- })();
440
- }
441
- return finalizePromise;
442
- }
443
-
444
- process.on('SIGINT', () => {
445
- if (interrupted) process.exit(130);
446
- interrupted = true;
447
- abortController.abort();
448
- console.error('\n已中断');
449
- // json 模式:SIGINT 也要给出结构化结局(stop_reason='interrupted')
450
- if (isJson) result.stopReason = 'interrupted';
451
- void finalizeOnce().finally(() => process.exit(130));
452
- });
453
-
319
+ let code = 0;
454
320
  try {
455
- const workspaceRoot = options.workspace?.cwd ?? process.cwd();
456
- const workspace = await workspaceIndexService
457
- .findByPath(workspaceRoot)
458
- .catch(() => null);
459
- const sessionId = options.workspace?.sessionId ?? 'default';
460
- const sessionState = getOrCreateSessionState(
461
- sessionStateKey({
462
- surface: 'cli',
463
- workspaceId: workspace?.id,
464
- cwd: workspace?.id ? undefined : workspaceRoot,
465
- sessionId,
466
- }),
467
- );
468
- liveBackgroundTasks = sessionState.backgroundTasks;
469
- await hydrateSessionWorktree({
470
- sessionState,
471
- workspaceId: workspace?.id,
472
- sessionId,
473
- cwd: workspaceRoot,
474
- });
475
- const cwd = sessionState.activeWorktree?.path ?? workspaceRoot;
476
- const conversationKey = `workspace:${workspace?.id ?? workspaceRoot}:session:${sessionId}`;
477
- const computerRun =
478
- options.computerUseMode && options.computerUseMode !== 'disabled'
479
- ? createCliComputerRun({
480
- mode: options.computerUseMode,
481
- surface: 'cli',
482
- conversationKey,
483
- userInput: prompt,
484
- allowedFileRoots: [cwd],
485
- supervised: true,
486
- diagnosticTraceDir: options.computerUseTraceDir,
487
- })
488
- : undefined;
489
- const runtimeContext = createAgentRuntimeContext({
490
- surface: 'cli',
321
+ const words = extractPromptArgs(args);
322
+ const prompt = words.length
323
+ ? words.join(' ')
324
+ : process.stdin.isTTY
325
+ ? ''
326
+ : await readFromStdin(process.stdin, lifecycle.signal);
327
+ if (!prompt.trim()) throw new Error('请提供非空提示文本或使用管道输入');
328
+ for await (const event of runHeadlessTurn(provider, prompt, {
329
+ ...options,
330
+ ...extractImageOptions(args),
331
+ signal: lifecycle.signal,
332
+ interactive: false,
491
333
  host: 'cli',
492
- profile: 'main',
493
- cwd,
494
- workspaceId: workspace?.id,
495
- sessionId,
496
- owner: options.memoryAccess === 'denied' ? 'untrusted' : 'local-owner',
497
- memoryAccess: options.memoryAccess ?? 'read-only',
498
- interactiveAsk: false,
499
- browser:
500
- options.browserMode !== 'off'
501
- ? await resolveLocalBrowserRun({
502
- mode: options.browserMode ?? 'headless',
503
- conversationKey,
504
- userInput: prompt,
505
- allowedUploadRoots: [cwd],
506
- })
507
- : undefined,
508
- computer: computerRun,
509
- computerIntent: classifyComputerAutomationIntent(
510
- prompt,
511
- sessionState.computerAutomation,
512
- ),
513
- });
514
- const turnTools = filterToolsForRuntime(ALL_TOOLS, runtimeContext);
515
- await refreshStableSystemPrompt(history, cwd, turnTools);
516
- const transientBundle = await buildTransientPromptBundle({
517
- cwd,
518
- tools: turnTools,
519
- runtime: {
520
- surface: 'cli',
521
- host: 'cli',
522
- cwd,
523
- workspaceId: workspace?.id,
524
- sessionId,
525
- interactiveAsk: false,
526
- memoryAccess: runtimeContext.memoryAccess,
527
- browser: browserPromptRuntime(runtimeContext.browser, provider.supportsVision),
528
- currentUserInput: prompt,
529
- previousUserInput: previousUserRequest(history),
530
- contextWindow: provider.contextWindow,
531
- },
532
- }).catch(() => undefined);
533
- for await (const event of runWithPlugins(prompt, {
534
- provider,
535
- history,
536
- signal: abortController.signal,
537
- maxTurns: options.maxTurns,
538
- imageInputs: imageOptions.imageInputs,
539
- parseInlineImages: true,
540
- imageDetail: imageOptions.imageDetail,
541
- imageMaxLongSidePixel: imageOptions.imageMaxLongSidePixel,
542
- allowedTools: turnTools.map((tool) => tool.name),
543
- runtimeContext,
544
- sessionState,
545
- ...(transientBundle ? { transientBundle } : {}),
546
- promptCache: createPromptCacheContext(
547
- `workspace:${workspace?.id ?? cwd}:session:${sessionId}`,
548
- ),
549
- memoryContext: memoryContextFromRuntime(runtimeContext),
550
- ...(computerRun ? { computerRun } : {}),
551
334
  })) {
552
- // event 是 LoopEvent | PluginEvent;handleEvent 只认 LoopEvent,未识别的插件私有事件走 default 静默忽略
553
335
  const handled = handleEvent(
554
- (event.type === 'turn_done'
555
- ? { ...event, ...backgroundCompletionFields(liveBackgroundTasks) }
556
- : event) as HandleableEvent,
336
+ event as HandleableEvent,
557
337
  result,
558
338
  options.verbose,
559
- outputFormat,
339
+ format,
560
340
  );
561
- if (handled.exitCode !== undefined) {
562
- await finalizeOnce();
563
- process.exit(handled.exitCode);
564
- }
341
+ if (handled.exitCode !== undefined) code = handled.exitCode;
342
+ }
343
+ if (!result.stopReason) {
344
+ result.stopReason = 'error';
345
+ result.error = '执行结束但没有终态回执';
346
+ code = 1;
565
347
  }
566
- } catch (e) {
567
- if ((e as Error).name === 'AbortError') {
568
- if (isJson) result.stopReason = 'interrupted';
569
- await finalizeOnce();
570
- process.exit(130);
348
+ } catch (error) {
349
+ result.stopReason = lifecycle.signal.aborted ? 'interrupted' : 'error';
350
+ result.error = error instanceof Error ? error.message : String(error);
351
+ code = lifecycle.exitCode ?? 1;
352
+ if (format === 'text') console.error(result.error);
353
+ } finally {
354
+ if (lifecycle.signal.aborted) {
355
+ result.stopReason = 'interrupted';
356
+ code = lifecycle.exitCode ?? 130;
571
357
  }
572
- console.error(`\n未捕获异常: ${(e as Error).message}`);
573
- if (isJson) {
574
- // 未分类异常按 error 收尾(stopReason 仍为空 → emitJsonResult 兜底 'error')
575
- result.error = result.error ?? (e as Error).message;
358
+ try {
359
+ if (format === 'json' && !process.stdout.destroyed)
360
+ emitJsonResult(result, trySessionFile(options.sessionFile));
361
+ await flushCliOutput();
362
+ } finally {
363
+ lifecycle.dispose();
576
364
  }
577
- await finalizeOnce();
578
- process.exit(1);
579
365
  }
580
-
581
- // 正常跑完(没触发任何 exitCode 退出点)也走同一个收尾(json 模式 emit 一行结局)。
582
- await finalizeOnce();
366
+ return code || (result.stopReason === 'end_turn' ? 0 : 1);
583
367
  }
584
368
 
585
369
  /**
@@ -700,8 +484,10 @@ export function handleEvent(
700
484
  // 托管运行时的生命周期状态(goal 等)。同上:读了就必须输出,
701
485
  // 否则「Agent 自检通过但还没人验收」在宿主眼里与「办完了」逐字节相同。
702
486
  if (event.managedStatus) result.goalStatus = event.managedStatus;
703
- if (event.pendingRequired?.length) result.pendingRequired = event.pendingRequired;
704
- if (event.pendingBackground?.length) result.pendingBackground = event.pendingBackground;
487
+ if (event.pendingRequired?.length)
488
+ result.pendingRequired = event.pendingRequired;
489
+ if (event.pendingBackground?.length)
490
+ result.pendingBackground = event.pendingBackground;
705
491
  if (!isJson && !verbose) console.log(result.buffer);
706
492
  return {};
707
493
 
@@ -714,7 +500,7 @@ export function handleEvent(
714
500
  return {};
715
501
  }
716
502
  // 其余 error 都是终结性的。
717
- if (isJson) {
503
+ {
718
504
  result.stopReason =
719
505
  event.code === 'max_turns'
720
506
  ? 'max_turns'
@@ -722,17 +508,14 @@ export function handleEvent(
722
508
  ? 'stalled'
723
509
  : 'error';
724
510
  result.error = event.error;
725
- // json 模式不在这里打 stdout/stderr;由外层 emitJsonResult 统一输出
511
+ if (!isJson) console.error(`\n错误: ${event.error}`);
726
512
  return { exitCode: 1 };
727
513
  }
728
- // text 模式:保持旧行为(红字 stderr + exitCode 1)
729
- console.error(`\n错误: ${event.error}`);
730
- return { exitCode: 1 };
731
514
 
732
515
  case 'interrupted':
733
516
  // 用户中断:json 模式记 stop_reason;外层退出点(catch / for-await 收尾 / SIGINT)emit。
734
517
  // text 模式无需特殊处理(与旧行为一致:静默忽略,靠 SIGINT handler 退出)。
735
- if (isJson) result.stopReason = 'interrupted';
518
+ result.stopReason = 'interrupted';
736
519
  return {};
737
520
 
738
521
  case 'workflow_progress': {
@@ -765,35 +548,50 @@ export function handleEvent(
765
548
  }
766
549
  }
767
550
 
768
- function readFromStdin(): Promise<string> {
769
- return new Promise((resolve) => {
551
+ /** The timeout applies only before the first byte, never to a live pipe. */
552
+ export function readFromStdin(
553
+ input: NodeJS.ReadableStream = process.stdin,
554
+ signal?: AbortSignal,
555
+ firstByteTimeoutMs = STDIN_TIMEOUT_MS,
556
+ ): Promise<string> {
557
+ return new Promise((resolve, reject) => {
770
558
  let data = '';
771
- let settled = false;
772
-
773
- const timer = setTimeout(() => {
774
- if (!settled) {
775
- settled = true;
776
- resolve('');
777
- }
778
- }, STDIN_TIMEOUT_MS);
779
-
780
- process.stdin.setEncoding('utf8');
781
-
782
- function onData(chunk: string): void {
559
+ let timer: ReturnType<typeof setTimeout> | undefined;
560
+ const cleanup = () => {
561
+ clearTimeout(timer);
562
+ input.removeListener('data', onData);
563
+ input.removeListener('end', onEnd);
564
+ input.removeListener('error', onError);
565
+ input.removeListener('close', onClose);
566
+ signal?.removeEventListener('abort', onAbort);
567
+ input.pause();
568
+ };
569
+ const onData = (chunk: string) => {
570
+ clearTimeout(timer);
783
571
  data += chunk;
784
- }
785
-
786
- function onEnd(): void {
787
- if (!settled) {
788
- clearTimeout(timer);
789
- settled = true;
790
- resolve(data.trim());
791
- }
792
- }
793
-
794
- process.stdin.on('data', onData);
795
- process.stdin.on('end', onEnd);
572
+ };
573
+ const onEnd = () => {
574
+ cleanup();
575
+ resolve(data.trim());
576
+ };
577
+ const onError = (error: Error) => {
578
+ cleanup();
579
+ reject(error);
580
+ };
581
+ const onClose = () => onError(new Error('stdin 在输入完成前断开'));
582
+ const onAbort = () =>
583
+ onError(new DOMException('Interrupted', 'AbortError'));
584
+ if (signal?.aborted) return onAbort();
585
+ input.setEncoding('utf8');
586
+ input.on('data', onData);
587
+ input.once('end', onEnd);
588
+ input.once('error', onError);
589
+ input.once('close', onClose);
590
+ signal?.addEventListener('abort', onAbort, { once: true });
591
+ if ((input as { readableEnded?: boolean }).readableEnded) return onEnd();
592
+ timer = setTimeout(
593
+ () => onError(new Error('等待 stdin 输入超时;请传入提示或关闭空管道')),
594
+ firstByteTimeoutMs,
595
+ );
796
596
  });
797
597
  }
798
-
799
- export { readFromStdin };
@@ -13,6 +13,9 @@ export function QuickModelSetup({ onDone }) {
13
13
  void configService.reload().then((snapshot) => {
14
14
  setReadOnly(snapshot.readOnly);
15
15
  setModels(snapshot.config?.models ?? []);
16
+ }).catch((error) => {
17
+ setMessage(error.message);
18
+ setModels([]);
16
19
  });
17
20
  }, []);
18
21
  useInput((input, key) => {
@@ -20,6 +20,9 @@ export function QuickModelSetup({ onDone }: Props): JSX.Element {
20
20
  void configService.reload().then((snapshot) => {
21
21
  setReadOnly(snapshot.readOnly);
22
22
  setModels(snapshot.config?.models ?? []);
23
+ }).catch((error: Error) => {
24
+ setMessage(error.message);
25
+ setModels([]);
23
26
  });
24
27
  }, []);
25
28
  useInput((input, key) => {