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
|
@@ -72,9 +72,10 @@ const MAIN_POLICIES: PromptPolicySpec[] = [
|
|
|
72
72
|
{
|
|
73
73
|
id: 'identity.working-style', layer: 'identity', profiles: ['main'], source: '01',
|
|
74
74
|
render: () => `# 工作方式
|
|
75
|
-
-
|
|
75
|
+
- 独立判断,不奉承;跟随用户语言,默认中文。
|
|
76
76
|
- 从用户措辞判断是讨论还是执行。明确要求实现、修改、修复、重构时直接完成;纯解释或评估时保持只读。
|
|
77
77
|
- 信息足够时自行选择稳健默认值。只有关键输入无法推断、存在影响方向的真实取舍,或不可逆高风险操作前才询问。
|
|
78
|
+
- 按领域专家的方法工作,不只模仿语气:明确约束与判据,选择适用方法和已授权工具,用反例或检查检验假设;简单任务不堆流程。
|
|
78
79
|
- 找根因并在职责所属层修复;说明重要取舍,不用临时 workaround 冒充完整解决。`,
|
|
79
80
|
},
|
|
80
81
|
{
|
|
@@ -298,10 +299,11 @@ const CAPABILITY_POLICIES: PromptPolicySpec[] = [
|
|
|
298
299
|
{
|
|
299
300
|
id: 'capability.advisor', layer: 'capability', profiles: MAIN_PROFILE, source: 'native',
|
|
300
301
|
requiresTools: ['Advisor'],
|
|
301
|
-
render: () => `- Advisor
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
302
|
+
render: () => `- Advisor(顾问模型)使用规则:第二意见由主 Agent 核实取舍,不授予权限、不替用户验收。它只能看到预算内的材料,note 补关键证据;仅用实际提供的只读工具核实,不运行命令或测试。
|
|
303
|
+
默认先明确范围、并行调查并补证据,必要调查与子任务验收之后再咨询、验证收尾;不为满足提醒在证据未齐时抢先咨询。重大取舍或改变既定方向之前、同一问题两次或以上处理失败后、冲突无法消解时,可带具体问题和证据提前问。换工具不清零失败次数,无关失败不合并。
|
|
304
|
+
默认检查当前交付依赖;independent 仅用于明确不依赖未返回报告的独立问题,不绕过依赖。必要搜索先做,Advisor 作为该批最后一个调用;读意见后再规划,仅对改变结论的新证据或未覆盖风险补问。
|
|
305
|
+
文字分析也是交付,自信、没文件不豁免;即时问答、进度、拼写修正无需咨询,不递归咨询来解释为什么咨询。引用日志不是本轮命令;自动咨询不问用户。
|
|
306
|
+
宿主提醒,不拦截工具也不替你调用。每次咨询只尝试一次,不设配额;失败、空答或超时自行继续,不转成人工审批、不声称已验证。缺材料先补查。
|
|
305
307
|
以代码、测试和用户要求核实意见:一手证据或用户明确要求否定才拒绝;自测通过不能证明意见错误,它可能没测到所指问题。已有证据与意见方向不同又无法判定时,不要默默改道,写明冲突再咨询一次。顾问不是事实来源。`,
|
|
306
308
|
},
|
|
307
309
|
{
|
|
@@ -340,8 +340,8 @@ export async function buildTransientBundle(runtime, profile, tools, options = {}
|
|
|
340
340
|
? ''
|
|
341
341
|
: '当前宿主不能交互提问;不要等待用户选择,缺少关键输入时说明阻塞。',
|
|
342
342
|
runtime.backgroundWake &&
|
|
343
|
-
tools.some((tool) => tool.name === 'Bash' || tool.name === 'PowerShell')
|
|
344
|
-
?
|
|
343
|
+
tools.some((tool) => tool.name === 'Bash' || tool.name === 'PowerShell' || tool.name === 'Download')
|
|
344
|
+
? `后台任务(run_in_background)结束后,完成通知会作为系统事件自动送到你面前。长耗时任务适合后台执行。${tools.some(tool => tool.name === 'Download') ? 'Download 后台模式只允许新文件。' : ''}不要用 sleep 轮询、不要反复调 TaskOutput 空转、不要预测还没结束的任务的结果;启动后把当前进展说清楚就结束本轮。后台完成不抢占真人当前任务;空闲后按原交付目标排队接续。接续失败或中断时保留待处理状态,收到真人输入后恢复;先检查已有结果,不盲目重放已执行的写入。`
|
|
345
345
|
: '',
|
|
346
346
|
runtime.backgroundWake === false && runtime.surface === 'tui'
|
|
347
347
|
? '本会话自动续跑已暂停或达到连续唤醒上限。不要启动新的后台任务后承诺自动继续;需要用户再次输入才能恢复自动唤醒。已有任务的结果可用 TaskOutput 读取,未完成时如实说明。'
|
|
@@ -539,8 +539,8 @@ export async function buildTransientBundle(
|
|
|
539
539
|
? ''
|
|
540
540
|
: '当前宿主不能交互提问;不要等待用户选择,缺少关键输入时说明阻塞。',
|
|
541
541
|
runtime.backgroundWake &&
|
|
542
|
-
tools.some((tool) => tool.name === 'Bash' || tool.name === 'PowerShell')
|
|
543
|
-
?
|
|
542
|
+
tools.some((tool) => tool.name === 'Bash' || tool.name === 'PowerShell' || tool.name === 'Download')
|
|
543
|
+
? `后台任务(run_in_background)结束后,完成通知会作为系统事件自动送到你面前。长耗时任务适合后台执行。${tools.some(tool => tool.name === 'Download') ? 'Download 后台模式只允许新文件。' : ''}不要用 sleep 轮询、不要反复调 TaskOutput 空转、不要预测还没结束的任务的结果;启动后把当前进展说清楚就结束本轮。后台完成不抢占真人当前任务;空闲后按原交付目标排队接续。接续失败或中断时保留待处理状态,收到真人输入后恢复;先检查已有结果,不盲目重放已执行的写入。`
|
|
544
544
|
: '',
|
|
545
545
|
runtime.backgroundWake === false && runtime.surface === 'tui'
|
|
546
546
|
? '本会话自动续跑已暂停或达到连续唤醒上限。不要启动新的后台任务后承诺自动继续;需要用户再次输入才能恢复自动唤醒。已有任务的结果可用 TaskOutput 读取,未完成时如实说明。'
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/** A conservative view for host intent heuristics, NOT an authorization parser.
|
|
2
|
+
* Keep the original request in model history. Only explicitly marked evidence
|
|
3
|
+
* is omitted here; prose is not guessed away because it resembles a log.
|
|
4
|
+
* Unfenced evidence lasts until an explicit request/resume heading. */
|
|
5
|
+
export function requestIntentText(input) {
|
|
6
|
+
const out = [];
|
|
7
|
+
let fence = '';
|
|
8
|
+
let evidence = false;
|
|
9
|
+
let bracketDepth = 0;
|
|
10
|
+
let remainder;
|
|
11
|
+
const consumeQuote = (line, start = 0) => {
|
|
12
|
+
for (let i = start; i < line.length; i++) {
|
|
13
|
+
if (line[i] === '【')
|
|
14
|
+
bracketDepth++;
|
|
15
|
+
if (line[i] === '】' && --bracketDepth === 0) {
|
|
16
|
+
remainder = line.slice(i + 1);
|
|
17
|
+
return;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
const lines = input.replace(/\r\n?/g, '\n').split('\n');
|
|
22
|
+
let index = 0;
|
|
23
|
+
while (index < lines.length || remainder !== undefined) {
|
|
24
|
+
const line = remainder ?? lines[index++];
|
|
25
|
+
remainder = undefined;
|
|
26
|
+
const mark = /^\s*(`{3,}|~{3,})/.exec(line)?.[1];
|
|
27
|
+
if (fence) {
|
|
28
|
+
if (mark?.[0] === fence[0] && mark.length >= fence.length) {
|
|
29
|
+
fence = '';
|
|
30
|
+
evidence = false;
|
|
31
|
+
}
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
34
|
+
if (mark) {
|
|
35
|
+
fence = mark;
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
if (/^\s*>/.test(line))
|
|
39
|
+
continue;
|
|
40
|
+
if (!bracketDepth && /^\s*(?:#{1,6}\s*)?(?:我的(?:请求|问题|要求)|本轮(?:请求|问题|要求)|以上(?:是|为)(?:日志|记录|引用|材料)|引用结束|日志结束|my request|end (?:log|quote|transcript))\s*[::]?/i.test(line)) {
|
|
41
|
+
evidence = false;
|
|
42
|
+
out.push(line.replace(/^\s*(?:#{1,6}\s*)?(?:我的(?:请求|问题|要求)|本轮(?:请求|问题|要求)|以上(?:是|为)(?:日志|记录|引用|材料)|引用结束|日志结束|my request|end (?:log|quote|transcript))\s*[::]?/i, ''));
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
if (bracketDepth) {
|
|
46
|
+
consumeQuote(line);
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
if (evidence) {
|
|
50
|
+
if (line.trimStart().startsWith('【')) {
|
|
51
|
+
evidence = false;
|
|
52
|
+
consumeQuote(line.trimStart());
|
|
53
|
+
}
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
if (/^\s*(?:#{1,6}\s*)?(?:下面|以下)(?:是|为)?[^::【\n]{0,40}(?:日志|对话记录|聊天记录|回复|输出|引用|材料)\s*[::]?\s*$/.test(line)) {
|
|
57
|
+
evidence = true;
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
// A labelled paste may follow the user's question on the same line.
|
|
61
|
+
const label = /(?:(?:下面|以下)(?:是|为)?(?:[^\n::【]{0,20})?(?:日志|对话记录|聊天记录|回复|输出|引用|材料)|(?<![\p{L}\p{N}_])(?:参考)?(?:日志|对话记录|聊天记录|引用|log|transcript|quoted text))\s*[::]/iu.exec(line);
|
|
62
|
+
if (label) {
|
|
63
|
+
out.push(line.slice(0, label.index));
|
|
64
|
+
const rest = line.slice(label.index + label[0].length).trim();
|
|
65
|
+
if (/^(`{3,}|~{3,})/.test(rest)) {
|
|
66
|
+
fence = /^(`{3,}|~{3,})/.exec(rest)[1];
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
if (!rest.startsWith('【')) {
|
|
70
|
+
evidence = true;
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
consumeQuote(rest);
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
// Chinese quotation blocks commonly used when asking whether a report is true.
|
|
77
|
+
const start = line.indexOf('【');
|
|
78
|
+
if (start >= 0 && /(?:说法|日志|记录|回复|输出|引用|材料|如下|下面|以下)/.test(line.slice(0, start))) {
|
|
79
|
+
out.push(line.slice(0, start));
|
|
80
|
+
consumeQuote(line, start);
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
out.push(line);
|
|
84
|
+
}
|
|
85
|
+
return out.join('\n').trim();
|
|
86
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/** A conservative view for host intent heuristics, NOT an authorization parser.
|
|
2
|
+
* Keep the original request in model history. Only explicitly marked evidence
|
|
3
|
+
* is omitted here; prose is not guessed away because it resembles a log.
|
|
4
|
+
* Unfenced evidence lasts until an explicit request/resume heading. */
|
|
5
|
+
export function requestIntentText(input: string): string {
|
|
6
|
+
const out: string[] = [];
|
|
7
|
+
let fence = '';
|
|
8
|
+
let evidence = false;
|
|
9
|
+
let bracketDepth = 0;
|
|
10
|
+
let remainder: string | undefined;
|
|
11
|
+
const consumeQuote = (line: string, start = 0) => {
|
|
12
|
+
for (let i = start; i < line.length; i++) {
|
|
13
|
+
if (line[i] === '【') bracketDepth++;
|
|
14
|
+
if (line[i] === '】' && --bracketDepth === 0) { remainder = line.slice(i + 1); return; }
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
const lines = input.replace(/\r\n?/g, '\n').split('\n');
|
|
18
|
+
let index = 0;
|
|
19
|
+
while (index < lines.length || remainder !== undefined) {
|
|
20
|
+
const line = remainder ?? lines[index++]!;
|
|
21
|
+
remainder = undefined;
|
|
22
|
+
const mark = /^\s*(`{3,}|~{3,})/.exec(line)?.[1];
|
|
23
|
+
if (fence) {
|
|
24
|
+
if (mark?.[0] === fence[0] && mark.length >= fence.length) { fence = ''; evidence = false; }
|
|
25
|
+
continue;
|
|
26
|
+
}
|
|
27
|
+
if (mark) { fence = mark; continue; }
|
|
28
|
+
if (/^\s*>/.test(line)) continue;
|
|
29
|
+
if (!bracketDepth && /^\s*(?:#{1,6}\s*)?(?:我的(?:请求|问题|要求)|本轮(?:请求|问题|要求)|以上(?:是|为)(?:日志|记录|引用|材料)|引用结束|日志结束|my request|end (?:log|quote|transcript))\s*[::]?/i.test(line)) {
|
|
30
|
+
evidence = false;
|
|
31
|
+
out.push(line.replace(/^\s*(?:#{1,6}\s*)?(?:我的(?:请求|问题|要求)|本轮(?:请求|问题|要求)|以上(?:是|为)(?:日志|记录|引用|材料)|引用结束|日志结束|my request|end (?:log|quote|transcript))\s*[::]?/i, ''));
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
34
|
+
if (bracketDepth) {
|
|
35
|
+
consumeQuote(line);
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
if (evidence) {
|
|
39
|
+
if (line.trimStart().startsWith('【')) { evidence = false; consumeQuote(line.trimStart()); }
|
|
40
|
+
continue;
|
|
41
|
+
}
|
|
42
|
+
if (/^\s*(?:#{1,6}\s*)?(?:下面|以下)(?:是|为)?[^::【\n]{0,40}(?:日志|对话记录|聊天记录|回复|输出|引用|材料)\s*[::]?\s*$/.test(line)) {
|
|
43
|
+
evidence = true;
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
// A labelled paste may follow the user's question on the same line.
|
|
47
|
+
const label = /(?:(?:下面|以下)(?:是|为)?(?:[^\n::【]{0,20})?(?:日志|对话记录|聊天记录|回复|输出|引用|材料)|(?<![\p{L}\p{N}_])(?:参考)?(?:日志|对话记录|聊天记录|引用|log|transcript|quoted text))\s*[::]/iu.exec(line);
|
|
48
|
+
if (label) {
|
|
49
|
+
out.push(line.slice(0, label.index));
|
|
50
|
+
const rest = line.slice(label.index + label[0].length).trim();
|
|
51
|
+
if (/^(`{3,}|~{3,})/.test(rest)) { fence = /^(`{3,}|~{3,})/.exec(rest)![1]!; continue; }
|
|
52
|
+
if (!rest.startsWith('【')) { evidence = true; continue; }
|
|
53
|
+
consumeQuote(rest);
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
// Chinese quotation blocks commonly used when asking whether a report is true.
|
|
57
|
+
const start = line.indexOf('【');
|
|
58
|
+
if (start >= 0 && /(?:说法|日志|记录|回复|输出|引用|材料|如下|下面|以下)/.test(line.slice(0, start))) {
|
|
59
|
+
out.push(line.slice(0, start));
|
|
60
|
+
consumeQuote(line, start);
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
out.push(line);
|
|
64
|
+
}
|
|
65
|
+
return out.join('\n').trim();
|
|
66
|
+
}
|
|
@@ -3,8 +3,17 @@ export const BACKGROUND_WAKE_MARKER = '[系统事件 · 不是用户输入]';
|
|
|
3
3
|
export function isSystemEventMessage(message) {
|
|
4
4
|
if (message.role !== 'user')
|
|
5
5
|
return false;
|
|
6
|
+
if (message.inputOrigin)
|
|
7
|
+
return true;
|
|
6
8
|
if (/^(?:agent-notice:|proc-notice:|proc-wake:)/.test(message.id ?? ''))
|
|
7
9
|
return true;
|
|
8
10
|
// Compatibility for wake stubs persisted before IDs were tagged.
|
|
9
|
-
|
|
11
|
+
const text = typeof message.content === 'string' ? message.content
|
|
12
|
+
: message.content.find(part => part.type === 'text')?.text ?? '';
|
|
13
|
+
return [BACKGROUND_WAKE_MARKER, 'This session is being continued from a previous conversation',
|
|
14
|
+
'(自动压缩失败:', '(LLM 摘要压缩失败,已使用规则式截断继续会话)',
|
|
15
|
+
'(LLM 返回了无效摘要,已使用规则式截断继续会话)',
|
|
16
|
+
'【实况图像】上面是刚才工具执行后附带的真实图像',
|
|
17
|
+
'【实况图像】(此前的实况图像已从上下文移除以节省空间。)',
|
|
18
|
+
].some(prefix => text.startsWith(prefix));
|
|
10
19
|
}
|
|
@@ -5,7 +5,15 @@ export const BACKGROUND_WAKE_MARKER = '[系统事件 · 不是用户输入]';
|
|
|
5
5
|
/** Host events use stable IDs, not a provider role pretending to be a human. */
|
|
6
6
|
export function isSystemEventMessage(message: Message): boolean {
|
|
7
7
|
if (message.role !== 'user') return false;
|
|
8
|
+
if (message.inputOrigin) return true;
|
|
8
9
|
if (/^(?:agent-notice:|proc-notice:|proc-wake:)/.test(message.id ?? '')) return true;
|
|
9
10
|
// Compatibility for wake stubs persisted before IDs were tagged.
|
|
10
|
-
|
|
11
|
+
const text = typeof message.content === 'string' ? message.content
|
|
12
|
+
: message.content.find(part => part.type === 'text')?.text ?? '';
|
|
13
|
+
return [BACKGROUND_WAKE_MARKER, 'This session is being continued from a previous conversation',
|
|
14
|
+
'(自动压缩失败:', '(LLM 摘要压缩失败,已使用规则式截断继续会话)',
|
|
15
|
+
'(LLM 返回了无效摘要,已使用规则式截断继续会话)',
|
|
16
|
+
'【实况图像】上面是刚才工具执行后附带的真实图像',
|
|
17
|
+
'【实况图像】(此前的实况图像已从上下文移除以节省空间。)',
|
|
18
|
+
].some(prefix => text.startsWith(prefix));
|
|
11
19
|
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { createPublicTextStream } from '../ui/publicText.js';
|
|
2
|
+
/** A slash command can expand into a different model input, or never call the
|
|
3
|
+
* model at all. Keep the UI transcript independent of that routing decision. */
|
|
4
|
+
export function commandRequest(input, userMessageId) {
|
|
5
|
+
return { role: 'system', _ephemeral: true, _uiProgress: true,
|
|
6
|
+
id: `command:${userMessageId}`, timestamp: Date.now(), content: input,
|
|
7
|
+
commandDisplay: { kind: 'request', userMessageId } };
|
|
8
|
+
}
|
|
9
|
+
/** Some deterministic plugins emit only text + turn_done. Model turns and
|
|
10
|
+
* workflows own their own drafts, echoes, and committed history. Never promote
|
|
11
|
+
* their preview (including a replayed echo) into a second or invented answer. */
|
|
12
|
+
export function captureCommandReply(userMessageId) {
|
|
13
|
+
const stream = createPublicTextStream();
|
|
14
|
+
const chunks = [];
|
|
15
|
+
let standalone = true;
|
|
16
|
+
let resultNumber = 0;
|
|
17
|
+
const result = (content) => ({
|
|
18
|
+
role: 'system', _ephemeral: true, _uiProgress: true,
|
|
19
|
+
id: `command:${userMessageId}:result:${++resultNumber}`, timestamp: Date.now(), content,
|
|
20
|
+
commandDisplay: { kind: 'result' },
|
|
21
|
+
});
|
|
22
|
+
return (event) => {
|
|
23
|
+
if (event.type === 'text' && event.commandResult === true && typeof event.delta === 'string') {
|
|
24
|
+
standalone = false;
|
|
25
|
+
chunks.length = 0;
|
|
26
|
+
stream.reset();
|
|
27
|
+
const content = stream.append(event.delta) + stream.finish();
|
|
28
|
+
return content.trim() ? result(content) : undefined;
|
|
29
|
+
}
|
|
30
|
+
if (!standalone)
|
|
31
|
+
return;
|
|
32
|
+
switch (event.type) {
|
|
33
|
+
case 'text':
|
|
34
|
+
if (typeof event.delta === 'string')
|
|
35
|
+
chunks.push(stream.append(event.delta));
|
|
36
|
+
return;
|
|
37
|
+
case 'plugin_progress':
|
|
38
|
+
case 'warning':
|
|
39
|
+
return;
|
|
40
|
+
case 'turn_done': {
|
|
41
|
+
standalone = false;
|
|
42
|
+
const content = chunks.join('') + stream.finish();
|
|
43
|
+
if (!content.trim() || event.completionStatus === 'no_answer')
|
|
44
|
+
return;
|
|
45
|
+
return result(content);
|
|
46
|
+
}
|
|
47
|
+
default:
|
|
48
|
+
standalone = false;
|
|
49
|
+
chunks.length = 0;
|
|
50
|
+
stream.reset();
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
/** Display projection shared by hosts. Never mutate the model's actual input. */
|
|
55
|
+
export function transcriptRows(history) {
|
|
56
|
+
const ids = new Set();
|
|
57
|
+
const users = new Map();
|
|
58
|
+
for (const m of history) {
|
|
59
|
+
if (m.role === 'user' && m.id)
|
|
60
|
+
users.set(m.id, m);
|
|
61
|
+
if (m.role === 'system' && m._ephemeral && m.commandDisplay?.kind === 'request')
|
|
62
|
+
ids.add(m.commandDisplay.userMessageId);
|
|
63
|
+
}
|
|
64
|
+
if (!ids.size)
|
|
65
|
+
return history;
|
|
66
|
+
return history.flatMap((m) => {
|
|
67
|
+
if (m.role === 'user' && m.id && ids.has(m.id))
|
|
68
|
+
return [];
|
|
69
|
+
if (m.role === 'system' && m._ephemeral && m.commandDisplay?.kind === 'request') {
|
|
70
|
+
const requestId = m.commandDisplay.userMessageId;
|
|
71
|
+
const original = users.get(requestId);
|
|
72
|
+
return [{ ...original, role: 'user', content: m.content, timestamp: m.timestamp, id: requestId }];
|
|
73
|
+
}
|
|
74
|
+
return [m];
|
|
75
|
+
});
|
|
76
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import type { PluginEvent } from '../plugins/pluginApi.js';
|
|
2
|
+
import type { LoopEvent, Message } from '../types.js';
|
|
3
|
+
import { createPublicTextStream } from '../ui/publicText.js';
|
|
4
|
+
|
|
5
|
+
type LocalRow = Extract<Message, { role: 'system' }>;
|
|
6
|
+
|
|
7
|
+
/** A slash command can expand into a different model input, or never call the
|
|
8
|
+
* model at all. Keep the UI transcript independent of that routing decision. */
|
|
9
|
+
export function commandRequest(input: string, userMessageId: string): LocalRow {
|
|
10
|
+
return { role: 'system', _ephemeral: true, _uiProgress: true,
|
|
11
|
+
id: `command:${userMessageId}`, timestamp: Date.now(), content: input,
|
|
12
|
+
commandDisplay: { kind: 'request', userMessageId } };
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Some deterministic plugins emit only text + turn_done. Model turns and
|
|
16
|
+
* workflows own their own drafts, echoes, and committed history. Never promote
|
|
17
|
+
* their preview (including a replayed echo) into a second or invented answer. */
|
|
18
|
+
export function captureCommandReply(userMessageId: string) {
|
|
19
|
+
const stream = createPublicTextStream();
|
|
20
|
+
const chunks: string[] = [];
|
|
21
|
+
let standalone = true;
|
|
22
|
+
let resultNumber = 0;
|
|
23
|
+
const result = (content: string): LocalRow => ({
|
|
24
|
+
role: 'system', _ephemeral: true, _uiProgress: true,
|
|
25
|
+
id: `command:${userMessageId}:result:${++resultNumber}`, timestamp: Date.now(), content,
|
|
26
|
+
commandDisplay: { kind: 'result' },
|
|
27
|
+
});
|
|
28
|
+
return (event: LoopEvent | PluginEvent): LocalRow | undefined => {
|
|
29
|
+
if (event.type === 'text' && event.commandResult === true && typeof event.delta === 'string') {
|
|
30
|
+
standalone = false;
|
|
31
|
+
chunks.length = 0;
|
|
32
|
+
stream.reset();
|
|
33
|
+
const content = stream.append(event.delta) + stream.finish();
|
|
34
|
+
return content.trim() ? result(content) : undefined;
|
|
35
|
+
}
|
|
36
|
+
if (!standalone) return;
|
|
37
|
+
switch (event.type) {
|
|
38
|
+
case 'text':
|
|
39
|
+
if (typeof event.delta === 'string') chunks.push(stream.append(event.delta));
|
|
40
|
+
return;
|
|
41
|
+
case 'plugin_progress':
|
|
42
|
+
case 'warning':
|
|
43
|
+
return;
|
|
44
|
+
case 'turn_done': {
|
|
45
|
+
standalone = false;
|
|
46
|
+
const content = chunks.join('') + stream.finish();
|
|
47
|
+
if (!content.trim() || event.completionStatus === 'no_answer') return;
|
|
48
|
+
return result(content);
|
|
49
|
+
}
|
|
50
|
+
default:
|
|
51
|
+
standalone = false;
|
|
52
|
+
chunks.length = 0;
|
|
53
|
+
stream.reset();
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Display projection shared by hosts. Never mutate the model's actual input. */
|
|
59
|
+
export function transcriptRows(history: Message[]): Message[] {
|
|
60
|
+
const ids = new Set<string>();
|
|
61
|
+
const users = new Map<string, Extract<Message, { role: 'user' }>>();
|
|
62
|
+
for (const m of history) {
|
|
63
|
+
if (m.role === 'user' && m.id) users.set(m.id, m);
|
|
64
|
+
if (m.role === 'system' && m._ephemeral && m.commandDisplay?.kind === 'request')
|
|
65
|
+
ids.add(m.commandDisplay.userMessageId);
|
|
66
|
+
}
|
|
67
|
+
if (!ids.size) return history;
|
|
68
|
+
return history.flatMap((m): Message[] => {
|
|
69
|
+
if (m.role === 'user' && m.id && ids.has(m.id)) return [];
|
|
70
|
+
if (m.role === 'system' && m._ephemeral && m.commandDisplay?.kind === 'request') {
|
|
71
|
+
const requestId = m.commandDisplay.userMessageId;
|
|
72
|
+
const original = users.get(requestId);
|
|
73
|
+
return [{ ...original, role: 'user', content: m.content, timestamp: m.timestamp, id: requestId }];
|
|
74
|
+
}
|
|
75
|
+
return [m];
|
|
76
|
+
});
|
|
77
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/** A successful transport is not proof of completed work. Shared by scheduled hosts. */
|
|
2
|
+
export function executionOutcome(events) {
|
|
3
|
+
const done = [...events]
|
|
4
|
+
.reverse()
|
|
5
|
+
.find((event) => event.type === 'turn_done');
|
|
6
|
+
const completionStatus = typeof done?.completionStatus === 'string'
|
|
7
|
+
? done.completionStatus
|
|
8
|
+
: undefined;
|
|
9
|
+
const managedStatus = typeof done?.managedStatus === 'string' ? done.managedStatus : undefined;
|
|
10
|
+
const pending = ['pendingRequired', 'pendingBackground'].some((key) => Array.isArray(done?.[key]) && done[key].length > 0);
|
|
11
|
+
const interrupted = events.some((event) => event.type === 'interrupted');
|
|
12
|
+
const incomplete = !done || interrupted ||
|
|
13
|
+
pending ||
|
|
14
|
+
(completionStatus !== undefined && completionStatus !== 'completed') ||
|
|
15
|
+
['blocked', 'failed', 'paused', 'ready_for_acceptance'].includes(managedStatus ?? '');
|
|
16
|
+
return {
|
|
17
|
+
completionStatus,
|
|
18
|
+
managedStatus,
|
|
19
|
+
...(incomplete
|
|
20
|
+
? {
|
|
21
|
+
error: `执行尚未完成或需要处理:${interrupted ? 'interrupted' : !done ? '缺少回合完成回执' : pending ? '仍有未收口任务' : (managedStatus ?? completionStatus)}`,
|
|
22
|
+
}
|
|
23
|
+
: {}),
|
|
24
|
+
};
|
|
25
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/** A successful transport is not proof of completed work. Shared by scheduled hosts. */
|
|
2
|
+
export function executionOutcome(
|
|
3
|
+
events: ReadonlyArray<{ type: string; [key: string]: unknown }>,
|
|
4
|
+
) {
|
|
5
|
+
const done = [...events]
|
|
6
|
+
.reverse()
|
|
7
|
+
.find((event) => event.type === 'turn_done');
|
|
8
|
+
const completionStatus =
|
|
9
|
+
typeof done?.completionStatus === 'string'
|
|
10
|
+
? done.completionStatus
|
|
11
|
+
: undefined;
|
|
12
|
+
const managedStatus =
|
|
13
|
+
typeof done?.managedStatus === 'string' ? done.managedStatus : undefined;
|
|
14
|
+
const pending = ['pendingRequired', 'pendingBackground'].some(
|
|
15
|
+
(key) => Array.isArray(done?.[key]) && (done![key] as unknown[]).length > 0,
|
|
16
|
+
);
|
|
17
|
+
const interrupted = events.some((event) => event.type === 'interrupted');
|
|
18
|
+
const incomplete =
|
|
19
|
+
!done || interrupted ||
|
|
20
|
+
pending ||
|
|
21
|
+
(completionStatus !== undefined && completionStatus !== 'completed') ||
|
|
22
|
+
['blocked', 'failed', 'paused', 'ready_for_acceptance'].includes(
|
|
23
|
+
managedStatus ?? '',
|
|
24
|
+
);
|
|
25
|
+
return {
|
|
26
|
+
completionStatus,
|
|
27
|
+
managedStatus,
|
|
28
|
+
...(incomplete
|
|
29
|
+
? {
|
|
30
|
+
error: `执行尚未完成或需要处理:${interrupted ? 'interrupted' : !done ? '缺少回合完成回执' : pending ? '仍有未收口任务' : (managedStatus ?? completionStatus)}`,
|
|
31
|
+
}
|
|
32
|
+
: {}),
|
|
33
|
+
};
|
|
34
|
+
}
|
|
@@ -15,6 +15,8 @@ import { ALL_TOOLS } from '../tools/index.js';
|
|
|
15
15
|
import { hydrateSessionWorktree } from '../tools/worktree/sessionWorktree.js';
|
|
16
16
|
import { createLocalBrowserScope } from '../cli/browser.js';
|
|
17
17
|
import { runTurn } from './runTurn.js';
|
|
18
|
+
import { executionOutcome } from './executionOutcome.js';
|
|
19
|
+
import { backgroundCompletionFields } from '../runtime/backgroundCompletion.js';
|
|
18
20
|
import { getOrCreateSessionState, sessionStateKey, } from './sessionState.js';
|
|
19
21
|
export async function runAgentTurn(opts,
|
|
20
22
|
// DI 缝(仿 agent.ts 的 deps 先例):compact_failed 无法经 chat DI 触发
|
|
@@ -189,7 +191,9 @@ deps = {}) {
|
|
|
189
191
|
memoryContext: memoryContextFromRuntime(runtimeContext),
|
|
190
192
|
})) {
|
|
191
193
|
if (isEventLike(ev)) {
|
|
192
|
-
events.push(ev
|
|
194
|
+
events.push(ev.type === 'turn_done'
|
|
195
|
+
? { ...ev, ...backgroundCompletionFields(turnSessionState.backgroundTasks) }
|
|
196
|
+
: ev);
|
|
193
197
|
if (ev.type === 'text')
|
|
194
198
|
result += ev.delta;
|
|
195
199
|
if (ev.type === 'assistant_draft_discarded' && ev.textLength > 0)
|
|
@@ -208,7 +212,10 @@ deps = {}) {
|
|
|
208
212
|
if (!opts.browserScope)
|
|
209
213
|
await browserScope.dispose();
|
|
210
214
|
}
|
|
215
|
+
const outcome = executionOutcome(events);
|
|
216
|
+
error ??= outcome.error;
|
|
211
217
|
return {
|
|
218
|
+
...outcome,
|
|
212
219
|
ok: !error,
|
|
213
220
|
result,
|
|
214
221
|
...(error ? { error } : {}),
|
|
@@ -26,6 +26,8 @@ import { hydrateSessionWorktree } from '../tools/worktree/sessionWorktree.js';
|
|
|
26
26
|
import type { LoopEvent, Provider, ToolCallContext } from '../types.js';
|
|
27
27
|
import { createLocalBrowserScope, type BrowserCliMode } from '../cli/browser.js';
|
|
28
28
|
import { runTurn } from './runTurn.js';
|
|
29
|
+
import { executionOutcome } from './executionOutcome.js';
|
|
30
|
+
import { backgroundCompletionFields } from '../runtime/backgroundCompletion.js';
|
|
29
31
|
import {
|
|
30
32
|
type SessionState,
|
|
31
33
|
getOrCreateSessionState,
|
|
@@ -54,6 +56,8 @@ export interface RunAgentTurnOptions {
|
|
|
54
56
|
}
|
|
55
57
|
|
|
56
58
|
export interface RunAgentTurnResult {
|
|
59
|
+
completionStatus?: string;
|
|
60
|
+
managedStatus?: string;
|
|
57
61
|
ok: boolean;
|
|
58
62
|
result: string;
|
|
59
63
|
error?: string;
|
|
@@ -261,7 +265,9 @@ export async function runAgentTurn(
|
|
|
261
265
|
memoryContext: memoryContextFromRuntime(runtimeContext),
|
|
262
266
|
})) {
|
|
263
267
|
if (isEventLike(ev)) {
|
|
264
|
-
events.push(ev
|
|
268
|
+
events.push(ev.type === 'turn_done'
|
|
269
|
+
? { ...ev, ...backgroundCompletionFields(turnSessionState.backgroundTasks) }
|
|
270
|
+
: ev);
|
|
265
271
|
if (ev.type === 'text') result += ev.delta;
|
|
266
272
|
if (ev.type === 'assistant_draft_discarded' && ev.textLength > 0)
|
|
267
273
|
result = result.slice(0, Math.max(0, result.length - ev.textLength));
|
|
@@ -278,7 +284,10 @@ export async function runAgentTurn(
|
|
|
278
284
|
if (!opts.browserScope) await browserScope.dispose();
|
|
279
285
|
}
|
|
280
286
|
|
|
287
|
+
const outcome = executionOutcome(events);
|
|
288
|
+
error ??= outcome.error;
|
|
281
289
|
return {
|
|
290
|
+
...outcome,
|
|
282
291
|
ok: !error,
|
|
283
292
|
result,
|
|
284
293
|
...(error ? { error } : {}),
|
package/src/session/runTurn.js
CHANGED
|
@@ -24,6 +24,7 @@ import { loadContext, saveContext } from '../context/persistContext.js';
|
|
|
24
24
|
import { startTurnJournal } from '../memory/turnJournal.js';
|
|
25
25
|
import { createLearningModel } from '../memory/learningModel.js';
|
|
26
26
|
import { runWithPlugins } from '../plugins/pluginRunner.js';
|
|
27
|
+
import { captureCommandReply, commandRequest } from './commandTranscript.js';
|
|
27
28
|
import { upsertStableSystemMessage } from '../prompts/stableSystemPrompt.js';
|
|
28
29
|
/**
|
|
29
30
|
* 已有历史时,用调用方新算好的 systemPrompt(含当前日期/实时扫描的 skills·plugins 清单/
|
|
@@ -52,8 +53,24 @@ function buildInitialHistory(loaded, systemPrompt) {
|
|
|
52
53
|
export async function* runTurn(opts) {
|
|
53
54
|
const persist = opts.persist !== false;
|
|
54
55
|
const release = persist ? await acquireContextLock(opts.sessionFile, opts.signal) : async () => { };
|
|
56
|
+
try {
|
|
57
|
+
yield* runLockedTurn(opts, persist);
|
|
58
|
+
}
|
|
59
|
+
finally {
|
|
60
|
+
try {
|
|
61
|
+
await opts.cleanup?.();
|
|
62
|
+
}
|
|
63
|
+
finally {
|
|
64
|
+
await release();
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/** Initialization is also inside the lock lifetime; failures must not strand it. */
|
|
69
|
+
async function* runLockedTurn(opts, persist) {
|
|
55
70
|
const loaded = opts.initialHistory ?? (persist ? await loadContext(opts.sessionFile) : null);
|
|
56
71
|
const history = buildInitialHistory(loaded, opts.systemPrompt);
|
|
72
|
+
if (opts.prepare)
|
|
73
|
+
opts = { ...opts, ...await opts.prepare(history) };
|
|
57
74
|
const historyStart = history.length;
|
|
58
75
|
const userMessageId = opts.userMessageId ?? crypto.randomUUID();
|
|
59
76
|
// 会话原文记账:实现在 src/memory/turnJournal.ts(TUI 的 useChat 用同一份),
|
|
@@ -74,6 +91,14 @@ export async function* runTurn(opts) {
|
|
|
74
91
|
const trace = createLifecycleTrace('host');
|
|
75
92
|
let hostFailed = false;
|
|
76
93
|
try {
|
|
94
|
+
const commandReply = opts.userInput.trim().startsWith('/') ? captureCommandReply(userMessageId) : null;
|
|
95
|
+
if (commandReply) {
|
|
96
|
+
const request = commandRequest(opts.userInput, userMessageId);
|
|
97
|
+
history.push(request);
|
|
98
|
+
if (persist)
|
|
99
|
+
await saveContext(history, opts.sessionFile, { strict: opts.strictPersistence });
|
|
100
|
+
yield { type: 'injected_message', message: request };
|
|
101
|
+
}
|
|
77
102
|
for await (const event of runWithPlugins(opts.userInput, {
|
|
78
103
|
executionId: opts.executionId,
|
|
79
104
|
provider: opts.provider,
|
|
@@ -107,13 +132,18 @@ export async function* runTurn(opts) {
|
|
|
107
132
|
memoryContext: opts.memoryContext,
|
|
108
133
|
})) {
|
|
109
134
|
journal?.observe(event);
|
|
135
|
+
const commandResult = commandReply?.(event);
|
|
136
|
+
if (commandResult) {
|
|
137
|
+
history.push(commandResult);
|
|
138
|
+
yield { type: 'injected_message', message: commandResult };
|
|
139
|
+
}
|
|
110
140
|
// Stage records are user-visible history, not model instructions. Checkpoint
|
|
111
141
|
// at stage boundaries so a Runtime restart does not lose the whole workflow.
|
|
112
142
|
if (persist && (['user_message_committed', 'assistant_message', 'compact_start', 'turn_done'].includes(event.type)
|
|
113
143
|
|| (event.type === 'injected_message' && event.message && typeof event.message === 'object' && 'role' in event.message && event.message.role === 'system' && '_uiProgress' in event.message && event.message._uiProgress === true))) {
|
|
114
144
|
trace('save_start');
|
|
115
145
|
try {
|
|
116
|
-
await saveContext(history, opts.sessionFile);
|
|
146
|
+
await saveContext(history, opts.sessionFile, { strict: opts.strictPersistence });
|
|
117
147
|
trace('save_end');
|
|
118
148
|
}
|
|
119
149
|
catch (error) {
|
|
@@ -135,19 +165,14 @@ export async function* runTurn(opts) {
|
|
|
135
165
|
throw error;
|
|
136
166
|
}
|
|
137
167
|
finally {
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
await saveContext(history, opts.sessionFile);
|
|
148
|
-
}
|
|
149
|
-
finally {
|
|
150
|
-
await release();
|
|
151
|
-
}
|
|
168
|
+
if (!completedNormally && !hostFailed)
|
|
169
|
+
journal?.observe({ type: 'interrupted' });
|
|
170
|
+
trace('memory_start');
|
|
171
|
+
await journal?.finish(history, historyStart).catch(error => {
|
|
172
|
+
process.stderr.write(`[minimal-agent memory] 本轮记忆收尾失败,不影响会话落盘:${error.message}\n`);
|
|
173
|
+
});
|
|
174
|
+
trace('memory_end');
|
|
175
|
+
if (persist)
|
|
176
|
+
await saveContext(history, opts.sessionFile, { strict: opts.strictPersistence });
|
|
152
177
|
}
|
|
153
178
|
}
|