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.js
CHANGED
|
@@ -1,63 +1,22 @@
|
|
|
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
|
-
import { previousUserRequest } from '../memory/recallQuery.js';
|
|
22
|
-
import { backgroundCompletionFields } from '../runtime/backgroundCompletion.js';
|
|
23
5
|
import crypto from 'node:crypto';
|
|
24
6
|
import { getWorkingDir } from '../bootstrap/workingDir.js';
|
|
25
|
-
import {
|
|
26
|
-
import {
|
|
27
|
-
import {
|
|
28
|
-
import {
|
|
29
|
-
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';
|
|
30
11
|
import { setAskHandler } from '../askBridge.js';
|
|
31
12
|
import { normalizeImageDetail } from '../multimodal.js';
|
|
32
|
-
import {
|
|
33
|
-
import { buildTransientPromptBundle, browserPromptRuntime } from '../prompts/system.js';
|
|
34
|
-
import { refreshStableSystemPrompt } from '../prompts/stableSystemPrompt.js';
|
|
35
|
-
import { getOrCreateSessionState, sessionStateKey, } from '../session/sessionState.js';
|
|
36
|
-
import { listRunningBackgroundTasks, stopAllBackgroundTasks, } from '../tools/tasks/backgroundTaskService.js';
|
|
37
|
-
import { hydrateSessionWorktree } from '../tools/worktree/sessionWorktree.js';
|
|
38
|
-
import { ALL_TOOLS } from '../tools/index.js';
|
|
39
|
-
import { classifyComputerAutomationIntent } from '../tools/computeruse/computerIntent.js';
|
|
40
|
-
import { createPromptCacheContext } from '../llm/promptCache.js';
|
|
41
|
-
import { createAgentRuntimeContext, filterToolsForRuntime, memoryContextFromRuntime, } from '../runtime/agentRuntimeContext.js';
|
|
13
|
+
import { extractFlagValue } from './args.js';
|
|
42
14
|
import { extractImageOptions, extractPromptArgs } from './print.js';
|
|
43
|
-
import {
|
|
44
|
-
import {
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
process.stdout.write(`${JSON.stringify(ev)}\n`);
|
|
49
|
-
}
|
|
50
|
-
catch {
|
|
51
|
-
/* ignore */
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
function firstUserTitle(history) {
|
|
55
|
-
const u = history.find((m) => m.role === 'user');
|
|
56
|
-
if (!u)
|
|
57
|
-
return undefined;
|
|
58
|
-
if (typeof u.content === 'string')
|
|
59
|
-
return u.content;
|
|
60
|
-
return u.content.find((p) => p.type === 'text')?.text;
|
|
15
|
+
import { runHeadlessTurn } from './headlessTurn.js';
|
|
16
|
+
import { createCliLifecycle, flushCliOutput } from './lifecycle.js';
|
|
17
|
+
function emitLine(event) {
|
|
18
|
+
if (!process.stdout.destroyed)
|
|
19
|
+
process.stdout.write(JSON.stringify(event) + '\n');
|
|
61
20
|
}
|
|
62
21
|
function parseWireImages(raw) {
|
|
63
22
|
if (!Array.isArray(raw))
|
|
@@ -88,328 +47,279 @@ function parseWireImages(raw) {
|
|
|
88
47
|
}
|
|
89
48
|
return out;
|
|
90
49
|
}
|
|
91
|
-
|
|
92
|
-
* stdin 控制通道:把 stdin 从「一次性裸 prompt」升级为**逐行 JSON 控制通道**,
|
|
93
|
-
* 支撑「问答 over wire」的入站半边。两种控制消息:
|
|
94
|
-
* - `{ type:'prompt', text }` —— 首行,本轮的用户输入(替代裸 prompt)
|
|
95
|
-
* - `{ type:'ask_answer', requestId, answers }` —— AskUserQuestion 的回答,按 requestId 关联
|
|
96
|
-
*
|
|
97
|
-
* 向后兼容:首个非空行**不是** `{type:'prompt'}` 控制消息时,判定为 legacy 模式 ——
|
|
98
|
-
* 整段 stdin 当裸 prompt 读到 EOF(保 `echo "x" | minimal-agent -p --output-format stream-json` 仍可用,
|
|
99
|
-
* legacy 下天然无交互、一次性)。argv 已给 prompt 时,stdin 全部行都按 ask_answer 解析。
|
|
100
|
-
*
|
|
101
|
-
* 返回 `{ prompt, control }`:`control=true` **仅**当 prompt 来自 `{type:'prompt'}` 控制行
|
|
102
|
-
* (= broker 在管理本子进程、会回灌 ask_answer);argv / 裸管道 / TTY / EOF 兜底均为 `false`
|
|
103
|
-
* (无人回灌 → 调用方据此**不注册** wire ask handler,让 askBridge 内置「自动选推荐项」兜底,
|
|
104
|
-
* 避免模型提问后永等挂死)。同时把 ask_answer 路由给 onAskAnswer。stdin 全程保持打开,
|
|
105
|
-
* 直到子进程结束(broker 在 turn 末 end stdin)。
|
|
106
|
-
*/
|
|
107
|
-
export function attachStdinChannel(opts) {
|
|
50
|
+
function openStdinChannel(opts) {
|
|
108
51
|
const input = opts.input ?? process.stdin;
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
52
|
+
let dispose = () => { };
|
|
53
|
+
const prompt = new Promise((resolve, reject) => {
|
|
54
|
+
let resolved = false;
|
|
55
|
+
let ended = false;
|
|
56
|
+
let legacy = false;
|
|
57
|
+
let buf = '';
|
|
58
|
+
const finish = (text, control, images) => {
|
|
59
|
+
if (resolved)
|
|
113
60
|
return;
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
61
|
+
resolved = true;
|
|
62
|
+
resolve({
|
|
63
|
+
prompt: text,
|
|
64
|
+
control,
|
|
65
|
+
...(images?.length ? { imageInputs: images } : {}),
|
|
66
|
+
});
|
|
118
67
|
};
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
input.setEncoding('utf8');
|
|
130
|
-
input.on('data', (chunk) => {
|
|
68
|
+
const fail = (error) => {
|
|
69
|
+
if (ended)
|
|
70
|
+
return;
|
|
71
|
+
ended = true;
|
|
72
|
+
dispose();
|
|
73
|
+
if (!resolved)
|
|
74
|
+
reject(error);
|
|
75
|
+
opts.onDisconnect?.(error);
|
|
76
|
+
};
|
|
77
|
+
const onData = (chunk) => {
|
|
131
78
|
buf += chunk;
|
|
79
|
+
if (buf.length > 8 * 1024 * 1024)
|
|
80
|
+
return fail(new Error('stdin frame exceeds 8 Mi characters'));
|
|
132
81
|
if (legacy)
|
|
133
|
-
return;
|
|
82
|
+
return;
|
|
134
83
|
let nl;
|
|
135
84
|
while ((nl = buf.indexOf('\n')) >= 0) {
|
|
136
85
|
const line = buf.slice(0, nl);
|
|
137
86
|
buf = buf.slice(nl + 1);
|
|
138
87
|
if (!line.trim())
|
|
139
88
|
continue;
|
|
140
|
-
let msg
|
|
89
|
+
let msg;
|
|
141
90
|
try {
|
|
142
91
|
msg = JSON.parse(line);
|
|
143
92
|
}
|
|
144
93
|
catch {
|
|
145
94
|
msg = null;
|
|
146
95
|
}
|
|
147
|
-
if (!
|
|
148
|
-
if (msg
|
|
149
|
-
|
|
96
|
+
if (!resolved) {
|
|
97
|
+
if (msg?.type === 'prompt' && typeof msg.text === 'string') {
|
|
98
|
+
finish(msg.text, true, parseWireImages(msg.images));
|
|
150
99
|
}
|
|
151
100
|
else {
|
|
152
|
-
// 首行不是 prompt 控制消息 → legacy:把它放回去,整段当裸 prompt 读到 EOF
|
|
153
101
|
legacy = true;
|
|
154
|
-
|
|
102
|
+
// Preserve the consumed delimiter even if this chunk ends at it.
|
|
103
|
+
buf = line + '\n' + buf;
|
|
155
104
|
return;
|
|
156
105
|
}
|
|
157
106
|
}
|
|
158
|
-
else if (msg &&
|
|
159
|
-
msg.type === 'ask_answer' &&
|
|
107
|
+
else if (msg?.type === 'ask_answer' &&
|
|
160
108
|
typeof msg.requestId === 'string') {
|
|
161
109
|
opts.onAskAnswer(msg.requestId, Array.isArray(msg.answers) ? msg.answers : []);
|
|
162
110
|
}
|
|
163
111
|
}
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
112
|
+
};
|
|
113
|
+
const onEnd = () => {
|
|
114
|
+
if (ended)
|
|
115
|
+
return;
|
|
116
|
+
ended = true;
|
|
117
|
+
dispose();
|
|
118
|
+
finish(buf.trim(), false);
|
|
119
|
+
opts.onDisconnect?.();
|
|
120
|
+
};
|
|
121
|
+
const onClose = () => {
|
|
122
|
+
if (!ended)
|
|
123
|
+
fail(new Error('stdin closed before EOF'));
|
|
124
|
+
};
|
|
125
|
+
const onAbort = () => fail(new DOMException('Interrupted', 'AbortError'));
|
|
126
|
+
dispose = () => {
|
|
127
|
+
input.removeListener('data', onData);
|
|
128
|
+
input.removeListener('end', onEnd);
|
|
129
|
+
input.removeListener('error', fail);
|
|
130
|
+
input.removeListener('close', onClose);
|
|
131
|
+
opts.signal?.removeEventListener('abort', onAbort);
|
|
132
|
+
input.pause();
|
|
133
|
+
};
|
|
134
|
+
if (opts.signal?.aborted)
|
|
135
|
+
return onAbort();
|
|
136
|
+
if (opts.argvPrompt !== undefined)
|
|
137
|
+
finish(opts.argvPrompt, false);
|
|
138
|
+
if (input.isTTY) {
|
|
139
|
+
finish('', false);
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
input.setEncoding('utf8');
|
|
143
|
+
input.on('data', onData);
|
|
144
|
+
input.once('end', onEnd);
|
|
145
|
+
input.once('error', fail);
|
|
146
|
+
input.once('close', onClose);
|
|
147
|
+
opts.signal?.addEventListener('abort', onAbort, { once: true });
|
|
148
|
+
if (input.readableEnded)
|
|
149
|
+
onEnd();
|
|
170
150
|
});
|
|
151
|
+
return { prompt, dispose: () => dispose() };
|
|
152
|
+
}
|
|
153
|
+
/** Compatibility entry for channel parser tests and embedded callers. */
|
|
154
|
+
export function attachStdinChannel(opts) {
|
|
155
|
+
return openStdinChannel(opts).prompt;
|
|
171
156
|
}
|
|
172
157
|
export async function runStreamJsonMode(provider, args, initialHistory, options) {
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
// 同 print.ts:本模式一进程一回合、没有空闲唤醒者,进程退出会杀掉还在跑的
|
|
188
|
-
// 后台任务。如实发一条 warning,别让宿主以为那些结果已经拿到了。
|
|
189
|
-
const running = listRunningBackgroundTasks(liveBackgroundTasks);
|
|
190
|
-
if (running.length > 0) {
|
|
191
|
-
emitLine({
|
|
192
|
-
type: 'warning',
|
|
193
|
-
message: `${running.length} 个后台任务在本次结束时仍在运行,进程退出会终止它们,其结果未经验证:` +
|
|
194
|
-
running.map((task) => `${task.id}(${task.command.slice(0, 80)})`).join(';'),
|
|
195
|
-
});
|
|
196
|
-
}
|
|
197
|
-
if (liveBackgroundTasks)
|
|
198
|
-
await stopAllBackgroundTasks(liveBackgroundTasks);
|
|
199
|
-
await disposeLocalBrowsers();
|
|
200
|
-
// 释放 stdin:attachStdinChannel 的 'data' 监听会让进程在本轮结束后**仍存活**
|
|
201
|
-
// (等下一行输入)→ broker 永远收不到子进程 close、web 端 conn.running 卡死。
|
|
202
|
-
// turn 已结束(无挂起提问),unref 让 stdout 排空后进程自然退出;中途挂起期间
|
|
203
|
-
// 不会走到这里,故等答案时进程仍被 stdin 监听保活。
|
|
204
|
-
try {
|
|
205
|
-
process.stdin.unref();
|
|
206
|
-
}
|
|
207
|
-
catch {
|
|
208
|
-
/* 某些 stdin 类型无 unref,忽略 */
|
|
209
|
-
}
|
|
210
|
-
setAskHandler(null); // 注销 handler,避免全局污染(测试复用 / 同进程多次调用)
|
|
211
|
-
await saveContext(history, options.sessionFile);
|
|
212
|
-
})();
|
|
213
|
-
return finalizePromise;
|
|
158
|
+
const lifecycle = createCliLifecycle();
|
|
159
|
+
let channel;
|
|
160
|
+
let inputClosed = false;
|
|
161
|
+
let channelFailure;
|
|
162
|
+
let done = false;
|
|
163
|
+
let code = 0;
|
|
164
|
+
let interruptedEmitted = false;
|
|
165
|
+
const asks = new Map();
|
|
166
|
+
const rejectAsks = (error) => {
|
|
167
|
+
for (const ask of asks.values()) {
|
|
168
|
+
ask.cleanup();
|
|
169
|
+
ask.reject(error);
|
|
170
|
+
}
|
|
171
|
+
asks.clear();
|
|
214
172
|
};
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
173
|
+
const disconnect = (error) => {
|
|
174
|
+
inputClosed = true;
|
|
175
|
+
if (asks.size || (error && !lifecycle.signal.aborted)) {
|
|
176
|
+
channelFailure =
|
|
177
|
+
error ??
|
|
178
|
+
new Error('interaction_unavailable: stdin 已关闭,无法获取用户回答');
|
|
179
|
+
rejectAsks(channelFailure);
|
|
180
|
+
lifecycle.fail(channelFailure);
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
try {
|
|
184
|
+
if (options.compact) {
|
|
218
185
|
emitLine({ type: 'compact_start' });
|
|
219
|
-
const r = await
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
trigger: 'manual',
|
|
227
|
-
mode: r.mode,
|
|
228
|
-
degraded: r.degraded,
|
|
229
|
-
...(r.fallbackReason ? { fallbackReason: r.fallbackReason } : {}),
|
|
230
|
-
...(r.messagesRemoved !== undefined
|
|
231
|
-
? { messagesRemoved: r.messagesRemoved }
|
|
232
|
-
: {}),
|
|
233
|
-
...(r.tokensFreed !== undefined ? { tokensFreed: r.tokensFreed } : {}),
|
|
186
|
+
const r = await compactSession({
|
|
187
|
+
sessionFile: options.sessionFile ?? getContextPath(),
|
|
188
|
+
history: initialHistory,
|
|
189
|
+
provider,
|
|
190
|
+
signal: lifecycle.signal,
|
|
191
|
+
customInstructions: extractFlagValue(args, ['--compact-instructions']),
|
|
192
|
+
promptCache: createPromptCacheContext(`workspace:${options.workspace?.cwd ?? getWorkingDir()}:session:${options.workspace?.sessionId ?? 'default'}`),
|
|
234
193
|
});
|
|
194
|
+
initialHistory.splice(0, initialHistory.length, ...r.messages);
|
|
195
|
+
if (r.unchangedReason)
|
|
196
|
+
emitLine({ type: 'warning', message: manualCompactNotice(r) });
|
|
197
|
+
else
|
|
198
|
+
emitLine({
|
|
199
|
+
type: 'compact_done',
|
|
200
|
+
before: r.before,
|
|
201
|
+
after: r.after,
|
|
202
|
+
trigger: 'manual',
|
|
203
|
+
mode: r.mode,
|
|
204
|
+
degraded: r.degraded,
|
|
205
|
+
...(r.fallbackReason ? { fallbackReason: r.fallbackReason } : {}),
|
|
206
|
+
...(r.messagesRemoved !== undefined
|
|
207
|
+
? { messagesRemoved: r.messagesRemoved }
|
|
208
|
+
: {}),
|
|
209
|
+
...(r.tokensFreed !== undefined
|
|
210
|
+
? { tokensFreed: r.tokensFreed }
|
|
211
|
+
: {}),
|
|
212
|
+
});
|
|
235
213
|
emitLine({ type: 'turn_done' });
|
|
214
|
+
done = true;
|
|
236
215
|
}
|
|
237
|
-
|
|
216
|
+
else {
|
|
217
|
+
const words = extractPromptArgs(args);
|
|
218
|
+
channel = openStdinChannel({
|
|
219
|
+
argvPrompt: words.length ? words.join(' ') : undefined,
|
|
220
|
+
signal: lifecycle.signal,
|
|
221
|
+
onDisconnect: disconnect,
|
|
222
|
+
onAskAnswer(id, answers) {
|
|
223
|
+
const ask = asks.get(id);
|
|
224
|
+
if (ask) {
|
|
225
|
+
asks.delete(id);
|
|
226
|
+
ask.cleanup();
|
|
227
|
+
ask.resolve(answers);
|
|
228
|
+
}
|
|
229
|
+
},
|
|
230
|
+
});
|
|
231
|
+
const { prompt, control, imageInputs } = await channel.prompt;
|
|
232
|
+
if (!prompt.trim())
|
|
233
|
+
throw new Error('未提供非空 prompt');
|
|
234
|
+
if (control)
|
|
235
|
+
setAskHandler((questions, signal) => {
|
|
236
|
+
if (inputClosed) {
|
|
237
|
+
channelFailure = new Error('interaction_unavailable: stdin 已关闭,无法获取用户回答');
|
|
238
|
+
lifecycle.fail(channelFailure);
|
|
239
|
+
return Promise.reject(channelFailure);
|
|
240
|
+
}
|
|
241
|
+
return new Promise((resolve, reject) => {
|
|
242
|
+
const requestId = crypto.randomUUID();
|
|
243
|
+
const abort = () => {
|
|
244
|
+
asks.delete(requestId);
|
|
245
|
+
signal?.removeEventListener('abort', abort);
|
|
246
|
+
reject(new DOMException('Interrupted', 'AbortError'));
|
|
247
|
+
};
|
|
248
|
+
if (signal?.aborted)
|
|
249
|
+
return abort();
|
|
250
|
+
asks.set(requestId, {
|
|
251
|
+
resolve,
|
|
252
|
+
reject,
|
|
253
|
+
cleanup: () => signal?.removeEventListener('abort', abort),
|
|
254
|
+
});
|
|
255
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
256
|
+
emitLine({ type: 'ask', requestId, questions });
|
|
257
|
+
});
|
|
258
|
+
});
|
|
259
|
+
const images = extractImageOptions(args);
|
|
260
|
+
for await (const event of runHeadlessTurn(provider, prompt, {
|
|
261
|
+
...options,
|
|
262
|
+
...images,
|
|
263
|
+
imageInputs: [...images.imageInputs, ...(imageInputs ?? [])],
|
|
264
|
+
signal: lifecycle.signal,
|
|
265
|
+
interactive: control,
|
|
266
|
+
host: 'stream-json',
|
|
267
|
+
})) {
|
|
268
|
+
// Transport loss is a host error, not a second "user interrupted" terminal.
|
|
269
|
+
if (channelFailure &&
|
|
270
|
+
['error', 'interrupted', 'turn_done'].includes(event.type))
|
|
271
|
+
continue;
|
|
272
|
+
if (event.type === 'error' && event.code !== 'compact_failed')
|
|
273
|
+
code = 1;
|
|
274
|
+
if (event.type === 'interrupted') {
|
|
275
|
+
code = 130;
|
|
276
|
+
interruptedEmitted = true;
|
|
277
|
+
}
|
|
278
|
+
if (event.type === 'turn_done')
|
|
279
|
+
done = true;
|
|
280
|
+
emitLine(event);
|
|
281
|
+
}
|
|
282
|
+
if (channelFailure)
|
|
283
|
+
throw channelFailure;
|
|
284
|
+
if (!done && !code)
|
|
285
|
+
throw new Error('执行结束但没有终态回执');
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
catch (error) {
|
|
289
|
+
if (lifecycle.signal.aborted && lifecycle.exitCode !== 1) {
|
|
290
|
+
if (!interruptedEmitted)
|
|
291
|
+
emitLine({ type: 'interrupted' });
|
|
292
|
+
code = lifecycle.exitCode ?? 130;
|
|
293
|
+
}
|
|
294
|
+
else {
|
|
238
295
|
emitLine({
|
|
239
296
|
type: 'error',
|
|
240
|
-
|
|
241
|
-
|
|
297
|
+
code: options.compact ? 'compact_failed' : 'host_error',
|
|
298
|
+
error: options.compact
|
|
299
|
+
? `手动压缩失败,原上下文保持不变:${error.message}`
|
|
300
|
+
: error instanceof Error
|
|
301
|
+
? error.message
|
|
302
|
+
: String(error),
|
|
242
303
|
});
|
|
304
|
+
code = 1;
|
|
243
305
|
}
|
|
244
|
-
await finalize();
|
|
245
|
-
return;
|
|
246
|
-
}
|
|
247
|
-
// --- 普通一轮 ---
|
|
248
|
-
// 「问答 over wire」入站半边:pendingAsks 持本轮未决提问(requestId → resolver)。
|
|
249
|
-
const pendingAsks = new Map();
|
|
250
|
-
const rejectAllAsks = (reason) => {
|
|
251
|
-
for (const p of pendingAsks.values())
|
|
252
|
-
p.reject(new Error(reason));
|
|
253
|
-
pendingAsks.clear();
|
|
254
|
-
};
|
|
255
|
-
const promptArgs = extractPromptArgs(args);
|
|
256
|
-
const cliImageOptions = extractImageOptions(args);
|
|
257
|
-
const { prompt, control, imageInputs: stdinImageInputs, } = await attachStdinChannel({
|
|
258
|
-
argvPrompt: promptArgs.length > 0 ? promptArgs.join(' ') : undefined,
|
|
259
|
-
onAskAnswer: (requestId, answers) => {
|
|
260
|
-
const p = pendingAsks.get(requestId);
|
|
261
|
-
if (p) {
|
|
262
|
-
pendingAsks.delete(requestId);
|
|
263
|
-
p.resolve(answers);
|
|
264
|
-
}
|
|
265
|
-
},
|
|
266
|
-
});
|
|
267
|
-
// 仅当存在控制通道(broker 经 `{type:'prompt'}` 启动、会回灌 ask_answer)才注册 wire handler:
|
|
268
|
-
// 工具调 requestUserChoice → emit `ask` 到 stdout、挂起等 stdin 回灌。无控制通道(argv / 裸管道 /
|
|
269
|
-
// TTY)时**不注册** → 落 askBridge 内置「自动选推荐项」兜底,避免模型提问后永等挂死。
|
|
270
|
-
// loop 在 prompt resolve 后才启动 → 此处注册时机安全(注册前不会有 ask 触发)。
|
|
271
|
-
if (control) {
|
|
272
|
-
setAskHandler((questions) => new Promise((resolve, reject) => {
|
|
273
|
-
const requestId = crypto.randomUUID();
|
|
274
|
-
pendingAsks.set(requestId, { resolve, reject });
|
|
275
|
-
emitLine({ type: 'ask', requestId, questions });
|
|
276
|
-
}));
|
|
277
|
-
}
|
|
278
|
-
if (!prompt.trim()) {
|
|
279
|
-
emitLine({
|
|
280
|
-
type: 'error',
|
|
281
|
-
error: '未提供 prompt(argv / stdin 都为空)',
|
|
282
|
-
code: 'llm_error',
|
|
283
|
-
});
|
|
284
|
-
process.exit(1);
|
|
285
|
-
}
|
|
286
|
-
// 记录最近目录(侧栏用);title 优先用历史里第一条用户消息(稳定),否则用当前 prompt
|
|
287
|
-
await recordRecentDir(getWorkingDir(), firstUserTitle(history) ?? prompt);
|
|
288
|
-
if (options.workspace) {
|
|
289
|
-
await updateSessionMetadata(options.workspace.cwd, options.workspace.sessionId, {
|
|
290
|
-
lastMessagePreview: prompt,
|
|
291
|
-
}).catch(() => { });
|
|
292
306
|
}
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
abortController.abort();
|
|
300
|
-
rejectAllAsks('已中断'); // 挂起的提问立即落败,工具回 ok:false → loop 收口 interrupted
|
|
301
|
-
emitLine({ type: 'interrupted' });
|
|
302
|
-
void finalize().finally(() => process.exit(130));
|
|
303
|
-
});
|
|
304
|
-
try {
|
|
305
|
-
const workspaceRoot = options.workspace?.cwd ?? getWorkingDir();
|
|
306
|
-
const workspace = await workspaceIndexService
|
|
307
|
-
.findByPath(workspaceRoot)
|
|
308
|
-
.catch(() => null);
|
|
309
|
-
const sessionId = options.workspace?.sessionId ?? 'default';
|
|
310
|
-
const sessionState = getOrCreateSessionState(sessionStateKey({
|
|
311
|
-
surface: 'headless',
|
|
312
|
-
workspaceId: workspace?.id,
|
|
313
|
-
cwd: workspace?.id ? undefined : workspaceRoot,
|
|
314
|
-
sessionId,
|
|
315
|
-
}));
|
|
316
|
-
liveBackgroundTasks = sessionState.backgroundTasks;
|
|
317
|
-
await hydrateSessionWorktree({
|
|
318
|
-
sessionState,
|
|
319
|
-
workspaceId: workspace?.id,
|
|
320
|
-
sessionId,
|
|
321
|
-
cwd: workspaceRoot,
|
|
322
|
-
});
|
|
323
|
-
const cwd = sessionState.activeWorktree?.path ?? workspaceRoot;
|
|
324
|
-
const conversationKey = `workspace:${workspace?.id ?? workspaceRoot}:session:${sessionId}`;
|
|
325
|
-
const computerRun = options.computerUseMode && options.computerUseMode !== 'disabled'
|
|
326
|
-
? createCliComputerRun({
|
|
327
|
-
mode: options.computerUseMode,
|
|
328
|
-
surface: 'cli',
|
|
329
|
-
conversationKey,
|
|
330
|
-
userInput: prompt,
|
|
331
|
-
allowedFileRoots: [cwd],
|
|
332
|
-
supervised: true,
|
|
333
|
-
diagnosticTraceDir: options.computerUseTraceDir,
|
|
334
|
-
})
|
|
335
|
-
: undefined;
|
|
336
|
-
const runtimeContext = createAgentRuntimeContext({
|
|
337
|
-
surface: 'headless',
|
|
338
|
-
host: 'stream-json',
|
|
339
|
-
profile: 'main',
|
|
340
|
-
cwd,
|
|
341
|
-
workspaceId: workspace?.id,
|
|
342
|
-
sessionId,
|
|
343
|
-
owner: options.memoryAccess === 'denied' ? 'untrusted' : 'local-owner',
|
|
344
|
-
memoryAccess: options.memoryAccess ?? 'read-only',
|
|
345
|
-
interactiveAsk: control,
|
|
346
|
-
browser: options.browserMode !== 'off'
|
|
347
|
-
? await resolveLocalBrowserRun({
|
|
348
|
-
mode: options.browserMode ?? 'headless',
|
|
349
|
-
conversationKey,
|
|
350
|
-
userInput: prompt,
|
|
351
|
-
allowedUploadRoots: [cwd],
|
|
352
|
-
})
|
|
353
|
-
: undefined,
|
|
354
|
-
computer: computerRun,
|
|
355
|
-
computerIntent: classifyComputerAutomationIntent(prompt, sessionState.computerAutomation),
|
|
356
|
-
});
|
|
357
|
-
const turnTools = filterToolsForRuntime(ALL_TOOLS, runtimeContext);
|
|
358
|
-
await refreshStableSystemPrompt(history, cwd, turnTools);
|
|
359
|
-
const transientBundle = await buildTransientPromptBundle({
|
|
360
|
-
cwd,
|
|
361
|
-
tools: turnTools,
|
|
362
|
-
runtime: {
|
|
363
|
-
surface: 'headless',
|
|
364
|
-
host: 'stream-json',
|
|
365
|
-
cwd,
|
|
366
|
-
workspaceId: workspace?.id,
|
|
367
|
-
sessionId,
|
|
368
|
-
interactiveAsk: control,
|
|
369
|
-
memoryAccess: runtimeContext.memoryAccess,
|
|
370
|
-
browser: browserPromptRuntime(runtimeContext.browser, provider.supportsVision),
|
|
371
|
-
currentUserInput: prompt,
|
|
372
|
-
previousUserInput: previousUserRequest(history),
|
|
373
|
-
contextWindow: provider.contextWindow,
|
|
374
|
-
},
|
|
375
|
-
}).catch(() => undefined);
|
|
376
|
-
for await (const event of runWithPlugins(prompt, {
|
|
377
|
-
provider,
|
|
378
|
-
history,
|
|
379
|
-
signal: abortController.signal,
|
|
380
|
-
maxTurns: options.maxTurns,
|
|
381
|
-
imageInputs: [
|
|
382
|
-
...cliImageOptions.imageInputs,
|
|
383
|
-
...(stdinImageInputs ?? []),
|
|
384
|
-
],
|
|
385
|
-
parseInlineImages: true,
|
|
386
|
-
imageDetail: cliImageOptions.imageDetail,
|
|
387
|
-
imageMaxLongSidePixel: cliImageOptions.imageMaxLongSidePixel,
|
|
388
|
-
runtimeContext,
|
|
389
|
-
sessionState,
|
|
390
|
-
allowedTools: turnTools.map((tool) => tool.name),
|
|
391
|
-
...(transientBundle ? { transientBundle } : {}),
|
|
392
|
-
promptCache: createPromptCacheContext(`workspace:${workspace?.id ?? cwd}:session:${sessionId}`),
|
|
393
|
-
memoryContext: memoryContextFromRuntime(runtimeContext),
|
|
394
|
-
...(computerRun ? { computerRun } : {}),
|
|
395
|
-
})) {
|
|
396
|
-
// event 是 LoopEvent | PluginEvent,原样逐行 emit;前端不识别的插件私有事件会静默忽略
|
|
397
|
-
emitLine(event.type === 'turn_done'
|
|
398
|
-
? { ...event, ...backgroundCompletionFields(liveBackgroundTasks) }
|
|
399
|
-
: event);
|
|
307
|
+
finally {
|
|
308
|
+
rejectAsks(new Error('CLI turn ended'));
|
|
309
|
+
setAskHandler(null);
|
|
310
|
+
channel?.dispose();
|
|
311
|
+
try {
|
|
312
|
+
process.stdin.unref();
|
|
400
313
|
}
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
314
|
+
catch {
|
|
315
|
+
/* Some input streams cannot be unreferenced. */
|
|
316
|
+
}
|
|
317
|
+
try {
|
|
318
|
+
await flushCliOutput();
|
|
319
|
+
}
|
|
320
|
+
finally {
|
|
321
|
+
lifecycle.dispose();
|
|
409
322
|
}
|
|
410
|
-
emitLine({ type: 'error', error: e.message, code: 'llm_error' });
|
|
411
|
-
await finalize();
|
|
412
|
-
process.exit(1);
|
|
413
323
|
}
|
|
414
|
-
|
|
324
|
+
return lifecycle.exitCode ?? code;
|
|
415
325
|
}
|