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.
- package/README.md +16 -3
- package/package.json +1 -1
- package/plugins/cron-runner/README.md +23 -0
- package/plugins/cron-runner/commands/cron.md +7 -1
- package/plugins/cron-runner/plugin.js +9 -2
- package/plugins/cron-runner/plugin.ts +10 -2
- package/plugins/cron-runner/src/commands.js +112 -25
- package/plugins/cron-runner/src/commands.ts +154 -33
- package/plugins/cron-runner/src/contract.js +70 -0
- package/plugins/cron-runner/src/contract.ts +70 -0
- package/plugins/cron-runner/src/requests.js +22 -13
- package/plugins/cron-runner/src/requests.ts +34 -14
- package/plugins/cron-runner/src/runs.js +63 -10
- package/plugins/cron-runner/src/runs.ts +107 -15
- package/plugins/cron-runner/src/scheduler.js +188 -76
- package/plugins/cron-runner/src/scheduler.ts +277 -94
- package/plugins/cron-runner/src/schema.js +52 -17
- package/plugins/cron-runner/src/schema.ts +73 -22
- package/plugins/cron-runner/src/service.js +29 -8
- package/plugins/cron-runner/src/service.ts +71 -18
- package/plugins/cron-runner/src/store.js +92 -30
- package/plugins/cron-runner/src/store.ts +156 -53
- package/plugins/cron-runner/src/transaction.js +24 -0
- package/plugins/cron-runner/src/transaction.ts +36 -0
- package/plugins/cron-runner/src/types.ts +30 -4
- package/plugins/cron-runner/test/lifecycle.test.ts +419 -0
- package/plugins/cron-runner/test/plugin-integration.test.ts +3 -2
- package/plugins/cron-runner/test/reliability.test.ts +2 -2
- package/plugins/cron-runner/test/store-and-scheduler.test.ts +9 -7
- package/plugins/workflow-runner/plugin.js +1 -0
- package/plugins/workflow-runner/plugin.ts +1 -0
- package/plugins/workflow-runner/src/index.js +1 -0
- package/plugins/workflow-runner/src/index.ts +2 -0
- package/plugins/workflow-runner/src/runner.js +6 -1
- package/plugins/workflow-runner/src/runner.ts +5 -1
- package/plugins/workflow-runner/src/types.ts +1 -0
- package/plugins/workflow-runner/test/api.test.ts +1 -0
- package/plugins/workflow-runner/test/apiCapabilities.test.ts +4 -0
- package/plugins/workflow-runner/test/apiConcurrencyGate.test.ts +1 -0
- package/plugins/workflow-runner/test/childWorkflow.test.ts +19 -0
- package/plugins/workflow-runner/test/embeddedExecution.test.ts +23 -3
- package/src/advisor/README.md +17 -6
- package/src/advisor/advisorNudge.js +23 -3
- package/src/advisor/advisorNudge.ts +20 -3
- package/src/advisor/deliveryReview.js +9 -2
- package/src/advisor/deliveryReview.ts +10 -2
- package/src/cli/args.js +1 -0
- package/src/cli/args.ts +1 -0
- package/src/cli/headlessTurn.js +143 -0
- package/src/cli/headlessTurn.ts +187 -0
- package/src/cli/lifecycle.js +52 -0
- package/src/cli/lifecycle.ts +59 -0
- package/src/cli/print.js +91 -240
- package/src/cli/print.ts +99 -301
- package/src/cli/quickModelSetup.js +3 -0
- package/src/cli/quickModelSetup.tsx +3 -0
- package/src/cli/streamJson.js +244 -334
- package/src/cli/streamJson.ts +248 -416
- package/src/cli/wizards/contextAdvisorWizard.js +0 -7
- package/src/cli/wizards/contextAdvisorWizard.tsx +0 -11
- package/src/cli/wizards/providerPresets.js +25 -14
- package/src/cli/wizards/providerPresets.ts +25 -14
- package/src/cli/wizards/providerWizard.js +29 -11
- package/src/cli/wizards/providerWizard.tsx +29 -11
- package/src/config/configDefaults.js +2 -2
- package/src/config/configDefaults.ts +2 -2
- package/src/config/configDiagnostics.js +7 -3
- package/src/config/configDiagnostics.ts +6 -3
- package/src/config/configFile.ts +1 -1
- package/src/context/compact.js +40 -10
- package/src/context/compact.ts +51 -12
- package/src/context/compactResources.js +39 -0
- package/src/context/compactResources.ts +35 -0
- package/src/context/manualCompact.js +20 -0
- package/src/context/manualCompact.ts +28 -0
- package/src/llm/client.js +4 -0
- package/src/llm/client.ts +4 -0
- package/src/llm/messageProvenance.js +1 -1
- package/src/llm/messageProvenance.ts +1 -1
- package/src/loop/README.md +4 -2
- package/src/loop/deliveryIntent.js +3 -2
- package/src/loop/deliveryIntent.ts +4 -2
- package/src/loop/messages.js +1 -0
- package/src/loop/messages.ts +1 -0
- package/src/loop/options.ts +2 -0
- package/src/loop.js +10 -2
- package/src/loop.ts +9 -2
- package/src/main.js +40 -45
- package/src/main.tsx +33 -52
- package/src/plugin-sdk.js +1 -1
- package/src/plugin-sdk.ts +1 -1
- package/src/plugins/artifactDelivery.js +76 -0
- package/src/plugins/artifactDelivery.ts +76 -0
- package/src/plugins/pluginApi.ts +4 -0
- package/src/plugins/pluginRunner.js +2 -0
- package/src/plugins/pluginRunner.ts +3 -0
- package/src/prompts/delegation.js +2 -2
- package/src/prompts/delegation.ts +2 -2
- package/src/prompts/policyRegistry.js +7 -5
- package/src/prompts/policyRegistry.ts +7 -5
- package/src/prompts/promptAssembly.js +2 -2
- package/src/prompts/promptAssembly.ts +2 -2
- package/src/runtime/requestIntent.js +86 -0
- package/src/runtime/requestIntent.ts +66 -0
- package/src/runtime/systemEvents.js +10 -1
- package/src/runtime/systemEvents.ts +9 -1
- package/src/session/commandTranscript.js +76 -0
- package/src/session/commandTranscript.ts +77 -0
- package/src/session/executionOutcome.js +25 -0
- package/src/session/executionOutcome.ts +34 -0
- package/src/session/runAgentTurn.js +8 -1
- package/src/session/runAgentTurn.ts +10 -1
- package/src/session/runTurn.js +40 -15
- package/src/session/runTurn.ts +38 -12
- package/src/session/sessionState.js +7 -2
- package/src/session/sessionState.ts +7 -2
- package/src/team/onlineToolContract.js +1 -0
- package/src/team/onlineToolContract.ts +1 -0
- package/src/tools/advisor/advisor.js +73 -30
- package/src/tools/advisor/advisor.ts +73 -33
- package/src/tools/advisor/advisorCoordination.js +44 -0
- package/src/tools/advisor/advisorCoordination.ts +45 -0
- package/src/tools/advisor/advisorDescription.js +1 -1
- package/src/tools/advisor/advisorDescription.ts +1 -1
- package/src/tools/agent/README.md +2 -0
- package/src/tools/agent/agent.js +7 -3
- package/src/tools/agent/agent.ts +7 -3
- package/src/tools/agent/agentHandoff.js +2 -1
- package/src/tools/agent/agentHandoff.ts +2 -1
- package/src/tools/agent/agentTaskService.js +26 -5
- package/src/tools/agent/agentTaskService.ts +25 -5
- package/src/tools/agent/agentTypes.js +2 -2
- package/src/tools/agent/agentTypes.ts +2 -2
- package/src/tools/agent/baselineAttach.js +14 -7
- package/src/tools/agent/baselineAttach.ts +14 -7
- package/src/tools/applypatch/applyPatch.js +39 -13
- package/src/tools/applypatch/applyPatch.ts +35 -15
- package/src/tools/bash/bash.js +3 -0
- package/src/tools/bash/bash.ts +3 -0
- package/src/tools/capabilities.js +1 -0
- package/src/tools/capabilities.ts +1 -0
- package/src/tools/download/download.js +147 -11
- package/src/tools/download/download.ts +193 -17
- package/src/tools/edit/edit.js +4 -4
- package/src/tools/edit/edit.ts +4 -4
- package/src/tools/edit/multi-edit.js +2 -2
- package/src/tools/edit/multi-edit.ts +2 -2
- package/src/tools/index.js +2 -0
- package/src/tools/index.ts +2 -0
- package/src/tools/powershell/powershell.js +2 -0
- package/src/tools/powershell/powershell.ts +2 -0
- package/src/tools/schedule/schedule.js +184 -0
- package/src/tools/schedule/schedule.ts +214 -0
- package/src/tools/shared/fileUtils.js +16 -6
- package/src/tools/shared/fileUtils.ts +15 -6
- package/src/tools/tasks/backgroundTaskService.js +108 -12
- package/src/tools/tasks/backgroundTaskService.ts +106 -14
- package/src/tools/tasks/taskOutput.js +15 -5
- package/src/tools/tasks/taskOutput.ts +13 -5
- package/src/tools/tasks/taskStop.js +2 -2
- package/src/tools/tasks/taskStop.ts +2 -2
- package/src/tools/toolPromptGuides.js +4 -3
- package/src/tools/toolPromptGuides.ts +4 -3
- package/src/tools/webfetch/webfetch.js +1 -1
- package/src/tools/webfetch/webfetch.ts +1 -1
- package/src/types.ts +6 -0
- package/src/ui/App.js +3 -1
- package/src/ui/App.tsx +2 -0
- package/src/ui/InputBox.js +2 -2
- package/src/ui/InputBox.tsx +2 -2
- package/src/ui/LiveArea.js +6 -1
- package/src/ui/LiveArea.tsx +6 -1
- package/src/ui/MessageList.js +2 -0
- package/src/ui/MessageList.tsx +2 -0
- package/src/ui/README.md +8 -2
- package/src/ui/activityPresentation.js +23 -3
- package/src/ui/activityPresentation.ts +22 -3
- package/src/ui/backgroundWake.js +20 -4
- package/src/ui/backgroundWake.ts +19 -4
- package/src/ui/commandTranscript.js +2 -69
- package/src/ui/commandTranscript.ts +2 -71
- package/src/ui/hooks/useBackgroundAgents.js +33 -0
- package/src/ui/hooks/useBackgroundAgents.ts +36 -0
- package/src/ui/hooks/useChat.js +46 -25
- package/src/ui/hooks/useChat.ts +36 -23
- package/src/web/protocol.ts +5 -2
- package/src/cli/wizards/advisorWizard.js +0 -152
- package/src/cli/wizards/advisorWizard.tsx +0 -203
package/src/cli/streamJson.ts
CHANGED
|
@@ -1,99 +1,29 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
* ------------------------------------------------------------
|
|
5
|
-
* 与 print.ts 的 text/json 一次性契约**并列、互不影响**(print.ts 一行未动):
|
|
6
|
-
* - text : 纯文本答案(向后兼容)
|
|
7
|
-
* - json : 退出时一行结局契约
|
|
8
|
-
* - stream-json(本文件): 把 runQuery 的**每个 LoopEvent 作为一行 JSON**
|
|
9
|
-
* 实时写 stdout(jsonl)。给 webchat 本地服务 broker 用 —— 它 spawn 本模式、
|
|
10
|
-
* 逐行转发成 WebSocket event 帧。也是给网关预留的"流式子进程"契约。
|
|
11
|
-
*
|
|
12
|
-
* 约定:
|
|
13
|
-
* - stdout 只允许 jsonl 事件流(一行一个 JSON.stringify(LoopEvent)),含「问答 over wire」
|
|
14
|
-
* 的出站事件 `{type:'ask',requestId,questions}`(AskUserQuestion 在远程通道弹问题)。
|
|
15
|
-
* - stdin 是**逐行 JSON 控制通道**(见 attachStdinChannel):首行 `{type:'prompt',text}` 为本轮输入,
|
|
16
|
-
* 后续 `{type:'ask_answer',requestId,answers}` 回灌用户选择。兼容:首行非控制消息 → 整段当裸 prompt。
|
|
17
|
-
* argv 也可给 prompt(此时 stdin 全部行按 ask_answer 解析)。--compact 走压缩动作(无需 prompt)。
|
|
18
|
-
* - 跑完 / 中断 / 出错都先 saveContext 再退出(finalize 还会 unref stdin,让本轮结束后进程能退出)。
|
|
19
|
-
* ============================================================
|
|
2
|
+
* One-turn JSONL transport. stdin carries either a raw prompt or prompt/ask_answer
|
|
3
|
+
* control frames. Persistence, memory and resource ownership live in runHeadlessTurn.
|
|
20
4
|
*/
|
|
21
|
-
|
|
22
|
-
import { previousUserRequest } from '../memory/recallQuery.js';
|
|
23
|
-
import { backgroundCompletionFields } from '../runtime/backgroundCompletion.js';
|
|
24
5
|
import crypto from 'node:crypto';
|
|
25
6
|
import { getWorkingDir } from '../bootstrap/workingDir.js';
|
|
26
|
-
import {
|
|
27
|
-
import {
|
|
28
|
-
import {
|
|
29
|
-
import {
|
|
30
|
-
import { saveContext } from '../context/persistContext.js';
|
|
7
|
+
import { manualCompactNotice } from '../context/compact.js';
|
|
8
|
+
import { compactSession } from '../context/manualCompact.js';
|
|
9
|
+
import { getContextPath } from '../context/persistContext.js';
|
|
10
|
+
import { createPromptCacheContext } from '../llm/promptCache.js';
|
|
31
11
|
import { setAskHandler, type AskAnswer } from '../askBridge.js';
|
|
32
|
-
// attachStdinChannel 的公开签名引用 AskAnswer → 从本模块一并 re-export,
|
|
33
|
-
// 供消费者(含 test/streamJson.askChannel.test.ts)从同一入口导入。
|
|
34
12
|
export type { AskAnswer } from '../askBridge.js';
|
|
35
13
|
import { normalizeImageDetail } from '../multimodal.js';
|
|
36
14
|
import type { ImageInputSpec, Message, Provider } from '../types.js';
|
|
37
|
-
import {
|
|
38
|
-
import { buildTransientPromptBundle, browserPromptRuntime } from '../prompts/system.js';
|
|
39
|
-
import { refreshStableSystemPrompt } from '../prompts/stableSystemPrompt.js';
|
|
40
|
-
import {
|
|
41
|
-
getOrCreateSessionState,
|
|
42
|
-
sessionStateKey,
|
|
43
|
-
} from '../session/sessionState.js';
|
|
44
|
-
import {
|
|
45
|
-
type BackgroundTaskState,
|
|
46
|
-
listRunningBackgroundTasks,
|
|
47
|
-
stopAllBackgroundTasks,
|
|
48
|
-
} from '../tools/tasks/backgroundTaskService.js';
|
|
49
|
-
import { hydrateSessionWorktree } from '../tools/worktree/sessionWorktree.js';
|
|
50
|
-
import { ALL_TOOLS } from '../tools/index.js';
|
|
51
|
-
import { classifyComputerAutomationIntent } from '../tools/computeruse/computerIntent.js';
|
|
52
|
-
import { createPromptCacheContext } from '../llm/promptCache.js';
|
|
53
|
-
import {
|
|
54
|
-
createAgentRuntimeContext,
|
|
55
|
-
filterToolsForRuntime,
|
|
56
|
-
memoryContextFromRuntime,
|
|
57
|
-
} from '../runtime/agentRuntimeContext.js';
|
|
15
|
+
import { extractFlagValue } from './args.js';
|
|
58
16
|
import { extractImageOptions, extractPromptArgs } from './print.js';
|
|
59
|
-
import type
|
|
60
|
-
import {
|
|
61
|
-
import { resolveLocalBrowserRun, disposeLocalBrowsers, type BrowserCliMode } from './browser.js';
|
|
17
|
+
import { runHeadlessTurn, type HeadlessOptions } from './headlessTurn.js';
|
|
18
|
+
import { createCliLifecycle, flushCliOutput } from './lifecycle.js';
|
|
62
19
|
|
|
63
|
-
interface StreamJsonOptions {
|
|
64
|
-
maxTurns?: number;
|
|
65
|
-
/** true 时执行一次压缩(对应 Web 的 /compact),忽略 prompt。 */
|
|
20
|
+
interface StreamJsonOptions extends HeadlessOptions {
|
|
66
21
|
compact?: boolean;
|
|
67
|
-
/**
|
|
68
|
-
* `--session <id>` 解析出的会话文件路径(main.tsx 算好传入)。缺省退回
|
|
69
|
-
* saveContext 的默认路径(= default session)。必须和 initialHistory 的
|
|
70
|
-
* 加载路径一致,否则出现"读 session A、存回 default"的读写分裂。
|
|
71
|
-
*/
|
|
72
|
-
sessionFile?: string;
|
|
73
|
-
workspace?: { cwd: string; sessionId: string };
|
|
74
|
-
/** 本机长期记忆权限,由 main.tsx 判定后传入;stream-json 默认 denied(见 resolveMemoryAccess)。 */
|
|
75
|
-
memoryAccess?: import('../runtime/agentRuntimeContext.js').MemoryAccessInput;
|
|
76
|
-
/** 非交互 Computer Use 必须显式启用;缺省 disabled。 */
|
|
77
|
-
computerUseMode?: ComputerUseCliMode;
|
|
78
|
-
/** Explicit opt-in directory for chronological Computer Use diagnostics. */
|
|
79
|
-
computerUseTraceDir?: string;
|
|
80
|
-
browserMode?: BrowserCliMode;
|
|
81
22
|
}
|
|
82
23
|
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
process.stdout.write(`${JSON.stringify(ev)}\n`);
|
|
87
|
-
} catch {
|
|
88
|
-
/* ignore */
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
function firstUserTitle(history: Message[]): string | undefined {
|
|
93
|
-
const u = history.find((m) => m.role === 'user');
|
|
94
|
-
if (!u) return undefined;
|
|
95
|
-
if (typeof u.content === 'string') return u.content;
|
|
96
|
-
return u.content.find((p) => p.type === 'text')?.text;
|
|
24
|
+
function emitLine(event: unknown): void {
|
|
25
|
+
if (!process.stdout.destroyed)
|
|
26
|
+
process.stdout.write(JSON.stringify(event) + '\n');
|
|
97
27
|
}
|
|
98
28
|
|
|
99
29
|
type PromptImageWire =
|
|
@@ -136,110 +66,121 @@ function parseWireImages(raw: unknown): ImageInputSpec[] {
|
|
|
136
66
|
return out;
|
|
137
67
|
}
|
|
138
68
|
|
|
139
|
-
|
|
140
|
-
* stdin 控制通道:把 stdin 从「一次性裸 prompt」升级为**逐行 JSON 控制通道**,
|
|
141
|
-
* 支撑「问答 over wire」的入站半边。两种控制消息:
|
|
142
|
-
* - `{ type:'prompt', text }` —— 首行,本轮的用户输入(替代裸 prompt)
|
|
143
|
-
* - `{ type:'ask_answer', requestId, answers }` —— AskUserQuestion 的回答,按 requestId 关联
|
|
144
|
-
*
|
|
145
|
-
* 向后兼容:首个非空行**不是** `{type:'prompt'}` 控制消息时,判定为 legacy 模式 ——
|
|
146
|
-
* 整段 stdin 当裸 prompt 读到 EOF(保 `echo "x" | minimal-agent -p --output-format stream-json` 仍可用,
|
|
147
|
-
* legacy 下天然无交互、一次性)。argv 已给 prompt 时,stdin 全部行都按 ask_answer 解析。
|
|
148
|
-
*
|
|
149
|
-
* 返回 `{ prompt, control }`:`control=true` **仅**当 prompt 来自 `{type:'prompt'}` 控制行
|
|
150
|
-
* (= broker 在管理本子进程、会回灌 ask_answer);argv / 裸管道 / TTY / EOF 兜底均为 `false`
|
|
151
|
-
* (无人回灌 → 调用方据此**不注册** wire ask handler,让 askBridge 内置「自动选推荐项」兜底,
|
|
152
|
-
* 避免模型提问后永等挂死)。同时把 ask_answer 路由给 onAskAnswer。stdin 全程保持打开,
|
|
153
|
-
* 直到子进程结束(broker 在 turn 末 end stdin)。
|
|
154
|
-
*/
|
|
155
|
-
export function attachStdinChannel(opts: {
|
|
69
|
+
interface ChannelOptions {
|
|
156
70
|
argvPrompt?: string;
|
|
157
71
|
onAskAnswer: (requestId: string, answers: AskAnswer[]) => void;
|
|
158
|
-
/** 输入流;默认 process.stdin(测试可注入 PassThrough 驱动)。 */
|
|
159
72
|
input?: NodeJS.ReadableStream & { isTTY?: boolean };
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
73
|
+
signal?: AbortSignal;
|
|
74
|
+
onDisconnect?: (error?: Error) => void;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function openStdinChannel(opts: ChannelOptions) {
|
|
165
78
|
const input = opts.input ?? process.stdin;
|
|
166
|
-
|
|
79
|
+
let dispose = () => {};
|
|
80
|
+
const prompt = new Promise<{
|
|
167
81
|
prompt: string;
|
|
168
82
|
control: boolean;
|
|
169
83
|
imageInputs?: ImageInputSpec[];
|
|
170
|
-
}>((
|
|
171
|
-
let
|
|
172
|
-
|
|
84
|
+
}>((resolve, reject) => {
|
|
85
|
+
let resolved = false;
|
|
86
|
+
let ended = false;
|
|
87
|
+
let legacy = false;
|
|
88
|
+
let buf = '';
|
|
89
|
+
const finish = (
|
|
173
90
|
text: string,
|
|
174
91
|
control: boolean,
|
|
175
|
-
|
|
176
|
-
)
|
|
177
|
-
if (
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
);
|
|
92
|
+
images?: ImageInputSpec[],
|
|
93
|
+
) => {
|
|
94
|
+
if (resolved) return;
|
|
95
|
+
resolved = true;
|
|
96
|
+
resolve({
|
|
97
|
+
prompt: text,
|
|
98
|
+
control,
|
|
99
|
+
...(images?.length ? { imageInputs: images } : {}),
|
|
100
|
+
});
|
|
184
101
|
};
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
let buf = '';
|
|
195
|
-
let legacy = false;
|
|
196
|
-
input.setEncoding('utf8');
|
|
197
|
-
input.on('data', (chunk: string) => {
|
|
102
|
+
const fail = (error: Error) => {
|
|
103
|
+
if (ended) return;
|
|
104
|
+
ended = true;
|
|
105
|
+
dispose();
|
|
106
|
+
if (!resolved) reject(error);
|
|
107
|
+
opts.onDisconnect?.(error);
|
|
108
|
+
};
|
|
109
|
+
const onData = (chunk: string) => {
|
|
198
110
|
buf += chunk;
|
|
199
|
-
if (
|
|
111
|
+
if (buf.length > 8 * 1024 * 1024)
|
|
112
|
+
return fail(new Error('stdin frame exceeds 8 Mi characters'));
|
|
113
|
+
if (legacy) return;
|
|
200
114
|
let nl: number;
|
|
201
115
|
while ((nl = buf.indexOf('\n')) >= 0) {
|
|
202
116
|
const line = buf.slice(0, nl);
|
|
203
117
|
buf = buf.slice(nl + 1);
|
|
204
118
|
if (!line.trim()) continue;
|
|
205
|
-
let msg:
|
|
206
|
-
type?: string;
|
|
207
|
-
text?: unknown;
|
|
208
|
-
images?: unknown;
|
|
209
|
-
requestId?: unknown;
|
|
210
|
-
answers?: unknown;
|
|
211
|
-
} | null = null;
|
|
119
|
+
let msg: any;
|
|
212
120
|
try {
|
|
213
121
|
msg = JSON.parse(line);
|
|
214
122
|
} catch {
|
|
215
123
|
msg = null;
|
|
216
124
|
}
|
|
217
|
-
if (!
|
|
218
|
-
if (msg
|
|
219
|
-
|
|
125
|
+
if (!resolved) {
|
|
126
|
+
if (msg?.type === 'prompt' && typeof msg.text === 'string') {
|
|
127
|
+
finish(msg.text, true, parseWireImages(msg.images));
|
|
220
128
|
} else {
|
|
221
|
-
// 首行不是 prompt 控制消息 → legacy:把它放回去,整段当裸 prompt 读到 EOF
|
|
222
129
|
legacy = true;
|
|
223
|
-
|
|
130
|
+
// Preserve the consumed delimiter even if this chunk ends at it.
|
|
131
|
+
buf = line + '\n' + buf;
|
|
224
132
|
return;
|
|
225
133
|
}
|
|
226
134
|
} else if (
|
|
227
|
-
msg &&
|
|
228
|
-
msg.type === 'ask_answer' &&
|
|
135
|
+
msg?.type === 'ask_answer' &&
|
|
229
136
|
typeof msg.requestId === 'string'
|
|
230
137
|
) {
|
|
231
138
|
opts.onAskAnswer(
|
|
232
139
|
msg.requestId,
|
|
233
|
-
Array.isArray(msg.answers) ?
|
|
140
|
+
Array.isArray(msg.answers) ? msg.answers : [],
|
|
234
141
|
);
|
|
235
142
|
}
|
|
236
143
|
}
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
144
|
+
};
|
|
145
|
+
const onEnd = () => {
|
|
146
|
+
if (ended) return;
|
|
147
|
+
ended = true;
|
|
148
|
+
dispose();
|
|
149
|
+
finish(buf.trim(), false);
|
|
150
|
+
opts.onDisconnect?.();
|
|
151
|
+
};
|
|
152
|
+
const onClose = () => {
|
|
153
|
+
if (!ended) fail(new Error('stdin closed before EOF'));
|
|
154
|
+
};
|
|
155
|
+
const onAbort = () => fail(new DOMException('Interrupted', 'AbortError'));
|
|
156
|
+
dispose = () => {
|
|
157
|
+
input.removeListener('data', onData);
|
|
158
|
+
input.removeListener('end', onEnd);
|
|
159
|
+
input.removeListener('error', fail);
|
|
160
|
+
input.removeListener('close', onClose);
|
|
161
|
+
opts.signal?.removeEventListener('abort', onAbort);
|
|
162
|
+
input.pause();
|
|
163
|
+
};
|
|
164
|
+
if (opts.signal?.aborted) return onAbort();
|
|
165
|
+
if (opts.argvPrompt !== undefined) finish(opts.argvPrompt, false);
|
|
166
|
+
if (input.isTTY) {
|
|
167
|
+
finish('', false);
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
input.setEncoding('utf8');
|
|
171
|
+
input.on('data', onData);
|
|
172
|
+
input.once('end', onEnd);
|
|
173
|
+
input.once('error', fail);
|
|
174
|
+
input.once('close', onClose);
|
|
175
|
+
opts.signal?.addEventListener('abort', onAbort, { once: true });
|
|
176
|
+
if ((input as { readableEnded?: boolean }).readableEnded) onEnd();
|
|
242
177
|
});
|
|
178
|
+
return { prompt, dispose: () => dispose() };
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** Compatibility entry for channel parser tests and embedded callers. */
|
|
182
|
+
export function attachStdinChannel(opts: ChannelOptions) {
|
|
183
|
+
return openStdinChannel(opts).prompt;
|
|
243
184
|
}
|
|
244
185
|
|
|
245
186
|
export async function runStreamJsonMode(
|
|
@@ -247,281 +188,172 @@ export async function runStreamJsonMode(
|
|
|
247
188
|
args: string[],
|
|
248
189
|
initialHistory: Message[],
|
|
249
190
|
options: StreamJsonOptions,
|
|
250
|
-
): Promise<
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
`${running.length} 个后台任务在本次结束时仍在运行,进程退出会终止它们,其结果未经验证:` +
|
|
273
|
-
running.map((task) => `${task.id}(${task.command.slice(0, 80)})`).join(';'),
|
|
274
|
-
});
|
|
275
|
-
}
|
|
276
|
-
if (liveBackgroundTasks) await stopAllBackgroundTasks(liveBackgroundTasks);
|
|
277
|
-
await disposeLocalBrowsers();
|
|
278
|
-
// 释放 stdin:attachStdinChannel 的 'data' 监听会让进程在本轮结束后**仍存活**
|
|
279
|
-
// (等下一行输入)→ broker 永远收不到子进程 close、web 端 conn.running 卡死。
|
|
280
|
-
// turn 已结束(无挂起提问),unref 让 stdout 排空后进程自然退出;中途挂起期间
|
|
281
|
-
// 不会走到这里,故等答案时进程仍被 stdin 监听保活。
|
|
282
|
-
try {
|
|
283
|
-
process.stdin.unref();
|
|
284
|
-
} catch {
|
|
285
|
-
/* 某些 stdin 类型无 unref,忽略 */
|
|
286
|
-
}
|
|
287
|
-
setAskHandler(null); // 注销 handler,避免全局污染(测试复用 / 同进程多次调用)
|
|
288
|
-
await saveContext(history, options.sessionFile);
|
|
289
|
-
})();
|
|
290
|
-
return finalizePromise;
|
|
191
|
+
): Promise<number> {
|
|
192
|
+
const lifecycle = createCliLifecycle();
|
|
193
|
+
let channel: ReturnType<typeof openStdinChannel> | undefined;
|
|
194
|
+
let inputClosed = false;
|
|
195
|
+
let channelFailure: Error | undefined;
|
|
196
|
+
let done = false;
|
|
197
|
+
let code = 0;
|
|
198
|
+
let interruptedEmitted = false;
|
|
199
|
+
const asks = new Map<
|
|
200
|
+
string,
|
|
201
|
+
{
|
|
202
|
+
resolve: (a: AskAnswer[]) => void;
|
|
203
|
+
reject: (e: Error) => void;
|
|
204
|
+
cleanup: () => void;
|
|
205
|
+
}
|
|
206
|
+
>();
|
|
207
|
+
const rejectAsks = (error: Error) => {
|
|
208
|
+
for (const ask of asks.values()) {
|
|
209
|
+
ask.cleanup();
|
|
210
|
+
ask.reject(error);
|
|
211
|
+
}
|
|
212
|
+
asks.clear();
|
|
291
213
|
};
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
214
|
+
const disconnect = (error?: Error) => {
|
|
215
|
+
inputClosed = true;
|
|
216
|
+
if (asks.size || (error && !lifecycle.signal.aborted)) {
|
|
217
|
+
channelFailure =
|
|
218
|
+
error ??
|
|
219
|
+
new Error('interaction_unavailable: stdin 已关闭,无法获取用户回答');
|
|
220
|
+
rejectAsks(channelFailure);
|
|
221
|
+
lifecycle.fail(channelFailure);
|
|
222
|
+
}
|
|
223
|
+
};
|
|
224
|
+
try {
|
|
225
|
+
if (options.compact) {
|
|
296
226
|
emitLine({ type: 'compact_start' });
|
|
297
|
-
const r = await
|
|
298
|
-
|
|
227
|
+
const r = await compactSession({
|
|
228
|
+
sessionFile: options.sessionFile ?? getContextPath(),
|
|
229
|
+
history: initialHistory,
|
|
299
230
|
provider,
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
createPromptCacheContext(
|
|
231
|
+
signal: lifecycle.signal,
|
|
232
|
+
customInstructions: extractFlagValue(args, ['--compact-instructions']),
|
|
233
|
+
promptCache: createPromptCacheContext(
|
|
303
234
|
`workspace:${options.workspace?.cwd ?? getWorkingDir()}:session:${options.workspace?.sessionId ?? 'default'}`,
|
|
304
235
|
),
|
|
305
|
-
);
|
|
306
|
-
history.length = 0;
|
|
307
|
-
history.push(...r.messages);
|
|
308
|
-
emitLine({
|
|
309
|
-
type: 'compact_done',
|
|
310
|
-
before: r.before,
|
|
311
|
-
after: r.after,
|
|
312
|
-
trigger: 'manual',
|
|
313
|
-
mode: r.mode,
|
|
314
|
-
degraded: r.degraded,
|
|
315
|
-
...(r.fallbackReason ? { fallbackReason: r.fallbackReason } : {}),
|
|
316
|
-
...(r.messagesRemoved !== undefined
|
|
317
|
-
? { messagesRemoved: r.messagesRemoved }
|
|
318
|
-
: {}),
|
|
319
|
-
...(r.tokensFreed !== undefined ? { tokensFreed: r.tokensFreed } : {}),
|
|
320
236
|
});
|
|
237
|
+
initialHistory.splice(0, initialHistory.length, ...r.messages);
|
|
238
|
+
if (r.unchangedReason)
|
|
239
|
+
emitLine({ type: 'warning', message: manualCompactNotice(r) });
|
|
240
|
+
else
|
|
241
|
+
emitLine({
|
|
242
|
+
type: 'compact_done',
|
|
243
|
+
before: r.before,
|
|
244
|
+
after: r.after,
|
|
245
|
+
trigger: 'manual',
|
|
246
|
+
mode: r.mode,
|
|
247
|
+
degraded: r.degraded,
|
|
248
|
+
...(r.fallbackReason ? { fallbackReason: r.fallbackReason } : {}),
|
|
249
|
+
...(r.messagesRemoved !== undefined
|
|
250
|
+
? { messagesRemoved: r.messagesRemoved }
|
|
251
|
+
: {}),
|
|
252
|
+
...(r.tokensFreed !== undefined
|
|
253
|
+
? { tokensFreed: r.tokensFreed }
|
|
254
|
+
: {}),
|
|
255
|
+
});
|
|
321
256
|
emitLine({ type: 'turn_done' });
|
|
322
|
-
|
|
257
|
+
done = true;
|
|
258
|
+
} else {
|
|
259
|
+
const words = extractPromptArgs(args);
|
|
260
|
+
channel = openStdinChannel({
|
|
261
|
+
argvPrompt: words.length ? words.join(' ') : undefined,
|
|
262
|
+
signal: lifecycle.signal,
|
|
263
|
+
onDisconnect: disconnect,
|
|
264
|
+
onAskAnswer(id, answers) {
|
|
265
|
+
const ask = asks.get(id);
|
|
266
|
+
if (ask) {
|
|
267
|
+
asks.delete(id);
|
|
268
|
+
ask.cleanup();
|
|
269
|
+
ask.resolve(answers);
|
|
270
|
+
}
|
|
271
|
+
},
|
|
272
|
+
});
|
|
273
|
+
const { prompt, control, imageInputs } = await channel.prompt;
|
|
274
|
+
if (!prompt.trim()) throw new Error('未提供非空 prompt');
|
|
275
|
+
if (control)
|
|
276
|
+
setAskHandler((questions, signal) => {
|
|
277
|
+
if (inputClosed) {
|
|
278
|
+
channelFailure = new Error(
|
|
279
|
+
'interaction_unavailable: stdin 已关闭,无法获取用户回答',
|
|
280
|
+
);
|
|
281
|
+
lifecycle.fail(channelFailure);
|
|
282
|
+
return Promise.reject(channelFailure);
|
|
283
|
+
}
|
|
284
|
+
return new Promise<AskAnswer[]>((resolve, reject) => {
|
|
285
|
+
const requestId = crypto.randomUUID();
|
|
286
|
+
const abort = () => {
|
|
287
|
+
asks.delete(requestId);
|
|
288
|
+
signal?.removeEventListener('abort', abort);
|
|
289
|
+
reject(new DOMException('Interrupted', 'AbortError'));
|
|
290
|
+
};
|
|
291
|
+
if (signal?.aborted) return abort();
|
|
292
|
+
asks.set(requestId, {
|
|
293
|
+
resolve,
|
|
294
|
+
reject,
|
|
295
|
+
cleanup: () => signal?.removeEventListener('abort', abort),
|
|
296
|
+
});
|
|
297
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
298
|
+
emitLine({ type: 'ask', requestId, questions });
|
|
299
|
+
});
|
|
300
|
+
});
|
|
301
|
+
const images = extractImageOptions(args);
|
|
302
|
+
for await (const event of runHeadlessTurn(provider, prompt, {
|
|
303
|
+
...options,
|
|
304
|
+
...images,
|
|
305
|
+
imageInputs: [...images.imageInputs, ...(imageInputs ?? [])],
|
|
306
|
+
signal: lifecycle.signal,
|
|
307
|
+
interactive: control,
|
|
308
|
+
host: 'stream-json',
|
|
309
|
+
})) {
|
|
310
|
+
// Transport loss is a host error, not a second "user interrupted" terminal.
|
|
311
|
+
if (
|
|
312
|
+
channelFailure &&
|
|
313
|
+
['error', 'interrupted', 'turn_done'].includes(event.type)
|
|
314
|
+
)
|
|
315
|
+
continue;
|
|
316
|
+
if (event.type === 'error' && event.code !== 'compact_failed') code = 1;
|
|
317
|
+
if (event.type === 'interrupted') {
|
|
318
|
+
code = 130;
|
|
319
|
+
interruptedEmitted = true;
|
|
320
|
+
}
|
|
321
|
+
if (event.type === 'turn_done') done = true;
|
|
322
|
+
emitLine(event);
|
|
323
|
+
}
|
|
324
|
+
if (channelFailure) throw channelFailure;
|
|
325
|
+
if (!done && !code) throw new Error('执行结束但没有终态回执');
|
|
326
|
+
}
|
|
327
|
+
} catch (error) {
|
|
328
|
+
if (lifecycle.signal.aborted && lifecycle.exitCode !== 1) {
|
|
329
|
+
if (!interruptedEmitted) emitLine({ type: 'interrupted' });
|
|
330
|
+
code = lifecycle.exitCode ?? 130;
|
|
331
|
+
} else {
|
|
323
332
|
emitLine({
|
|
324
333
|
type: 'error',
|
|
325
|
-
|
|
326
|
-
|
|
334
|
+
code: options.compact ? 'compact_failed' : 'host_error',
|
|
335
|
+
error: options.compact
|
|
336
|
+
? `手动压缩失败,原上下文保持不变:${(error as Error).message}`
|
|
337
|
+
: error instanceof Error
|
|
338
|
+
? error.message
|
|
339
|
+
: String(error),
|
|
327
340
|
});
|
|
341
|
+
code = 1;
|
|
328
342
|
}
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
{ resolve: (a: AskAnswer[]) => void; reject: (e: Error) => void }
|
|
338
|
-
>();
|
|
339
|
-
const rejectAllAsks = (reason: string): void => {
|
|
340
|
-
for (const p of pendingAsks.values()) p.reject(new Error(reason));
|
|
341
|
-
pendingAsks.clear();
|
|
342
|
-
};
|
|
343
|
-
|
|
344
|
-
const promptArgs = extractPromptArgs(args);
|
|
345
|
-
const cliImageOptions = extractImageOptions(args);
|
|
346
|
-
const {
|
|
347
|
-
prompt,
|
|
348
|
-
control,
|
|
349
|
-
imageInputs: stdinImageInputs,
|
|
350
|
-
} = await attachStdinChannel({
|
|
351
|
-
argvPrompt: promptArgs.length > 0 ? promptArgs.join(' ') : undefined,
|
|
352
|
-
onAskAnswer: (requestId, answers) => {
|
|
353
|
-
const p = pendingAsks.get(requestId);
|
|
354
|
-
if (p) {
|
|
355
|
-
pendingAsks.delete(requestId);
|
|
356
|
-
p.resolve(answers);
|
|
357
|
-
}
|
|
358
|
-
},
|
|
359
|
-
});
|
|
360
|
-
|
|
361
|
-
// 仅当存在控制通道(broker 经 `{type:'prompt'}` 启动、会回灌 ask_answer)才注册 wire handler:
|
|
362
|
-
// 工具调 requestUserChoice → emit `ask` 到 stdout、挂起等 stdin 回灌。无控制通道(argv / 裸管道 /
|
|
363
|
-
// TTY)时**不注册** → 落 askBridge 内置「自动选推荐项」兜底,避免模型提问后永等挂死。
|
|
364
|
-
// loop 在 prompt resolve 后才启动 → 此处注册时机安全(注册前不会有 ask 触发)。
|
|
365
|
-
if (control) {
|
|
366
|
-
setAskHandler(
|
|
367
|
-
(questions) =>
|
|
368
|
-
new Promise<AskAnswer[]>((resolve, reject) => {
|
|
369
|
-
const requestId = crypto.randomUUID();
|
|
370
|
-
pendingAsks.set(requestId, { resolve, reject });
|
|
371
|
-
emitLine({ type: 'ask', requestId, questions });
|
|
372
|
-
}),
|
|
373
|
-
);
|
|
374
|
-
}
|
|
375
|
-
|
|
376
|
-
if (!prompt.trim()) {
|
|
377
|
-
emitLine({
|
|
378
|
-
type: 'error',
|
|
379
|
-
error: '未提供 prompt(argv / stdin 都为空)',
|
|
380
|
-
code: 'llm_error',
|
|
381
|
-
});
|
|
382
|
-
process.exit(1);
|
|
383
|
-
}
|
|
384
|
-
|
|
385
|
-
// 记录最近目录(侧栏用);title 优先用历史里第一条用户消息(稳定),否则用当前 prompt
|
|
386
|
-
await recordRecentDir(getWorkingDir(), firstUserTitle(history) ?? prompt);
|
|
387
|
-
if (options.workspace) {
|
|
388
|
-
await updateSessionMetadata(
|
|
389
|
-
options.workspace.cwd,
|
|
390
|
-
options.workspace.sessionId,
|
|
391
|
-
{
|
|
392
|
-
lastMessagePreview: prompt,
|
|
393
|
-
},
|
|
394
|
-
).catch(() => {});
|
|
395
|
-
}
|
|
396
|
-
|
|
397
|
-
const abortController = new AbortController();
|
|
398
|
-
let interrupted = false;
|
|
399
|
-
process.on('SIGINT', () => {
|
|
400
|
-
if (interrupted) process.exit(130);
|
|
401
|
-
interrupted = true;
|
|
402
|
-
abortController.abort();
|
|
403
|
-
rejectAllAsks('已中断'); // 挂起的提问立即落败,工具回 ok:false → loop 收口 interrupted
|
|
404
|
-
emitLine({ type: 'interrupted' });
|
|
405
|
-
void finalize().finally(() => process.exit(130));
|
|
406
|
-
});
|
|
407
|
-
|
|
408
|
-
try {
|
|
409
|
-
const workspaceRoot = options.workspace?.cwd ?? getWorkingDir();
|
|
410
|
-
const workspace = await workspaceIndexService
|
|
411
|
-
.findByPath(workspaceRoot)
|
|
412
|
-
.catch(() => null);
|
|
413
|
-
const sessionId = options.workspace?.sessionId ?? 'default';
|
|
414
|
-
const sessionState = getOrCreateSessionState(
|
|
415
|
-
sessionStateKey({
|
|
416
|
-
surface: 'headless',
|
|
417
|
-
workspaceId: workspace?.id,
|
|
418
|
-
cwd: workspace?.id ? undefined : workspaceRoot,
|
|
419
|
-
sessionId,
|
|
420
|
-
}),
|
|
421
|
-
);
|
|
422
|
-
liveBackgroundTasks = sessionState.backgroundTasks;
|
|
423
|
-
await hydrateSessionWorktree({
|
|
424
|
-
sessionState,
|
|
425
|
-
workspaceId: workspace?.id,
|
|
426
|
-
sessionId,
|
|
427
|
-
cwd: workspaceRoot,
|
|
428
|
-
});
|
|
429
|
-
const cwd = sessionState.activeWorktree?.path ?? workspaceRoot;
|
|
430
|
-
const conversationKey = `workspace:${workspace?.id ?? workspaceRoot}:session:${sessionId}`;
|
|
431
|
-
const computerRun =
|
|
432
|
-
options.computerUseMode && options.computerUseMode !== 'disabled'
|
|
433
|
-
? createCliComputerRun({
|
|
434
|
-
mode: options.computerUseMode,
|
|
435
|
-
surface: 'cli',
|
|
436
|
-
conversationKey,
|
|
437
|
-
userInput: prompt,
|
|
438
|
-
allowedFileRoots: [cwd],
|
|
439
|
-
supervised: true,
|
|
440
|
-
diagnosticTraceDir: options.computerUseTraceDir,
|
|
441
|
-
})
|
|
442
|
-
: undefined;
|
|
443
|
-
const runtimeContext = createAgentRuntimeContext({
|
|
444
|
-
surface: 'headless',
|
|
445
|
-
host: 'stream-json',
|
|
446
|
-
profile: 'main',
|
|
447
|
-
cwd,
|
|
448
|
-
workspaceId: workspace?.id,
|
|
449
|
-
sessionId,
|
|
450
|
-
owner: options.memoryAccess === 'denied' ? 'untrusted' : 'local-owner',
|
|
451
|
-
memoryAccess: options.memoryAccess ?? 'read-only',
|
|
452
|
-
interactiveAsk: control,
|
|
453
|
-
browser:
|
|
454
|
-
options.browserMode !== 'off'
|
|
455
|
-
? await resolveLocalBrowserRun({
|
|
456
|
-
mode: options.browserMode ?? 'headless',
|
|
457
|
-
conversationKey,
|
|
458
|
-
userInput: prompt,
|
|
459
|
-
allowedUploadRoots: [cwd],
|
|
460
|
-
})
|
|
461
|
-
: undefined,
|
|
462
|
-
computer: computerRun,
|
|
463
|
-
computerIntent: classifyComputerAutomationIntent(
|
|
464
|
-
prompt,
|
|
465
|
-
sessionState.computerAutomation,
|
|
466
|
-
),
|
|
467
|
-
});
|
|
468
|
-
const turnTools = filterToolsForRuntime(ALL_TOOLS, runtimeContext);
|
|
469
|
-
await refreshStableSystemPrompt(history, cwd, turnTools);
|
|
470
|
-
const transientBundle = await buildTransientPromptBundle({
|
|
471
|
-
cwd,
|
|
472
|
-
tools: turnTools,
|
|
473
|
-
runtime: {
|
|
474
|
-
surface: 'headless',
|
|
475
|
-
host: 'stream-json',
|
|
476
|
-
cwd,
|
|
477
|
-
workspaceId: workspace?.id,
|
|
478
|
-
sessionId,
|
|
479
|
-
interactiveAsk: control,
|
|
480
|
-
memoryAccess: runtimeContext.memoryAccess,
|
|
481
|
-
browser: browserPromptRuntime(runtimeContext.browser, provider.supportsVision),
|
|
482
|
-
currentUserInput: prompt,
|
|
483
|
-
previousUserInput: previousUserRequest(history),
|
|
484
|
-
contextWindow: provider.contextWindow,
|
|
485
|
-
},
|
|
486
|
-
}).catch(() => undefined);
|
|
487
|
-
for await (const event of runWithPlugins(prompt, {
|
|
488
|
-
provider,
|
|
489
|
-
history,
|
|
490
|
-
signal: abortController.signal,
|
|
491
|
-
maxTurns: options.maxTurns,
|
|
492
|
-
imageInputs: [
|
|
493
|
-
...cliImageOptions.imageInputs,
|
|
494
|
-
...(stdinImageInputs ?? []),
|
|
495
|
-
],
|
|
496
|
-
parseInlineImages: true,
|
|
497
|
-
imageDetail: cliImageOptions.imageDetail,
|
|
498
|
-
imageMaxLongSidePixel: cliImageOptions.imageMaxLongSidePixel,
|
|
499
|
-
runtimeContext,
|
|
500
|
-
sessionState,
|
|
501
|
-
allowedTools: turnTools.map((tool) => tool.name),
|
|
502
|
-
...(transientBundle ? { transientBundle } : {}),
|
|
503
|
-
promptCache: createPromptCacheContext(
|
|
504
|
-
`workspace:${workspace?.id ?? cwd}:session:${sessionId}`,
|
|
505
|
-
),
|
|
506
|
-
memoryContext: memoryContextFromRuntime(runtimeContext),
|
|
507
|
-
...(computerRun ? { computerRun } : {}),
|
|
508
|
-
})) {
|
|
509
|
-
// event 是 LoopEvent | PluginEvent,原样逐行 emit;前端不识别的插件私有事件会静默忽略
|
|
510
|
-
emitLine(event.type === 'turn_done'
|
|
511
|
-
? { ...event, ...backgroundCompletionFields(liveBackgroundTasks) }
|
|
512
|
-
: event);
|
|
343
|
+
} finally {
|
|
344
|
+
rejectAsks(new Error('CLI turn ended'));
|
|
345
|
+
setAskHandler(null);
|
|
346
|
+
channel?.dispose();
|
|
347
|
+
try {
|
|
348
|
+
process.stdin.unref();
|
|
349
|
+
} catch {
|
|
350
|
+
/* Some input streams cannot be unreferenced. */
|
|
513
351
|
}
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
await finalize();
|
|
519
|
-
process.exit(130);
|
|
352
|
+
try {
|
|
353
|
+
await flushCliOutput();
|
|
354
|
+
} finally {
|
|
355
|
+
lifecycle.dispose();
|
|
520
356
|
}
|
|
521
|
-
emitLine({ type: 'error', error: (e as Error).message, code: 'llm_error' });
|
|
522
|
-
await finalize();
|
|
523
|
-
process.exit(1);
|
|
524
357
|
}
|
|
525
|
-
|
|
526
|
-
await finalize();
|
|
358
|
+
return lifecycle.exitCode ?? code;
|
|
527
359
|
}
|