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
|
@@ -206,7 +206,10 @@ async function* executeWorkflowScript(
|
|
|
206
206
|
...(!opts.parentStateDir ? { commandResult: true as const } : {}),
|
|
207
207
|
delta: `工作流「${script.name}」的这个目标此前已完成,产物:\n${list}\n换个目标即可重新执行。\n`,
|
|
208
208
|
};
|
|
209
|
-
if (!opts.parentStateDir)
|
|
209
|
+
if (!opts.parentStateDir) {
|
|
210
|
+
if (ctx.presentArtifacts && !ctx.managedBridge) yield* ctx.presentArtifacts((resume.artifacts ?? []).map(p => resolve(state.workingDir, p)));
|
|
211
|
+
yield { type: 'turn_done' };
|
|
212
|
+
}
|
|
210
213
|
return {
|
|
211
214
|
workflow: script.name,
|
|
212
215
|
runId: opts.runId,
|
|
@@ -566,6 +569,7 @@ async function* executeWorkflowScript(
|
|
|
566
569
|
// ⚠️ 收尾状态必须过进程边界。传进去 'verified' 拿回来的很可能是
|
|
567
570
|
// 'ready_for_acceptance' —— 机器自检通过但还没人验收,这两者对宿主是天差地别。
|
|
568
571
|
// 就地丢弃会让 `-p --output-format json` 的宿主把「等待验收」读成「办完了」。
|
|
572
|
+
if (ctx.presentArtifacts && !ctx.managedBridge) yield* ctx.presentArtifacts(artifacts);
|
|
569
573
|
yield { type: 'turn_done', ...managedStatusOf(finished) };
|
|
570
574
|
return {
|
|
571
575
|
workflow: script.name,
|
|
@@ -128,6 +128,7 @@ export interface DiscoveryResult {
|
|
|
128
128
|
* 「重试三次、每次退避一点」就是一个 `for` 加 `try`,不需要引擎参与。
|
|
129
129
|
*/
|
|
130
130
|
export interface RunContext {
|
|
131
|
+
presentArtifacts?: PluginContext['presentArtifacts'];
|
|
131
132
|
executionId?: string;
|
|
132
133
|
provider: Provider;
|
|
133
134
|
runtimeContext?: AgentRuntimeContext;
|
|
@@ -55,6 +55,7 @@ function scriptedChat(texts: string[]) {
|
|
|
55
55
|
type: 'text_delta' as const,
|
|
56
56
|
delta: texts[Math.min(n++, texts.length - 1)],
|
|
57
57
|
};
|
|
58
|
+
yield { type: 'done' as const, stopReason: 'stop' as const };
|
|
58
59
|
};
|
|
59
60
|
return { fn, calls };
|
|
60
61
|
}
|
|
@@ -409,6 +410,7 @@ describe('①+② 联动:pipeline 扇出后仍能断点续跑(这是整轮
|
|
|
409
410
|
const i = n++;
|
|
410
411
|
await new Promise((r) => setTimeout(r, (texts.length - i) * 3));
|
|
411
412
|
yield { type: 'text_delta' as const, delta: texts[i] ?? 'x' };
|
|
413
|
+
yield { type: 'done' as const, stopReason: 'stop' as const };
|
|
412
414
|
};
|
|
413
415
|
};
|
|
414
416
|
const texts = Array.from({ length: N }, (_, i) => `{"items":[${i}]}`);
|
|
@@ -455,6 +457,7 @@ describe('③ model 覆盖', () => {
|
|
|
455
457
|
signals.push(a.signal);
|
|
456
458
|
if (signals.length === 1) {
|
|
457
459
|
yield { type: 'text_delta' as const, delta: 'invalid JSON' };
|
|
460
|
+
yield { type: 'done' as const, stopReason: 'stop' as const };
|
|
458
461
|
} else {
|
|
459
462
|
await new Promise<void>((resolve) => {
|
|
460
463
|
if (a.signal.aborted) resolve();
|
|
@@ -479,6 +482,7 @@ describe('③ model 覆盖', () => {
|
|
|
479
482
|
if (started <= 8)
|
|
480
483
|
await new Promise<void>((resolve) => release.push(resolve));
|
|
481
484
|
yield { type: 'text_delta' as const, delta: 'ok' };
|
|
485
|
+
yield { type: 'done' as const, stopReason: 'stop' as const };
|
|
482
486
|
};
|
|
483
487
|
const h = await harness(chat);
|
|
484
488
|
const running = h.globals.flow.pipeline(
|
|
@@ -49,6 +49,7 @@ async function harness() {
|
|
|
49
49
|
// 强制重叠:没有这个延迟,调用可能快到彼此从不同时在场,测不出并发峰值。
|
|
50
50
|
await new Promise((r) => setTimeout(r, 15));
|
|
51
51
|
yield { type: 'text_delta' as const, delta: 'ok' };
|
|
52
|
+
yield { type: 'done' as const, stopReason: 'stop' as const };
|
|
52
53
|
} finally {
|
|
53
54
|
active--;
|
|
54
55
|
}
|
|
@@ -73,6 +73,25 @@ const parent = `export const meta={description:'parent',dependencies:['child']};
|
|
|
73
73
|
export default async function run(wf) { const r=await wf.flow.child('child', {}, {label:'child-label'}); wf.output.message(r.result); return r; }`.replace('{description:', '{apiVersion:2,description:');
|
|
74
74
|
const child = `export const meta={apiVersion:2,description:'child'}; export default async function run(wf) { return await wf.model.generate('child', {isolated:true}); }`;
|
|
75
75
|
|
|
76
|
+
test('only successful root completion presents artifacts, including completed replay', async () => {
|
|
77
|
+
const h = await fixture(
|
|
78
|
+
`export const meta={apiVersion:2,description:'parent',dependencies:['child'],artifacts:['root.txt']}; export default async function run(wf) { await wf.flow.child('child',{}); await wf.fs.writeText('root.txt','root'); }`,
|
|
79
|
+
`export const meta={apiVersion:2,description:'child',artifacts:['child.txt']}; export default async function run(wf) { await wf.fs.writeText('child.txt','child'); }`,
|
|
80
|
+
);
|
|
81
|
+
const delivered: string[][] = [];
|
|
82
|
+
h.ctx.presentArtifacts = async function* (paths) { delivered.push([...paths]); };
|
|
83
|
+
try {
|
|
84
|
+
expect((await h.run()).some(e => e.type === 'error')).toBe(false);
|
|
85
|
+
const rootArtifacts = [join(h.cwd, 'root.txt'), join(h.cwd, 'child.txt')];
|
|
86
|
+
expect(delivered).toEqual([rootArtifacts]);
|
|
87
|
+
await h.run();
|
|
88
|
+
expect(delivered).toEqual([rootArtifacts, rootArtifacts]);
|
|
89
|
+
await h.put('parent', `export const meta={apiVersion:2,description:'parent',artifacts:['root.txt']}; export default async function run(wf) { throw new Error('fixture failure'); }`);
|
|
90
|
+
expect((await h.run()).some(e => e.type === 'error')).toBe(true);
|
|
91
|
+
expect(delivered).toHaveLength(2);
|
|
92
|
+
} finally { await rm(h.cwd, { recursive: true, force: true }); }
|
|
93
|
+
});
|
|
94
|
+
|
|
76
95
|
test('root and child use strict typed input coercion', () => {
|
|
77
96
|
const defs = [{ name: 'n', type: 'number' as const }];
|
|
78
97
|
expect(coerceInputs({ n: '900' }, defs)).toEqual({ n: 900 });
|
|
@@ -115,6 +115,20 @@ async function harness(
|
|
|
115
115
|
return { wf, events, state, journal, ctx };
|
|
116
116
|
}
|
|
117
117
|
|
|
118
|
+
test.each(['agent', 'generate'] as const)('%s rejects EOF text and cannot replay it as a successful node', async method => {
|
|
119
|
+
let calls = 0;
|
|
120
|
+
const h = await harness(async function* () {
|
|
121
|
+
calls++;
|
|
122
|
+
yield { type: 'text_delta', delta: 'partial report' };
|
|
123
|
+
// Deliberately no terminal event: the provider disconnected.
|
|
124
|
+
});
|
|
125
|
+
try {
|
|
126
|
+
for (let attempt = 0; attempt < 2; attempt++)
|
|
127
|
+
await expect(h.wf.model[method]('inspect', { isolated: true })).rejects.toBeInstanceOf(WorkflowModelError);
|
|
128
|
+
expect(calls).toBe(2);
|
|
129
|
+
} finally { await h.state.flush(); }
|
|
130
|
+
});
|
|
131
|
+
|
|
118
132
|
test('TAOR: earlier prose cannot mask a later model failure; script may recover', async () => {
|
|
119
133
|
let calls = 0;
|
|
120
134
|
const h = await harness(async function* () {
|
|
@@ -130,7 +144,10 @@ test('TAOR: earlier prose cannot mask a later model failure; script may recover'
|
|
|
130
144
|
};
|
|
131
145
|
yield { type: 'done', stopReason: 'tool_calls' };
|
|
132
146
|
} else if (calls === 2) throw new Error('provider failed after tool');
|
|
133
|
-
else
|
|
147
|
+
else {
|
|
148
|
+
yield { type: 'text_delta', delta: 'recovered' };
|
|
149
|
+
yield { type: 'done', stopReason: 'stop' };
|
|
150
|
+
}
|
|
134
151
|
});
|
|
135
152
|
let failure: unknown;
|
|
136
153
|
try {
|
|
@@ -171,6 +188,7 @@ test('embedded tools exclude outer delivery/advisor/ask, preserve explicitly req
|
|
|
171
188
|
])
|
|
172
189
|
expect(names).not.toContain(name);
|
|
173
190
|
yield { type: 'text_delta', delta: 'stage result' };
|
|
191
|
+
yield { type: 'done', stopReason: 'stop' };
|
|
174
192
|
});
|
|
175
193
|
expect(
|
|
176
194
|
await h.wf.model.agent('生成文件并交付', {
|
|
@@ -375,9 +393,10 @@ test('parallel TAOR nodes share tool and process pools, not just outer model slo
|
|
|
375
393
|
const peak: Record<string, number> = { Read: 0, Bash: 0 };
|
|
376
394
|
const h = await harness(
|
|
377
395
|
async function* ({ messages }) {
|
|
378
|
-
if (messages.some((m) => m.role === 'tool'))
|
|
396
|
+
if (messages.some((m) => m.role === 'tool')) {
|
|
379
397
|
yield { type: 'text_delta', delta: 'done' };
|
|
380
|
-
|
|
398
|
+
yield { type: 'done', stopReason: 'stop' };
|
|
399
|
+
} else {
|
|
381
400
|
yield {
|
|
382
401
|
type: 'tool_call_delta',
|
|
383
402
|
index: 0,
|
|
@@ -429,6 +448,7 @@ test('skill loads actual complete instructions for every isolated node', async (
|
|
|
429
448
|
async function* (messages) {
|
|
430
449
|
expect(JSON.stringify(messages)).toContain('USE_EXISTING_SCRIPT');
|
|
431
450
|
yield { type: 'text_delta', delta: 'done' };
|
|
451
|
+
yield { type: 'done', stopReason: 'stop' };
|
|
432
452
|
},
|
|
433
453
|
async (name, args) => {
|
|
434
454
|
expect(name).toBe('Skill');
|
package/src/advisor/README.md
CHANGED
|
@@ -2,19 +2,28 @@
|
|
|
2
2
|
|
|
3
3
|
顾问的用法向 Claude Code 自带的 advisor 看齐:**谁来问、什么时候问由主模型自己判断**
|
|
4
4
|
(规则写在 `prompts/policyRegistry.ts::capability.advisor` 和 `tools/advisor/advisor.ts::description`),
|
|
5
|
-
|
|
6
|
-
|
|
5
|
+
顾问看到的是**模型上下文窗口内的对话材料**(上下文细则见 `CONTEXT.md`),不设独立输入配额。宿主不替模型调用——
|
|
6
|
+
旧 `AdvisorCoordinator` 曾降低回答实时性并制造误伤:
|
|
7
7
|
开着顾问时每个回答被藏起来整块出现,写文件被暂缓,合成的 Advisor 调用以模型名义写进历史。已全部移除,
|
|
8
8
|
连同 `AdvisorDecision`(采纳留痕)和 `shareSensitive` 开关。
|
|
9
9
|
|
|
10
|
-
##
|
|
10
|
+
## 咨询时机与依赖
|
|
11
|
+
|
|
12
|
+
- 默认有当前交付上下文时按 `synthesis` 检查必要任务;没有交付上下文的直接调用保留独立咨询兼容性。
|
|
13
|
+
- `purpose=independent` 须显式选择:有具体问题和已有证据、不依赖未返回报告时才与后台子任务并行;不能用来绕过汇总依赖。
|
|
14
|
+
- `purpose=synthesis`:检查当前交付的必要任务;`depends_on` 可明确指定依赖(包括可选任务)。
|
|
15
|
+
- 依赖未返回、受阻、未验收或账本不可读时,仅这次汇总请求返回 `deferred`,不发模型请求、不等待占槽。主 Agent 先获取报告、补材料或接管,再咨询。
|
|
16
|
+
- 汇总附带主 Agent 的验收摘要;完整子历史不自动合并,关键证据需提供。独立意见之后只对新证据或未覆盖风险补问。
|
|
17
|
+
- 默认先明确范围与验收、派发并行调查、主 Agent 补证据、收取与核验报告,再由顾问挑战结论。重大方案取舍或连续失败可带证据提前咨询;流程解释不递归咨询。
|
|
18
|
+
|
|
19
|
+
## 动态提醒:AdvisorNudge
|
|
11
20
|
|
|
12
21
|
`advisorNudge.ts` 只在一次 `runQuery` 内记账(改动、验证、调查证据、成功的咨询次数、卡住信号),
|
|
13
22
|
产出两样东西:
|
|
14
23
|
|
|
15
24
|
1. **提醒**——写进下一次请求的动态上下文(`loop.ts::buildRequestTransientContext`):
|
|
16
25
|
- 实质请求(分析/调研/比较/计算/设计/推荐/成本或风险判断,或已调查够多)且还没咨询、还没动手:
|
|
17
|
-
|
|
26
|
+
先完成调查与依赖验收,给结论/交付前复核;不因收到提醒立刻咨询,重大取舍才提前独立问;
|
|
18
27
|
- 已有实质成果、自上次咨询后又有新进展:给出最终结论或交付之前先咨询;
|
|
19
28
|
- 同一问题连续失败/没有进展:继续重试之前先咨询(只读诊断和换路径不受影响);
|
|
20
29
|
- 请求里有明显不满/证据冲突/无法判断的表达:先核查再咨询。
|
|
@@ -27,6 +36,7 @@
|
|
|
27
36
|
"请求是否实质"仍是写之前就能知道的启发式(`deliveryReview.ts::requestNeedsTextReview`):
|
|
28
37
|
"继续/展开第二点"沿用上一条请求的判定,"计算机/对比度"这类只是含了分析词的不算。
|
|
29
38
|
这是可测试的启发式,不是语义分类器;不要把"自信"或"没有文件"当成豁免条件。
|
|
39
|
+
顾问与文件交付判断共享 `runtime/requestIntent.ts`:忽略明确标记的引用、代码围栏和日志区域,保留区域外的当前请求;原始材料仍完整给模型。无结束标记的日志由“我的请求/本轮要求/日志结束”等明确边界恢复。它不是授权解析器,也不声称理解未标记的自然语言引用。
|
|
30
40
|
|
|
31
41
|
## 弱模型兜底:贴近动作的提示 + 可选的补问(`advisor.enforcement`)
|
|
32
42
|
|
|
@@ -34,18 +44,19 @@
|
|
|
34
44
|
|
|
35
45
|
1. **首次改动提示**(始终开启):实质请求里第一次动手改东西、却还没咨询过——提示作为一行文字贴在
|
|
36
46
|
**那条工具结果**末尾(`takeActionHint`,整个运行内一次)。工具照常执行;工具结果是模型下一次请求里最近的内容。
|
|
47
|
+
它区分重大取舍与普通实现,不要求首次编辑后立刻停下来咨询;普通实现依赖收齐核验后再复核交付。
|
|
37
48
|
2. **补问回合**(配置 `advisor.enforcement: 'followup'`,默认 `'remind'`):实质回答发布后仍未复核,
|
|
38
49
|
loop 追加一条系统提示用户消息(`pushAdvisorFollowUpMarker`)再发一次请求,让**模型自己**调用 Advisor——
|
|
39
50
|
回答不撤回,Advisor 调用是模型发出的。每个 `runQuery` 最多一次;模型不理会就由 warning 收尾。
|
|
40
51
|
代价是多一次全上下文请求,只给不会主动咨询的基座开。`RunQueryOptions.advisorFollowUp` 可显式覆盖配置。
|
|
41
52
|
|
|
42
|
-
##
|
|
53
|
+
## 批内"暂缓":同一批里排在 Advisor 之后的调用
|
|
43
54
|
|
|
44
55
|
模型一次响应里同时发出 `Advisor` 和后续调用时,排在 Advisor **之后**的调用不执行(回给模型的是
|
|
45
56
|
`disposition: 'deferred'` 的说明),让它先读完意见再重新规划——与自己用顾问的方式一致:"读完意见再操作"。
|
|
46
57
|
排在 Advisor 之前的调用(比如同批的 Read)照常执行,并且已经在顾问收到的历史里
|
|
47
58
|
(`test/advisorBackground.test.ts` 锁这条)。这只是一次批内的顺序规则,不是检查点:顾问不会因此
|
|
48
|
-
|
|
59
|
+
推迟排在它之前的工具调用,也不会扣下回答。必要搜索应先做,Advisor 应放在该批最后,不预制依赖其意见的后续调用。
|
|
49
60
|
|
|
50
61
|
## 顾问自己能核实(只读工具)
|
|
51
62
|
|
|
@@ -33,6 +33,7 @@ export class AdvisorNudge {
|
|
|
33
33
|
/** 进度计数:每次改动、验证、调查证据 +1。咨询时记下当时的值。 */
|
|
34
34
|
#progress = 0;
|
|
35
35
|
#consultedAtProgress = -1;
|
|
36
|
+
#failedAtProgress = -1;
|
|
36
37
|
#mutations = 0;
|
|
37
38
|
#nonRoutineMutation = false;
|
|
38
39
|
#verifications = 0;
|
|
@@ -63,11 +64,16 @@ export class AdvisorNudge {
|
|
|
63
64
|
const name = call.function.name;
|
|
64
65
|
if (name === 'Advisor') {
|
|
65
66
|
if (result.ok) {
|
|
67
|
+
this.#failedAtProgress = -1;
|
|
66
68
|
this.#consultations++;
|
|
67
69
|
this.#consultedAtProgress = this.#progress;
|
|
68
70
|
this.#stalled.clear();
|
|
69
71
|
this.#signal = undefined;
|
|
70
72
|
}
|
|
73
|
+
else {
|
|
74
|
+
this.#failedAtProgress = this.#progress;
|
|
75
|
+
this.#actionHintDue = false;
|
|
76
|
+
}
|
|
71
77
|
return;
|
|
72
78
|
}
|
|
73
79
|
if (name === 'OptimizeConversation')
|
|
@@ -81,6 +87,16 @@ export class AdvisorNudge {
|
|
|
81
87
|
}
|
|
82
88
|
if (!result.ok)
|
|
83
89
|
return;
|
|
90
|
+
if (name === 'AgentResolve') {
|
|
91
|
+
try {
|
|
92
|
+
const action = JSON.parse(call.function.arguments).action;
|
|
93
|
+
if (action === 'accept' || action === 'complete') {
|
|
94
|
+
this.#evidence++;
|
|
95
|
+
this.#progress++;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
catch { /* malformed calls cannot become review evidence */ }
|
|
99
|
+
}
|
|
84
100
|
if (metadata?.kind === 'file_activity') {
|
|
85
101
|
const changes = metadata.files.filter((file) => MUTATING_ACTIVITY.has(file.activity));
|
|
86
102
|
this.#mutations += changes.length;
|
|
@@ -116,7 +132,7 @@ export class AdvisorNudge {
|
|
|
116
132
|
return '';
|
|
117
133
|
this.#actionHintDue = false;
|
|
118
134
|
this.#actionHinted = true;
|
|
119
|
-
return '[Advisor 提醒]
|
|
135
|
+
return '[Advisor 提醒] 已开始改动:重大方案取舍应带证据提前复核;普通实现继续按约定推进,收取并核验必要子任务后、交付前再咨询。不要仅因首次编辑就打断工作或提前评价未返回的结果。';
|
|
120
136
|
}
|
|
121
137
|
/** 连续同类失败或没有进展:继续重试之前先问(提醒,不阻止只读诊断或换路径)。 */
|
|
122
138
|
notifyStalled(signature) {
|
|
@@ -149,6 +165,8 @@ export class AdvisorNudge {
|
|
|
149
165
|
reminder() {
|
|
150
166
|
if (!this.#available)
|
|
151
167
|
return '';
|
|
168
|
+
if (this.#failedAtProgress === this.#progress)
|
|
169
|
+
return 'Advisor 本次咨询失败;当前材料不循环重试,由主 Agent 核验并继续,如实说明尚未复核。有新的实质证据后再判断是否需要咨询。';
|
|
152
170
|
const lines = [];
|
|
153
171
|
if (this.#stalled.size > 0) {
|
|
154
172
|
lines.push(this.#consultations > 0
|
|
@@ -164,11 +182,13 @@ export class AdvisorNudge {
|
|
|
164
182
|
}
|
|
165
183
|
const substantive = this.#substantive();
|
|
166
184
|
if (substantive && this.#consultations === 0 && this.#mutations === 0 && !this.#delivered) {
|
|
167
|
-
lines.push('Advisor
|
|
185
|
+
lines.push('Advisor 提醒:本回合还没有咨询顾问。先完成必要调查、收取并核验依赖子任务,再在给出分析结论或交付之前复核;不要仅因本提醒立即咨询。重大方案取舍才在动手修改前带证据独立咨询,简短即时问答和调度解释不需要。');
|
|
168
186
|
}
|
|
169
187
|
else if (substantive && this.#unreviewed()) {
|
|
170
188
|
lines.push('Advisor 提醒:本回合已有实质成果(改动、验证或调查结论),自上次咨询后又有新进展。给出最终结论或交付之前,或打算改变已定的方案/方向之前,先咨询一次 Advisor。');
|
|
171
189
|
}
|
|
190
|
+
if (lines.length)
|
|
191
|
+
lines.push('默认咨询检查当前交付依赖;仅明确不依赖未返回报告的独立问题用 purpose=independent。必要搜索先执行,Advisor 放在该批最后;不要把子任务已启动当成已返回。');
|
|
172
192
|
return lines.join('\n');
|
|
173
193
|
}
|
|
174
194
|
#answerNeedsReview(answer) {
|
|
@@ -183,7 +203,7 @@ export class AdvisorNudge {
|
|
|
183
203
|
* 判据与 warning 相同,整个运行内只给一次;回答本身已显示,不撤回。
|
|
184
204
|
*/
|
|
185
205
|
followUpDue(answer) {
|
|
186
|
-
return !this.#followedUp && this.#answerNeedsReview(answer);
|
|
206
|
+
return this.#failedAtProgress !== this.#progress && !this.#followedUp && this.#answerNeedsReview(answer);
|
|
187
207
|
}
|
|
188
208
|
markFollowedUp() {
|
|
189
209
|
this.#followedUp = true;
|
|
@@ -58,6 +58,7 @@ export class AdvisorNudge {
|
|
|
58
58
|
/** 进度计数:每次改动、验证、调查证据 +1。咨询时记下当时的值。 */
|
|
59
59
|
#progress = 0;
|
|
60
60
|
#consultedAtProgress = -1;
|
|
61
|
+
#failedAtProgress = -1;
|
|
61
62
|
#mutations = 0;
|
|
62
63
|
#nonRoutineMutation = false;
|
|
63
64
|
#verifications = 0;
|
|
@@ -91,10 +92,14 @@ export class AdvisorNudge {
|
|
|
91
92
|
const name = call.function.name;
|
|
92
93
|
if (name === 'Advisor') {
|
|
93
94
|
if (result.ok) {
|
|
95
|
+
this.#failedAtProgress = -1;
|
|
94
96
|
this.#consultations++;
|
|
95
97
|
this.#consultedAtProgress = this.#progress;
|
|
96
98
|
this.#stalled.clear();
|
|
97
99
|
this.#signal = undefined;
|
|
100
|
+
} else {
|
|
101
|
+
this.#failedAtProgress = this.#progress;
|
|
102
|
+
this.#actionHintDue = false;
|
|
98
103
|
}
|
|
99
104
|
return;
|
|
100
105
|
}
|
|
@@ -107,6 +112,15 @@ export class AdvisorNudge {
|
|
|
107
112
|
this.#progress++;
|
|
108
113
|
}
|
|
109
114
|
if (!result.ok) return;
|
|
115
|
+
if (name === 'AgentResolve') {
|
|
116
|
+
try {
|
|
117
|
+
const action = JSON.parse(call.function.arguments).action;
|
|
118
|
+
if (action === 'accept' || action === 'complete') {
|
|
119
|
+
this.#evidence++;
|
|
120
|
+
this.#progress++;
|
|
121
|
+
}
|
|
122
|
+
} catch { /* malformed calls cannot become review evidence */ }
|
|
123
|
+
}
|
|
110
124
|
if (metadata?.kind === 'file_activity') {
|
|
111
125
|
const changes = metadata.files.filter((file) => MUTATING_ACTIVITY.has(file.activity));
|
|
112
126
|
this.#mutations += changes.length;
|
|
@@ -143,7 +157,7 @@ export class AdvisorNudge {
|
|
|
143
157
|
if (!this.#actionHintDue) return '';
|
|
144
158
|
this.#actionHintDue = false;
|
|
145
159
|
this.#actionHinted = true;
|
|
146
|
-
return '[Advisor 提醒]
|
|
160
|
+
return '[Advisor 提醒] 已开始改动:重大方案取舍应带证据提前复核;普通实现继续按约定推进,收取并核验必要子任务后、交付前再咨询。不要仅因首次编辑就打断工作或提前评价未返回的结果。';
|
|
147
161
|
}
|
|
148
162
|
|
|
149
163
|
/** 连续同类失败或没有进展:继续重试之前先问(提醒,不阻止只读诊断或换路径)。 */
|
|
@@ -179,6 +193,8 @@ export class AdvisorNudge {
|
|
|
179
193
|
/** 下一次请求的动态提醒。顾问不可用时为空。 */
|
|
180
194
|
reminder(): string {
|
|
181
195
|
if (!this.#available) return '';
|
|
196
|
+
if (this.#failedAtProgress === this.#progress)
|
|
197
|
+
return 'Advisor 本次咨询失败;当前材料不循环重试,由主 Agent 核验并继续,如实说明尚未复核。有新的实质证据后再判断是否需要咨询。';
|
|
182
198
|
const lines: string[] = [];
|
|
183
199
|
if (this.#stalled.size > 0) {
|
|
184
200
|
lines.push(
|
|
@@ -198,10 +214,11 @@ export class AdvisorNudge {
|
|
|
198
214
|
}
|
|
199
215
|
const substantive = this.#substantive();
|
|
200
216
|
if (substantive && this.#consultations === 0 && this.#mutations === 0 && !this.#delivered) {
|
|
201
|
-
lines.push('Advisor
|
|
217
|
+
lines.push('Advisor 提醒:本回合还没有咨询顾问。先完成必要调查、收取并核验依赖子任务,再在给出分析结论或交付之前复核;不要仅因本提醒立即咨询。重大方案取舍才在动手修改前带证据独立咨询,简短即时问答和调度解释不需要。');
|
|
202
218
|
} else if (substantive && this.#unreviewed()) {
|
|
203
219
|
lines.push('Advisor 提醒:本回合已有实质成果(改动、验证或调查结论),自上次咨询后又有新进展。给出最终结论或交付之前,或打算改变已定的方案/方向之前,先咨询一次 Advisor。');
|
|
204
220
|
}
|
|
221
|
+
if (lines.length) lines.push('默认咨询检查当前交付依赖;仅明确不依赖未返回报告的独立问题用 purpose=independent。必要搜索先执行,Advisor 放在该批最后;不要把子任务已启动当成已返回。');
|
|
205
222
|
return lines.join('\n');
|
|
206
223
|
}
|
|
207
224
|
|
|
@@ -217,7 +234,7 @@ export class AdvisorNudge {
|
|
|
217
234
|
* 判据与 warning 相同,整个运行内只给一次;回答本身已显示,不撤回。
|
|
218
235
|
*/
|
|
219
236
|
followUpDue(answer: string): boolean {
|
|
220
|
-
return !this.#followedUp && this.#answerNeedsReview(answer);
|
|
237
|
+
return this.#failedAtProgress !== this.#progress && !this.#followedUp && this.#answerNeedsReview(answer);
|
|
221
238
|
}
|
|
222
239
|
|
|
223
240
|
markFollowedUp(): void {
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { requestIntentText } from '../runtime/requestIntent.js';
|
|
1
2
|
/** Conservative text-delivery signals, not a claim of semantic understanding.
|
|
2
3
|
* Keep tiny acknowledgements/questions cheap; substantive text is an artifact too.
|
|
3
4
|
*/
|
|
@@ -17,6 +18,7 @@ const CONCLUSION_REQUEST = /建议|推荐|结论|成本|费用|计费|预算|价
|
|
|
17
18
|
* 40-character reply containing 建议/风险 was force-reviewed.
|
|
18
19
|
*/
|
|
19
20
|
export function requestNeedsTextReview(request, previousRequest) {
|
|
21
|
+
request = requestIntentText(request);
|
|
20
22
|
if (isReviewProcessQuestion(request))
|
|
21
23
|
return false;
|
|
22
24
|
if (ANALYSIS_TASK.test(request) || CONCLUSION_REQUEST.test(request))
|
|
@@ -46,13 +48,16 @@ export function needsTextDeliveryReview(request, draft, previousRequest) {
|
|
|
46
48
|
* A request to change code or review real deliverables is not a process question.
|
|
47
49
|
*/
|
|
48
50
|
export function isReviewProcessQuestion(request) {
|
|
49
|
-
|
|
51
|
+
request = requestIntentText(request);
|
|
52
|
+
const actions = request.replace(/(?:不要|不用|无需|不必|不需要)(?:再|去)?\s*(?:修复|重构|实现|开发|部署|修改|审查|评审)(?:代码)?|\b(?:do not|don't|no need to)\s+(?:implement|refactor|deploy|fix)\b/gi, '');
|
|
53
|
+
if (/修复|重构|实现|开发|部署|修改|审查代码|评审代码|\b(?:implement|refactor|deploy|fix)\b/i.test(actions))
|
|
50
54
|
return false;
|
|
51
55
|
return /顾问|咨询|advisor/i.test(request)
|
|
52
|
-
&&
|
|
56
|
+
&& /几次|次数|频繁|频率|太多|重复咨询|咨询时机|触发|流程|顺序|正常吗|为什么|为何|\b(?:why|how many|too often|frequency)\b/i.test(request);
|
|
53
57
|
}
|
|
54
58
|
/** Narrow, explicit maintenance scope, not a line-count-based risk exemption. */
|
|
55
59
|
export function isRoutineMaintenanceRequest(request) {
|
|
60
|
+
request = requestIntentText(request);
|
|
56
61
|
if (/权限|认证|密钥|安全|支付|迁移|部署|协议|架构|删除|\b(?:auth|secret|security|payment|migration|deploy|delete)\b/i.test(request))
|
|
57
62
|
return false;
|
|
58
63
|
return isCosmeticRequest(request) ||
|
|
@@ -62,6 +67,7 @@ export function isRoutineMaintenancePath(path) {
|
|
|
62
67
|
return /(?:^|[\\/])(?:README(?:\.(?:md|txt|rst))?|\.gitignore)$/i.test(path);
|
|
63
68
|
}
|
|
64
69
|
export function reviewSignal(text) {
|
|
70
|
+
text = requestIntentText(text);
|
|
65
71
|
if (isReviewProcessQuestion(text))
|
|
66
72
|
return;
|
|
67
73
|
// Topic discussion and explicit absence of conflict are not incident signals.
|
|
@@ -77,5 +83,6 @@ export function reviewSignal(text) {
|
|
|
77
83
|
}
|
|
78
84
|
/** Only explicit cosmetic edits skip implementation review; ambiguous edits do not. */
|
|
79
85
|
export function isCosmeticRequest(request) {
|
|
86
|
+
request = requestIntentText(request);
|
|
80
87
|
return /^(?:请)?(?:只|仅)(?:修改|修正|改|调整).{0,30}(?:错别字|拼写|标点|文案|typo|spelling)[。.!!]?$/i.test(request.trim());
|
|
81
88
|
}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { requestIntentText } from '../runtime/requestIntent.js';
|
|
2
|
+
|
|
1
3
|
/** Conservative text-delivery signals, not a claim of semantic understanding.
|
|
2
4
|
* Keep tiny acknowledgements/questions cheap; substantive text is an artifact too.
|
|
3
5
|
*/
|
|
@@ -18,6 +20,7 @@ const CONCLUSION_REQUEST = /建议|推荐|结论|成本|费用|计费|预算|价
|
|
|
18
20
|
* 40-character reply containing 建议/风险 was force-reviewed.
|
|
19
21
|
*/
|
|
20
22
|
export function requestNeedsTextReview(request: string, previousRequest?: string): boolean {
|
|
23
|
+
request = requestIntentText(request);
|
|
21
24
|
if (isReviewProcessQuestion(request)) return false;
|
|
22
25
|
if (ANALYSIS_TASK.test(request) || CONCLUSION_REQUEST.test(request)) return true;
|
|
23
26
|
// "继续"/"展开第二点" continue the previous request's deliverable, so they
|
|
@@ -44,13 +47,16 @@ export function needsTextDeliveryReview(request: string, draft: string, previous
|
|
|
44
47
|
* A request to change code or review real deliverables is not a process question.
|
|
45
48
|
*/
|
|
46
49
|
export function isReviewProcessQuestion(request: string): boolean {
|
|
47
|
-
|
|
50
|
+
request = requestIntentText(request);
|
|
51
|
+
const actions = request.replace(/(?:不要|不用|无需|不必|不需要)(?:再|去)?\s*(?:修复|重构|实现|开发|部署|修改|审查|评审)(?:代码)?|\b(?:do not|don't|no need to)\s+(?:implement|refactor|deploy|fix)\b/gi, '');
|
|
52
|
+
if (/修复|重构|实现|开发|部署|修改|审查代码|评审代码|\b(?:implement|refactor|deploy|fix)\b/i.test(actions)) return false;
|
|
48
53
|
return /顾问|咨询|advisor/i.test(request)
|
|
49
|
-
&&
|
|
54
|
+
&& /几次|次数|频繁|频率|太多|重复咨询|咨询时机|触发|流程|顺序|正常吗|为什么|为何|\b(?:why|how many|too often|frequency)\b/i.test(request);
|
|
50
55
|
}
|
|
51
56
|
|
|
52
57
|
/** Narrow, explicit maintenance scope, not a line-count-based risk exemption. */
|
|
53
58
|
export function isRoutineMaintenanceRequest(request: string): boolean {
|
|
59
|
+
request = requestIntentText(request);
|
|
54
60
|
if (/权限|认证|密钥|安全|支付|迁移|部署|协议|架构|删除|\b(?:auth|secret|security|payment|migration|deploy|delete)\b/i.test(request)) return false;
|
|
55
61
|
return isCosmeticRequest(request) ||
|
|
56
62
|
/^(?:请)?(?:只|仅)(?:修改|修正|改|调整|更新|整理).{0,40}(?:注释|README|\.gitignore|忽略规则)[。.!!]?$/i.test(request.trim());
|
|
@@ -61,6 +67,7 @@ export function isRoutineMaintenancePath(path: string): boolean {
|
|
|
61
67
|
}
|
|
62
68
|
|
|
63
69
|
export function reviewSignal(text: string): 'user_dissatisfaction' | 'evidence_conflict' | 'uncertainty' | undefined {
|
|
70
|
+
text = requestIntentText(text);
|
|
64
71
|
if (isReviewProcessQuestion(text)) return;
|
|
65
72
|
// Topic discussion and explicit absence of conflict are not incident signals.
|
|
66
73
|
if (/^(?:什么是|解释一下|介绍一下|如何处理|what is|explain)\s*/i.test(text.trim())) return;
|
|
@@ -72,5 +79,6 @@ export function reviewSignal(text: string): 'user_dissatisfaction' | 'evidence_c
|
|
|
72
79
|
|
|
73
80
|
/** Only explicit cosmetic edits skip implementation review; ambiguous edits do not. */
|
|
74
81
|
export function isCosmeticRequest(request: string): boolean {
|
|
82
|
+
request = requestIntentText(request);
|
|
75
83
|
return /^(?:请)?(?:只|仅)(?:修改|修正|改|调整).{0,30}(?:错别字|拼写|标点|文案|typo|spelling)[。.!!]?$/i.test(request.trim());
|
|
76
84
|
}
|
package/src/cli/args.js
CHANGED
package/src/cli/args.ts
CHANGED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { getWorkingDir } from '../bootstrap/workingDir.js';
|
|
2
|
+
import { getContextPath } from '../context/persistContext.js';
|
|
3
|
+
import { updateSessionMetadata } from '../context/sessionRegistry.js';
|
|
4
|
+
import { workspaceIndexService } from '../context/workspaceIndex.js';
|
|
5
|
+
import { previousUserRequest } from '../memory/recallQuery.js';
|
|
6
|
+
import { createPromptCacheContext } from '../llm/promptCache.js';
|
|
7
|
+
import { buildTransientPromptBundle, browserPromptRuntime, } from '../prompts/system.js';
|
|
8
|
+
import { refreshStableSystemPrompt } from '../prompts/stableSystemPrompt.js';
|
|
9
|
+
import { backgroundCompletionFields } from '../runtime/backgroundCompletion.js';
|
|
10
|
+
import { createAgentRuntimeContext, filterToolsForRuntime, memoryContextFromRuntime, } from '../runtime/agentRuntimeContext.js';
|
|
11
|
+
import { runTurn } from '../session/runTurn.js';
|
|
12
|
+
import { createSessionState, disposeDetachedSessionState, } from '../session/sessionState.js';
|
|
13
|
+
import { ALL_TOOLS } from '../tools/index.js';
|
|
14
|
+
import { classifyComputerAutomationIntent } from '../tools/computeruse/computerIntent.js';
|
|
15
|
+
import { listRunningBackgroundTasks } from '../tools/tasks/backgroundTaskService.js';
|
|
16
|
+
import { hydrateSessionWorktree } from '../tools/worktree/sessionWorktree.js';
|
|
17
|
+
import { createLocalBrowserScope } from './browser.js';
|
|
18
|
+
import { createCliComputerRun, } from './computerUse.js';
|
|
19
|
+
/** Both print transports use the same locked, journalled user-turn lifecycle. */
|
|
20
|
+
export async function* runHeadlessTurn(provider, prompt, options) {
|
|
21
|
+
const sessionState = createSessionState();
|
|
22
|
+
const browsers = createLocalBrowserScope();
|
|
23
|
+
const cwdRoot = options.workspace?.cwd ?? getWorkingDir();
|
|
24
|
+
const sessionId = options.workspace?.sessionId ?? 'default';
|
|
25
|
+
let terminal;
|
|
26
|
+
let failed = false;
|
|
27
|
+
for await (const event of runTurn({
|
|
28
|
+
userInput: prompt,
|
|
29
|
+
provider,
|
|
30
|
+
sessionFile: options.sessionFile ?? getContextPath(),
|
|
31
|
+
strictPersistence: true,
|
|
32
|
+
signal: options.signal,
|
|
33
|
+
maxTurns: options.maxTurns,
|
|
34
|
+
imageInputs: options.imageInputs,
|
|
35
|
+
parseInlineImages: true,
|
|
36
|
+
imageDetail: options.imageDetail,
|
|
37
|
+
imageMaxLongSidePixel: options.imageMaxLongSidePixel,
|
|
38
|
+
prepare: async (history) => {
|
|
39
|
+
const workspace = await workspaceIndexService.register(cwdRoot, previousUserRequest(history) ?? prompt);
|
|
40
|
+
await hydrateSessionWorktree({
|
|
41
|
+
sessionState,
|
|
42
|
+
workspaceId: workspace.id,
|
|
43
|
+
sessionId,
|
|
44
|
+
cwd: cwdRoot,
|
|
45
|
+
});
|
|
46
|
+
const cwd = sessionState.activeWorktree?.path ?? cwdRoot;
|
|
47
|
+
const conversationKey = `workspace:${workspace.id}:session:${sessionId}`;
|
|
48
|
+
const computerRun = options.computerUseMode && options.computerUseMode !== 'disabled'
|
|
49
|
+
? createCliComputerRun({
|
|
50
|
+
mode: options.computerUseMode,
|
|
51
|
+
surface: 'cli',
|
|
52
|
+
conversationKey,
|
|
53
|
+
userInput: prompt,
|
|
54
|
+
allowedFileRoots: [cwd],
|
|
55
|
+
supervised: options.interactive,
|
|
56
|
+
diagnosticTraceDir: options.computerUseTraceDir,
|
|
57
|
+
})
|
|
58
|
+
: undefined;
|
|
59
|
+
const runtimeContext = createAgentRuntimeContext({
|
|
60
|
+
surface: options.host === 'cli' ? 'cli' : 'headless',
|
|
61
|
+
host: options.host,
|
|
62
|
+
profile: 'main',
|
|
63
|
+
cwd,
|
|
64
|
+
workspaceId: workspace.id,
|
|
65
|
+
sessionId,
|
|
66
|
+
owner: options.memoryAccess === 'denied' ? 'untrusted' : 'local-owner',
|
|
67
|
+
memoryAccess: options.memoryAccess ?? 'read-only',
|
|
68
|
+
interactiveAsk: options.interactive,
|
|
69
|
+
browser: await browsers.resolve({
|
|
70
|
+
mode: options.browserMode ?? 'headless',
|
|
71
|
+
conversationKey,
|
|
72
|
+
userInput: prompt,
|
|
73
|
+
allowedUploadRoots: [cwd],
|
|
74
|
+
}),
|
|
75
|
+
computer: computerRun,
|
|
76
|
+
computerIntent: classifyComputerAutomationIntent(prompt, sessionState.computerAutomation),
|
|
77
|
+
});
|
|
78
|
+
const tools = filterToolsForRuntime(ALL_TOOLS, runtimeContext);
|
|
79
|
+
await refreshStableSystemPrompt(history, cwd, tools);
|
|
80
|
+
const transientBundle = await buildTransientPromptBundle({
|
|
81
|
+
cwd,
|
|
82
|
+
tools,
|
|
83
|
+
runtime: {
|
|
84
|
+
surface: runtimeContext.surface,
|
|
85
|
+
host: options.host,
|
|
86
|
+
cwd,
|
|
87
|
+
workspaceId: workspace.id,
|
|
88
|
+
sessionId,
|
|
89
|
+
interactiveAsk: options.interactive,
|
|
90
|
+
memoryAccess: runtimeContext.memoryAccess,
|
|
91
|
+
browser: browserPromptRuntime(runtimeContext.browser, provider.supportsVision),
|
|
92
|
+
currentUserInput: prompt,
|
|
93
|
+
previousUserInput: previousUserRequest(history),
|
|
94
|
+
contextWindow: provider.contextWindow,
|
|
95
|
+
},
|
|
96
|
+
});
|
|
97
|
+
await updateSessionMetadata(cwdRoot, sessionId, {
|
|
98
|
+
lastMessagePreview: prompt,
|
|
99
|
+
}).catch(() => { });
|
|
100
|
+
return {
|
|
101
|
+
runtimeContext,
|
|
102
|
+
sessionState,
|
|
103
|
+
computerRun,
|
|
104
|
+
transientBundle,
|
|
105
|
+
allowedTools: tools.map((tool) => tool.name),
|
|
106
|
+
promptCache: createPromptCacheContext(conversationKey),
|
|
107
|
+
memoryContext: memoryContextFromRuntime(runtimeContext),
|
|
108
|
+
};
|
|
109
|
+
},
|
|
110
|
+
cleanup: async () => {
|
|
111
|
+
try {
|
|
112
|
+
await disposeDetachedSessionState(sessionState);
|
|
113
|
+
}
|
|
114
|
+
finally {
|
|
115
|
+
await browsers.dispose();
|
|
116
|
+
}
|
|
117
|
+
},
|
|
118
|
+
})) {
|
|
119
|
+
if (event.type === 'error' && event.code !== 'compact_failed')
|
|
120
|
+
failed = true;
|
|
121
|
+
if (event.type === 'turn_done') {
|
|
122
|
+
terminal = {
|
|
123
|
+
...event,
|
|
124
|
+
...backgroundCompletionFields(sessionState.backgroundTasks),
|
|
125
|
+
};
|
|
126
|
+
const running = listRunningBackgroundTasks(sessionState.backgroundTasks);
|
|
127
|
+
if (running.length)
|
|
128
|
+
yield {
|
|
129
|
+
type: 'warning',
|
|
130
|
+
message: `${running.length} 个后台任务尚未完成,本次 CLI 收尾将终止它们,其结果未经验证:` +
|
|
131
|
+
running
|
|
132
|
+
.map((task) => `${task.id}(${task.command.slice(0, 80)})`)
|
|
133
|
+
.join(';'),
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
else
|
|
137
|
+
yield event;
|
|
138
|
+
}
|
|
139
|
+
// A terminal success is only published after persistence and resource cleanup.
|
|
140
|
+
options.signal.throwIfAborted();
|
|
141
|
+
if (terminal && !failed)
|
|
142
|
+
yield terminal;
|
|
143
|
+
}
|