@hugesb/dsh-stream-agent 0.0.0-stage → 0.3.2
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/CHANGELOG.md +622 -0
- package/CONTRIBUTING.md +72 -0
- package/LICENSE +202 -0
- package/README.en.md +349 -0
- package/README.md +300 -3
- package/cordis.patch.yml +77 -0
- package/dist/entry/action-gate.js +206 -0
- package/dist/entry/adapter-kit.js +192 -0
- package/dist/entry/context-render.js +119 -0
- package/dist/entry/control-bar-cli.js +289 -0
- package/dist/entry/control-bar.js +123 -0
- package/dist/entry/control-session.js +115 -0
- package/dist/entry/control-state.js +125 -0
- package/dist/entry/cordis-compat.js +95 -0
- package/dist/entry/eval-probe.js +112 -0
- package/dist/entry/intent-log.js +121 -0
- package/dist/entry/json-persistence.js +306 -0
- package/dist/entry/loop.js +4163 -0
- package/dist/entry/mock-provider.js +549 -0
- package/dist/entry/obs-broker.js +178 -0
- package/dist/entry/ptc-bridge.js +405 -0
- package/dist/entry/state-handle.js +217 -0
- package/dist/entry/takeover-registry.js +60 -0
- package/dist/kernel/control-bar.js +559 -0
- package/dist/kernel/final.js +62 -0
- package/dist/kernel/gate.js +464 -0
- package/dist/kernel/modes.js +253 -0
- package/dist/kernel/obs.js +517 -0
- package/dist/kernel/parser.js +1081 -0
- package/dist/kernel/render.js +466 -0
- package/dist/kernel/state.js +416 -0
- package/dist/version.js +9 -0
- package/docs/TEST-PROPOSITIONS.md +139 -0
- package/docs/adr-001-segment-boundary.md +61 -0
- package/docs/architecture.md +104 -0
- package/docs/desktop-ui-feasibility.md +277 -0
- package/docs/disabled-lines-audit.md +53 -0
- package/docs/limitations.md +181 -0
- package/docs/protocol.md +99 -0
- package/docs/v0.4.0-plan.md +50 -0
- package/eval/METRICS.md +128 -0
- package/eval/RESULTS.md +246 -0
- package/eval/tasks/fixtures/big-report.md +298 -0
- package/eval/tasks/fixtures/build-manifest.txt +5 -0
- package/eval/tasks/fixtures/deploy.yaml +4 -0
- package/eval/tasks/fixtures/error.log +200 -0
- package/eval/tasks/fixtures/features.yaml +4 -0
- package/eval/tasks/fixtures/pipeline.yaml +4 -0
- package/eval/tasks/fixtures/sales-q1.csv +61 -0
- package/eval/tasks/fixtures/settings.yaml +4 -0
- package/eval/tasks/fixtures/users-roster.json +304 -0
- package/eval/tasks/fixtures/users-scores.json +20 -0
- package/eval/tasks/gen-fixtures.cjs +80 -0
- package/eval/tasks/tasks.json +150 -0
- package/eval/tools/f6-kill-drill.cjs +176 -0
- package/eval/tools/f6-kill-drill.worker.cjs +131 -0
- package/eval/tools/gen-results.cjs +191 -0
- package/eval/tools/machine-test.cjs +200 -0
- package/eval/tools/manual-code-scenarios.md +59 -0
- package/eval/tools/replay-check.cjs +311 -0
- package/eval/tools/runner.cjs +219 -0
- package/eval/tools/session-log.cjs +106 -0
- package/eval/tools/summarize.cjs +185 -0
- package/eval/tools/t3-cells.cjs +173 -0
- package/package.json +73 -6
- package/patches/adapters-smoke.yml +41 -0
- package/patches/eval-account.yml +36 -0
- package/patches/eval-baseline.yml +33 -0
- package/patches/eval-stream-code-off.yml +46 -0
- package/patches/eval-stream-code-on.yml +47 -0
- package/patches/eval-stream.yml +54 -0
- package/patches/takeover.yml +42 -0
- package/patches/test-preset.yml +23 -0
- package/preset/stream/cordis.patch.yml +39 -0
- package/preset/stream/package.json +13 -0
- package/preset.yml +56 -0
- package/profiles/stream/README.md +66 -0
- package/profiles/stream/cordis.patch.yml +12 -0
- package/profiles/stream/package.json +17 -0
- package/profiles/stream-headless/package.json +16 -0
- package/scripts/build.mjs +103 -0
- package/scripts/check-consistency.mjs +146 -0
- package/scripts/gate.mjs +138 -0
- package/scripts/install-check.mjs +116 -0
- package/scripts/install-cycle.mjs +88 -0
- package/scripts/release.mjs +428 -0
- package/scripts/repair-session-logs.mjs +498 -0
- package/src/entry/action-gate.ts +206 -0
- package/src/entry/adapter-kit.ts +192 -0
- package/src/entry/context-render.ts +119 -0
- package/src/entry/control-bar-cli.ts +289 -0
- package/src/entry/control-bar.ts +123 -0
- package/src/entry/control-session.ts +115 -0
- package/src/entry/control-state.ts +125 -0
- package/src/entry/cordis-compat.ts +95 -0
- package/src/entry/eval-probe.ts +112 -0
- package/src/entry/intent-log.ts +121 -0
- package/src/entry/json-persistence.ts +306 -0
- package/src/entry/loop.ts +4163 -0
- package/src/entry/mock-provider.ts +549 -0
- package/src/entry/obs-broker.ts +178 -0
- package/src/entry/ptc-bridge.ts +405 -0
- package/src/entry/state-handle.ts +217 -0
- package/src/entry/takeover-registry.ts +60 -0
- package/src/kernel/control-bar.ts +559 -0
- package/src/kernel/final.ts +62 -0
- package/src/kernel/gate.ts +464 -0
- package/src/kernel/modes.ts +253 -0
- package/src/kernel/obs.ts +517 -0
- package/src/kernel/parser.ts +1081 -0
- package/src/kernel/render.ts +466 -0
- package/src/kernel/state.ts +416 -0
- package/src/version.ts +9 -0
- package/test/activation.test.ts +187 -0
- package/test/adapters.test.ts +676 -0
- package/test/control-bar.test.ts +486 -0
- package/test/desktop-ui.test.ts +359 -0
- package/test/eval-probe.test.ts +139 -0
- package/test/f5-plan.test.ts +221 -0
- package/test/f6-intent.test.ts +168 -0
- package/test/f7-segment.test.ts +190 -0
- package/test/fix-limits.test.ts +599 -0
- package/test/gate.test.ts +380 -0
- package/test/helpers/stub-loop.ts +240 -0
- package/test/host-conformance.test.ts +418 -0
- package/test/kernel/obs.test.ts +329 -0
- package/test/kernel/parser.test.ts +451 -0
- package/test/loop.test.ts +1393 -0
- package/test/mock-provider.test.ts +386 -0
- package/test/ptc-bridge.test.ts +356 -0
- package/test/render.test.ts +418 -0
- package/test/s2-install-check.test.ts +46 -0
- package/test/scenarios/3-file-basic.json +13 -0
- package/test/scenarios/5-file-basic.json +22 -0
- package/test/scenarios/burn-more.json +9 -0
- package/test/scenarios/degraded-final.json +10 -0
- package/test/scenarios/fault-abort-xml.json +11 -0
- package/test/scenarios/fault-malformed-command.json +12 -0
- package/test/scenarios/fault-midstream-abort.json +11 -0
- package/test/scenarios/fault-saturating-output.json +9 -0
- package/test/scenarios/fault-timeout.json +9 -0
- package/test/scenarios/peek-first.json +11 -0
- package/test/scenarios/peek-second.json +11 -0
- package/test/scenarios/peek-third.json +10 -0
- package/test/scenarios/recover-final.json +10 -0
- package/test/scenarios/reroute-first.json +17 -0
- package/test/scenarios/reroute-second.json +16 -0
- package/test/scenarios/starvation-final.json +10 -0
- package/test/scenarios/starvation-promote.json +11 -0
- package/test/scenarios/wait-tools-continue.json +10 -0
- package/test/scenarios/wait-tools-xml.json +22 -0
- package/test/scenarios/wait-tools.json +15 -0
- package/test/session-format.test.ts +234 -0
- package/test/state.test.ts +335 -0
- package/test/stream-v02.test.ts +264 -0
- package/test/v031-display.test.ts +333 -0
- package/test/v032-conflict.test.ts +191 -0
- package/test/v032-truncation.test.ts +291 -0
- package/ui/client.js +576 -0
- package/ui/index.js +282 -0
- package/ui/package.json +26 -0
|
@@ -0,0 +1,4163 @@
|
|
|
1
|
+
// entry/loop.ts —— 单流协议驱动器(分派 06,全项目核心命题:改地基)
|
|
2
|
+
//
|
|
3
|
+
// 本文件三层结构,边界即红线:
|
|
4
|
+
// ① 流契约镜像 —— dsh-llm 流词汇的本地镜像(零 @deepseek-ai 静态 import,file:line 见注释)。
|
|
5
|
+
// 本地插件 bare import 不走宿主解析(results/01-micro-spike-results.md §0 实测),
|
|
6
|
+
// 因此适配层对上游一切依赖都是 duck-typed 注入,类型只做镜像。
|
|
7
|
+
// ② SingleStreamDriver —— 单流协议驱动器(纯异步控制流,零宿主依赖)。
|
|
8
|
+
// 状态机:REQUEST → STREAMING(parser 事件循环,命令闭合即 gate.admit 派发)
|
|
9
|
+
// → 流终止 → 等 drain(F8 普通异步等待)→ 收束判定 → FINISH 或 INJECTING。
|
|
10
|
+
// 重入条件仅三种:info_gain=high 观测 / need_result(tf-peek)/ 执行失败。
|
|
11
|
+
// 成功路径零注入,只写 ledger。
|
|
12
|
+
// ③ StreamLoopAgent + createStreamAgentFactory + apply —— Cordis 适配壳。
|
|
13
|
+
// createAgent/resume 按 dsh-agent-loop/lib/index.js:1668-1775(rc.3 实测行号,
|
|
14
|
+
// rc.1 npm 副本一致)的机器 duck-type 复刻:sessions.prepare → persistence →
|
|
15
|
+
// sessions.enter/announce → setup → agents.enter/announce。
|
|
16
|
+
// AgentRegistry.enter/announce 无 brand 校验(dsh-agent/lib/index.js:641-719,
|
|
17
|
+
// 只查 agent.id === agent.session.id 与 store 唯一性),duck-typed agent 对象可通行。
|
|
18
|
+
//
|
|
19
|
+
// 业务逻辑全部在内核(parser/gate/render/obs/state),本文件只做编排(红线:插件里不写业务逻辑)。
|
|
20
|
+
//
|
|
21
|
+
// fail-open(红线 5):驱动器自身异常 → 结构化 fault 记录 + 重新抛出清晰错误,绝不静默吞掉。
|
|
22
|
+
// 唯一例外是"账本/事件落盘失败":内存 records 永远持有全量事实,onWarning 告警后继续
|
|
23
|
+
// (不因记账毁掉任务本身,但绝不无声)。
|
|
24
|
+
|
|
25
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
26
|
+
import { writeFileSync } from 'node:fs';
|
|
27
|
+
import { join } from 'node:path';
|
|
28
|
+
import { TfStreamParser, splitEditBody } from '../kernel/parser.js';
|
|
29
|
+
|
|
30
|
+
import { ContextRenderer, renderHash } from '../kernel/render.js';
|
|
31
|
+
|
|
32
|
+
import { ObservationLedger } from '../kernel/obs.js';
|
|
33
|
+
|
|
34
|
+
import { checkFinalSummary } from '../kernel/final.js';
|
|
35
|
+
import {
|
|
36
|
+
appendLedgerRecord,
|
|
37
|
+
createJsonlPersistence,
|
|
38
|
+
ledgerFileOf,
|
|
39
|
+
loadLedgerRecords,
|
|
40
|
+
resolveStateDir,
|
|
41
|
+
withEventCapture,
|
|
42
|
+
} from './json-persistence.js';
|
|
43
|
+
|
|
44
|
+
import { createCodeExecutor, DEFAULT_CODE_QUOTA, looksLikePtcRuntime } from './ptc-bridge.js';
|
|
45
|
+
|
|
46
|
+
import { asPluginEffect, getService } from './cordis-compat.js';
|
|
47
|
+
import { readPersistedControl, resolveControlState, writePersistedControl } from './control-state.js';
|
|
48
|
+
|
|
49
|
+
import { appendIntentRecord, intentFileOf, loadIntentRecords, pendingIntents } from './intent-log.js';
|
|
50
|
+
import { clearTakeover, markTakeover } from './takeover-registry.js';
|
|
51
|
+
import { isModeId, modeConfig, publicModeCatalog } from '../kernel/modes.js';
|
|
52
|
+
import { isLang } from '../kernel/control-bar.js';
|
|
53
|
+
import { VERSION } from '../version.js';
|
|
54
|
+
|
|
55
|
+
// ---------------------------------------------------------------------------
|
|
56
|
+
// ① 流契约镜像(dsh-llm/lib/types/types.d.ts 与 dsh-tools/lib/types/executor.d.ts,rc.1 npm)
|
|
57
|
+
// ---------------------------------------------------------------------------
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* 镜像 types.d.ts:138-156 FinishReasonMap。
|
|
61
|
+
* 真实宿主的 error finish 把失败事实放在 `failure`(rc.3 实测:
|
|
62
|
+
* {kind:'error', failure:{message, code}});mock 05 号用的是平铺 {message, code}。
|
|
63
|
+
* 两种形状都接受,读取统一走 finishCode/finishMessage。
|
|
64
|
+
*/
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
/** error finish 的机器码(宿主形状 failure.code 优先,mock 平铺形状 code 兜底)。 */
|
|
78
|
+
export function finishCode(finish ) {
|
|
79
|
+
if (finish.kind !== 'error') return finish.kind;
|
|
80
|
+
return finish.failure?.code ?? finish.code ?? 'UNKNOWN';
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** error/aborted finish 的可读消息。 */
|
|
84
|
+
export function finishMessage(finish ) {
|
|
85
|
+
if (finish.kind === 'error') return finish.failure?.message ?? finish.message ?? 'error';
|
|
86
|
+
if (finish.kind === 'aborted') return finish.message ?? 'aborted';
|
|
87
|
+
return finish.kind;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** 镜像 types.d.ts:458-488 StreamChunk(本驱动消费的全部变体) */
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
/** 镜像 types.d.ts:538-580 GenerateOptions(驱动器发出的请求形状)。
|
|
101
|
+
* v0.3.2:assistant 消息的 messages 项带可选 source(宿主 forAdapter 读
|
|
102
|
+
* `message.source.replayState`,缺失即 TypeError → 流 error → 回合中断;
|
|
103
|
+
* 类型镜像 dsh-llm typert.host.js AssistantProviderMetadata)。 */
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
/** 镜像 executor.d.ts:16-45 ToolBatchInput(probe B 实测形状;单命令批 = calls 长度 1) */
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
/** 镜像 executor.d.ts:47-56 ToolBatchResult(probe B 实测返回结构) */
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
// ---------------------------------------------------------------------------
|
|
137
|
+
// 驱动器配置与端口
|
|
138
|
+
// ---------------------------------------------------------------------------
|
|
139
|
+
|
|
140
|
+
/** tf-* 命令 → 原生工具的映射(信息型 read/bash 走原生阻塞通道,写类走单流通道) */
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
export const DEFAULT_TOOL_MAPPING = {
|
|
147
|
+
toToolCall(cmd) {
|
|
148
|
+
// 原生工具 schema:write(file_path, content)、read(file_path, ...)(dsh-tool-fs/lib/index.js:249-560)、
|
|
149
|
+
// edit(file_path, old_string, new_string, replace_all?)(dsh-tool-fs/lib/index.js,0.3.0 F1 映射)、
|
|
150
|
+
// apply_patch(input)(同上,*** End of File 锚实现 EOF 追加)、
|
|
151
|
+
// grep(pattern, path?, include?) / glob(pattern, path?)(dsh-tool-fs-search/lib/index.js,F2 映射)、
|
|
152
|
+
// bash(command)(dsh-tool-bash/lib/index.js:493)。参数名以真连实测为准(results 文档记录)。
|
|
153
|
+
switch (cmd.name) {
|
|
154
|
+
case 'tf-write':
|
|
155
|
+
return { name: 'write', arguments: { file_path: cmd.attrs['path'] ?? '', content: cmd.body ?? '' } };
|
|
156
|
+
case 'tf-read': {
|
|
157
|
+
// 行范围透传(上游 read-ranges 语义):1 基 offset 与行数 limit,宿主 read 原生支持
|
|
158
|
+
const offset = cmd.attrs['offset'];
|
|
159
|
+
const limit = cmd.attrs['limit'];
|
|
160
|
+
const args = { file_path: cmd.attrs['path'] ?? '' };
|
|
161
|
+
if (offset !== undefined && /^\d+$/.test(offset)) args['offset'] = Number(offset);
|
|
162
|
+
if (limit !== undefined && /^\d+$/.test(limit)) args['limit'] = Number(limit);
|
|
163
|
+
return { name: 'read', arguments: args };
|
|
164
|
+
}
|
|
165
|
+
case 'tf-edit': {
|
|
166
|
+
// F1:精确替换映射宿主 edit(old → new;replace_all=false 时宿主要求恰好出现一次)。
|
|
167
|
+
// body 用 OLD/NEW 标记行分隔两段字面量;解析失败回结构化失败,绝不静默改成全文重写。
|
|
168
|
+
const split = splitEditBody(cmd.body ?? '');
|
|
169
|
+
if (split === null) return null;
|
|
170
|
+
const args = {
|
|
171
|
+
file_path: cmd.attrs['path'] ?? '',
|
|
172
|
+
old_string: split.old,
|
|
173
|
+
new_string: split.new,
|
|
174
|
+
};
|
|
175
|
+
if (cmd.attrs['replace_all'] === 'true') args['replace_all'] = true;
|
|
176
|
+
return { name: 'edit', arguments: args };
|
|
177
|
+
}
|
|
178
|
+
case 'tf-append': {
|
|
179
|
+
// F1:只追加,不修改既有内容。
|
|
180
|
+
// - anchor 属性给定时:映射宿主 edit,在唯一锚点字面量之后插入(锚点行末补一个换行;
|
|
181
|
+
// 换行规则确定:new_string = anchor + '\n' + body)。
|
|
182
|
+
// - 无 anchor:EOF 追加映射宿主 apply_patch 的 `*** End of File` 锚(宿主原生支持,
|
|
183
|
+
// 不自建文件 IO);正文逐行加 '+' 前缀成补丁。
|
|
184
|
+
const body = cmd.body ?? '';
|
|
185
|
+
if (body === '') return null;
|
|
186
|
+
const anchor = cmd.attrs['anchor'];
|
|
187
|
+
if (anchor !== undefined && anchor !== '') {
|
|
188
|
+
return {
|
|
189
|
+
name: 'edit',
|
|
190
|
+
arguments: { file_path: cmd.attrs['path'] ?? '', old_string: anchor, new_string: `${anchor}\n${body}` },
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
const lines = body.split('\n');
|
|
194
|
+
if (lines.length > 1 && lines[lines.length - 1] === '') lines.pop(); // 末尾换行不产生空补丁行
|
|
195
|
+
const patch = ['*** Begin Patch', `*** Update File: ${cmd.attrs['path'] ?? ''}`, '*** End of File', ...lines.map((l) => `+${l}`), '*** End Patch'].join('\n');
|
|
196
|
+
return { name: 'apply_patch', arguments: { input: patch } };
|
|
197
|
+
}
|
|
198
|
+
case 'tf-grep': {
|
|
199
|
+
// F2:搜索只回匹配行(宿主 grep 自带行号与按文件分组),不回全文;
|
|
200
|
+
// 权限与工作区边界由宿主决定(不自建遍历)。
|
|
201
|
+
const args = { pattern: cmd.attrs['pattern'] ?? '' };
|
|
202
|
+
if (cmd.attrs['path'] !== undefined && cmd.attrs['path'] !== '') args['path'] = cmd.attrs['path'];
|
|
203
|
+
if (cmd.attrs['include'] !== undefined && cmd.attrs['include'] !== '') args['include'] = cmd.attrs['include'];
|
|
204
|
+
return { name: 'grep', arguments: args };
|
|
205
|
+
}
|
|
206
|
+
case 'tf-glob': {
|
|
207
|
+
const args = { pattern: cmd.attrs['pattern'] ?? '' };
|
|
208
|
+
if (cmd.attrs['path'] !== undefined && cmd.attrs['path'] !== '') args['path'] = cmd.attrs['path'];
|
|
209
|
+
return { name: 'glob', arguments: args };
|
|
210
|
+
}
|
|
211
|
+
case 'tf-bash':
|
|
212
|
+
// DSH Windows 宿主的 shell 工具是 pwsh(dsh-tool-pwsh:command 与 description 双必填,
|
|
213
|
+
// lib/index.js:249-250 实证)——v0.1.0 映射到不存在的 'bash',真连 R3/R4/C1 的
|
|
214
|
+
// "unknown tool bash" 即此缺陷(2026-11-15 修复)。
|
|
215
|
+
return {
|
|
216
|
+
name: 'pwsh',
|
|
217
|
+
arguments: {
|
|
218
|
+
command: cmd.attrs['cmd'] ?? '',
|
|
219
|
+
description: `tf-bash: ${(cmd.attrs['cmd'] ?? '').slice(0, 80)}`,
|
|
220
|
+
},
|
|
221
|
+
};
|
|
222
|
+
default:
|
|
223
|
+
return null; // tf-peek / tf-final / tf-code 由驱动器内部处理(tf-code 走 executeCode 端口)
|
|
224
|
+
}
|
|
225
|
+
},
|
|
226
|
+
};
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* 会话事件写入面(真实宿主路径专用;事件形状逐字段镜像 dsh-agent-loop/lib/index.js
|
|
306
|
+
* 的 append 调用 :731/:757/:781/:819/:891-955,turn/end reason 形状镜像 :747-821)。
|
|
307
|
+
*/
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
/** kernel/gate.ts ActionGate.admit 的 duck-type 面(04 号对接面备忘) */
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
// ---------------------------------------------------------------------------
|
|
365
|
+
// ledger 记录(探针 C 定案:tf-* 协议状态落 plugin:tf-agent/<record> 私有记录)
|
|
366
|
+
// ---------------------------------------------------------------------------
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
/** plugin record 通道(真实宿主)。类型语法 plugin:tf-agent/<record>(dsh-session types.d.ts:527)。 */
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
/**
|
|
396
|
+
* 不可重试的流错误码(LLM 配置/凭据层故障):重入必然重演,fail-fast 终止回合,
|
|
397
|
+
* 不烧重入预算(探针 A 实测 MISSING_CREDENTIAL 即此层错误)。
|
|
398
|
+
*/
|
|
399
|
+
const NON_RETRYABLE_STREAM_CODES = new Set([
|
|
400
|
+
'AUTH', 'MISSING_CREDENTIAL', 'NO_ADAPTER', 'INVALID_REQUEST', 'INVALID_PREPARED_CALL', 'NOT_FOUND', 'FORBIDDEN',
|
|
401
|
+
]);
|
|
402
|
+
|
|
403
|
+
// ---------------------------------------------------------------------------
|
|
404
|
+
// 默认协议文本(稳定前缀组成部分;逐字节确定性,禁止任何动态字段 —— O4)
|
|
405
|
+
// ---------------------------------------------------------------------------
|
|
406
|
+
|
|
407
|
+
export const DEFAULT_SYSTEM_PROMPT = '你是运行在 DeepSeek Harness 里的单流协议 agent。在一次回复流中完成任务:先简短思考,然后连续输出全部 tf-* 命令,最后输出 tf-final。';
|
|
408
|
+
|
|
409
|
+
export const DEFAULT_PROTOCOL_TEXT = `## tf-* 单流协议(本回合唯一工具语法)
|
|
410
|
+
|
|
411
|
+
<tf-write path="相对/绝对路径" id="w1" depends_on="r1">
|
|
412
|
+
文件正文原文(原样输出,直到闭合标签)
|
|
413
|
+
</tf-write>
|
|
414
|
+
<tf-read path="相对/绝对路径" id="r1" depends_on="w1,w2" offset="100" limit="50"/>
|
|
415
|
+
<tf-edit path="src/app.ts" id="e1" depends_on="r1">
|
|
416
|
+
<<<<<<< OLD
|
|
417
|
+
被替换的原文(精确字面量,全文唯一;不做模糊匹配)
|
|
418
|
+
=======
|
|
419
|
+
替换后的新文
|
|
420
|
+
>>>>>>> NEW
|
|
421
|
+
</tf-edit>
|
|
422
|
+
<tf-append path="notes.md" id="a1" anchor="锚点原文(可选;缺省=追加到文件末尾)">
|
|
423
|
+
追加正文(原样输出,直到闭合标签;不改既有内容)
|
|
424
|
+
</tf-append>
|
|
425
|
+
<tf-grep pattern="正则" path="src" include="*.ts" id="g1"/>
|
|
426
|
+
<tf-glob pattern="**/*.md" id="gl1"/>
|
|
427
|
+
<tf-bash cmd="命令行" id="b1"/>
|
|
428
|
+
<tf-peek handle="obs:read:c3@v1" from_line="10" to_line="20" id="p1"/>
|
|
429
|
+
<tf-final id="f1" summary="一句话完成说明"/>
|
|
430
|
+
|
|
431
|
+
(改既有文件用 tf-edit(精确替换)或 tf-append(只追加),不要整文件重写;
|
|
432
|
+
找内容用 tf-grep(回匹配行)/tf-glob(回路径),不要用 tf-bash 调 shell 搜索,
|
|
433
|
+
也不要把搜索当"读文件"用——grep 结果超长会截断并提示 tf-peek。)
|
|
434
|
+
|
|
435
|
+
(tf-read 可选 offset/limit:1 基行号起点与行数,大文件按行段取,省 token。)
|
|
436
|
+
|
|
437
|
+
(收尾纪律:命令全部闭合后,本流必须以 tf-final 结束;写完文件、执行完命令不等于任务结束。)
|
|
438
|
+
|
|
439
|
+
## 计划与验收(复合任务推荐)
|
|
440
|
+
<tf-plan id="p1">
|
|
441
|
+
- [a1] 验收项描述
|
|
442
|
+
- [a2] 验收项描述
|
|
443
|
+
</tf-plan>
|
|
444
|
+
- 计划只声明一次;修订时重发 tf-plan(新计划整体替换旧计划,请求里只注差分)。
|
|
445
|
+
- 完成某验收项对应的命令时,在该命令上加 accepts 属性,如 <tf-write path="out.md" id="w1" accepts="a1">...</tf-write>。
|
|
446
|
+
- 全部验收项都有命令成功回执后 tf-final 才会通过;缺项/未验证会被判为过早并注入提示——
|
|
447
|
+
模型自述"已完成"不构成验收证据。
|
|
448
|
+
|
|
449
|
+
## 结果获取(关键)
|
|
450
|
+
tf-read 首次/内容变化的结果会完整注入下一请求(超长文件截断为中段省略,用 tf-peek 精确取回);
|
|
451
|
+
tf-bash / tf-write / tf-edit / tf-append 成功只记台账(回执),不回灌输出。
|
|
452
|
+
失败一律以 [tf-stream:error] 注入,没有错误注入就是成功了。
|
|
453
|
+
因此:要看命令输出或计算结果时,用 tf-peek 按句柄取回——handle 从 [tf-stream:observation]
|
|
454
|
+
与句柄目录增量中取。答案依赖命令输出时,先 peek 再收尾。
|
|
455
|
+
|
|
456
|
+
## 回验纪律(省 token 的关键)
|
|
457
|
+
- 你 tf-write 的正文全文就在你的上下文里:不要为了"确认写成功"而 tf-read 自己刚写过的
|
|
458
|
+
路径——那只会得到回执(行数 + 内容指纹,[tf-stream:receipt]),不会重复回灌全文。
|
|
459
|
+
写失败一定会有 [tf-stream:error] 注入;没有错误注入就是写成功了。
|
|
460
|
+
- tf-read 留给"读不是你写的文件"(任务要求读的既有文件、命令产出的文件)。
|
|
461
|
+
- 确需局部比对自写文件时,用 tf-peek 按行段取回,不要全文重读。
|
|
462
|
+
|
|
463
|
+
## 时序与重发规则
|
|
464
|
+
- 同 id 同内容重复声明 = 幂等:直接返回原回执(含句柄),不重复执行;同 id 不同内容会被
|
|
465
|
+
拒绝(换新 id);被拒绝(无副作用)的命令可用原 id 修正后重发。
|
|
466
|
+
- 同流内后续命令自动等待先闭合的 tf-write 完成(写序保证:先写后读不会读到旧内容)。
|
|
467
|
+
- tf-peek 的句柄由命令产出——同流内提前 peek 会被自动延迟到命令完成后重试,仍无此句柄才报错;
|
|
468
|
+
要么给 peek 加 depends_on 挂到产出命令上(如 <tf-peek ... depends_on="r1"/>),
|
|
469
|
+
要么等下一请求(句柄会出现在句柄目录增量里)再 peek。
|
|
470
|
+
- tf-bash 的命令在 Windows 宿主以 PowerShell(pwsh)执行:python3 通常不存在,优先 node -e 或
|
|
471
|
+
PowerShell 原生命令(Select-String / Get-Content)。
|
|
472
|
+
|
|
473
|
+
tf-final 的 summary 必须包含任务要求的最终答案原文(数字、行内容、路径、结论),
|
|
474
|
+
不得写"已完成/占位"式描述;还没拿到答案就不要输出 tf-final。
|
|
475
|
+
|
|
476
|
+
规则:
|
|
477
|
+
1. 写文件一律用 tf-write(正文在标签体内原样输出);不要用原生工具写文件。
|
|
478
|
+
2. id 建议显式给出且全任务唯一;depends_on 是逗号分隔的依赖 id 列表,可省略。
|
|
479
|
+
依赖只能指向本任务里已出现或将要出现的命令 id。
|
|
480
|
+
3. 命令闭合即开始执行(独立命令并行,上限 3 个),不必等流结束再发后续命令。
|
|
481
|
+
4. tf-read 首次/变化结果完整注入下一请求;其余成功产出只句柄化(见"结果获取")。
|
|
482
|
+
需要某句柄的细节时发 tf-peek(handle 用句柄目录里的值,行段 1-based 闭区间)。
|
|
483
|
+
tf-edit 匹配失败(原文不唯一/不存在)会以结构化错误注入:核对后修正 OLD 段重发,
|
|
484
|
+
不要扩大替换范围改全文。tf-grep/tf-glob 只回匹配行/路径,超长会截断并提示 tf-peek。
|
|
485
|
+
5. 上一请求若报告 [tf-stream:error],先修复或改道该命令(换路径/换命令),再继续其余任务。
|
|
486
|
+
6. 全部命令成功且无需更多信息时输出 tf-final;收到 tf-final 后本任务收敛,不再有下一请求。
|
|
487
|
+
7. 调用工具只允许上表的 tf-* 标记:不要输出 <||DSML||…>、<think> 包裹、JSON tool_call
|
|
488
|
+
等任何原生调用格式——它们不会被解析成命令,只会浪费输出 token 并在界面显示为乱码。`;
|
|
489
|
+
|
|
490
|
+
export const DEFAULT_INVARIANTS = '不变量:历史消息只增不改(任何"压缩/摘要历史"的请求都会被拒绝);写文件成功不会有结果回灌(只记台账),失败一定会以 [tf-stream:error] 注入下一请求;tf-read 自己刚写过的文件只会得到回执([tf-stream:receipt],行数+指纹),不会回灌全文;不要用原生 tool_call 写文件。回合必须以 <tf-final .../> 收尾:所有命令输出完毕后立即输出 tf-final,不带 tf-final 的回合视为未完成——即使全部工作已做完。';
|
|
491
|
+
|
|
492
|
+
/**
|
|
493
|
+
* tf-code 通道的协议段(PTC 桥接):仅在 executeCode 端口在位时追加到协议文本之后
|
|
494
|
+
* (稳定前缀,构造期冻结——通道关闭的装配里模型永远看不到 tf-code,不会幻觉调用)。
|
|
495
|
+
*/
|
|
496
|
+
export const DEFAULT_CODE_PROTOCOL_SECTION = `## tf-code 程序化工具调用(PTC 桥接)
|
|
497
|
+
|
|
498
|
+
<tf-code id="c1" depends_on="w1" timeout="120000" description="一句话说明程序做什么">
|
|
499
|
+
(async TypeScript 函数体,可擦除语法——不用 enum/namespace;顶层 await 与 return 可用)
|
|
500
|
+
const lines = String(await tools.read({ file_path: 'big.log' })).split('\\n');
|
|
501
|
+
const errors = lines.filter((l) => l.includes('ERROR'));
|
|
502
|
+
return { total: lines.length, errorCount: errors.length, samples: errors.slice(0, 20) };
|
|
503
|
+
</tf-code>
|
|
504
|
+
|
|
505
|
+
- 程序体内可用的绑定(与 tf-write/tf-read/tf-bash 同一条宿主管线,守卫与工作区策略全部生效):
|
|
506
|
+
await tools.write({ file_path, content }) / await tools.read({ file_path, offset?, limit? }) /
|
|
507
|
+
await tools.pwsh({ command, description })。失败的绑定调用会抛错,可 try/catch 后继续或让程序失败。
|
|
508
|
+
- 中间结果不进上下文:只 return 最终值(无损 JSON 进句柄目录);需要看值时对该命令的句柄发 tf-peek。
|
|
509
|
+
- 独立子调用可用 Promise.all 并行;有顺序依赖的用 await 串行。
|
|
510
|
+
- 什么时候用 tf-code:多步数据加工(过滤/统计/变换/聚合)。单次文件读写用 tf-write/tf-read,
|
|
511
|
+
单条命令用 tf-bash,不要为一条命令包一层程序。
|
|
512
|
+
- 程序失败会以 [tf-stream:code-error] 注入(kind + 可重试结论,kind: exception/timeout/abort/
|
|
513
|
+
worker-exit/invalid-output/output-limit/protocol/sandbox-unavailable/quota-exceeded),
|
|
514
|
+
修复代码后换新 id 重发;timeout 属性为毫秒数,可省略(用宿主默认)。
|
|
515
|
+
- 每次运行的子调用次数、输出字节、墙钟有插件级配额(超限结构化终止 kind: quota-exceeded);
|
|
516
|
+
沙箱事实(mode/enforcement)逐次记账,enforcement=partial 只覆盖文件效果、不是隔离。`;
|
|
517
|
+
|
|
518
|
+
/** F3:tf-code 首成功/变化结果完整注入的默认上限(字符)。4000 ≈ 2k tokens:
|
|
519
|
+
* 上限内值直接可见(省一次 tf-peek 往返),超限转骨架 + 句柄(中间结果不回灌的红线不破)。 */
|
|
520
|
+
export const DEFAULT_CODE_VALUE_INJECT_LIMIT = 4000;
|
|
521
|
+
|
|
522
|
+
/** F4:原生 tool_call 结果单块注入的默认上限(字符),仅声明 nativeToolSchemas 时生效。
|
|
523
|
+
* 6000 ≈ 3k tokens:首成功/短结果完整注入,超限转骨架 + 句柄,杜绝原生通道全量回灌。 */
|
|
524
|
+
export const DEFAULT_NATIVE_RESULT_LIMIT = 6000;
|
|
525
|
+
|
|
526
|
+
/** F7:长会话段边界阈值(追加区字符数)。160k 字符 ≈ 40k tokens:超过即在新回合开始处
|
|
527
|
+
* 整块丢弃旧段(ADR-001:整块丢弃路线,显式缓存重置点,原文句柄化可回取)。 */
|
|
528
|
+
export const DEFAULT_SEGMENT_MAX_CHARS = 160_000;
|
|
529
|
+
|
|
530
|
+
/** v0.3.2:单步正文落追加区的上限(字符)。prose 通常很短;超长只截断历史摘要,
|
|
531
|
+
* 当期 assistant/message 仍完整落盘(不改变可读输出)。 */
|
|
532
|
+
export const STEP_PROSE_COMMIT_LIMIT = 4000;
|
|
533
|
+
|
|
534
|
+
/** v0.3.2:同一回合内"输出被截断 → 要求续写"的最大次数。超过即如实 blocked,
|
|
535
|
+
* 不无限重试(真机 max-tokens 截断的恢复路径需要重发完整命令,次数有界)。 */
|
|
536
|
+
export const MAX_TRUNCATION_RETRIES = 4;
|
|
537
|
+
|
|
538
|
+
/** v0.3.2:可转正进追加区的易变尾前缀(事实类)。瞬态指令(nudge/degraded/error)不转正。 */
|
|
539
|
+
const DURABLE_TAIL_PREFIXES = [
|
|
540
|
+
'[tf-stream:observation',
|
|
541
|
+
'[tf-stream:peek',
|
|
542
|
+
'[tf-stream:tool-result',
|
|
543
|
+
'[tf-stream:replay',
|
|
544
|
+
];
|
|
545
|
+
|
|
546
|
+
/** v0.3.2:正文归一化(连续空行压成一个;去首尾空白)——避免 "\n\n\n\n" 的空消息污染正文。 */
|
|
547
|
+
export function normalizeProse(text ) {
|
|
548
|
+
return text.replace(/\r\n/g, '\n').replace(/\n{3,}/g, '\n\n').trim();
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
/** 截断到上限(保留尾部标记,便于台账核对)。 */
|
|
552
|
+
function capText(text , limit ) {
|
|
553
|
+
return text.length <= limit ? text : `${text.slice(0, limit)}…(截断 ${text.length - limit} 字符)`;
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
/**
|
|
557
|
+
* v0.3.2:输出截断的续写注入。带已生成内容尾部(≤800 字符)——正文命令被 max-tokens
|
|
558
|
+
* 截断时,模型可以从断点继续,而不是从头重写整个文件。
|
|
559
|
+
*/
|
|
560
|
+
function truncationNudge(truncation ) {
|
|
561
|
+
const tail = truncation.raw.length <= 800
|
|
562
|
+
? truncation.raw
|
|
563
|
+
: `…${truncation.raw.slice(truncation.raw.length - 800)}`;
|
|
564
|
+
const head = truncation.reason === 'max-tokens'
|
|
565
|
+
? '上一条请求的输出触及 max tokens 上限,在句子/命令中途被截断。'
|
|
566
|
+
: `上一条请求的输出在命令中途被截断(${truncation.reason})。`;
|
|
567
|
+
return [
|
|
568
|
+
`[tf-stream:truncated reason=${truncation.reason}] ${head}`,
|
|
569
|
+
'已完整闭合的命令都已执行,不要重复执行;未闭合的命令没有被执行。',
|
|
570
|
+
'请从断点继续:把被截断的命令用**新 id**完整重发(正文命令必须给出完整内容,不能只给片段),',
|
|
571
|
+
'然后继续未完成的工作;任务确实已完成则输出 tf-final(summary 写最终答案原文)。',
|
|
572
|
+
tail !== '' ? `已生成部分的尾部(供续写定位):\n${tail}` : '',
|
|
573
|
+
].filter((line) => line !== '').join('\n');
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
// ---------------------------------------------------------------------------
|
|
577
|
+
// ② SingleStreamDriver
|
|
578
|
+
// ---------------------------------------------------------------------------
|
|
579
|
+
|
|
580
|
+
|
|
581
|
+
|
|
582
|
+
|
|
583
|
+
|
|
584
|
+
|
|
585
|
+
|
|
586
|
+
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
/** F5:验收项(计划状态放驱动器=宿主侧;请求只注差分)。 */
|
|
594
|
+
|
|
595
|
+
|
|
596
|
+
|
|
597
|
+
|
|
598
|
+
|
|
599
|
+
|
|
600
|
+
|
|
601
|
+
/** F5:解析 tf-plan body 的验收项行(`- [id] 描述`;无有效行时调用方判结构化失败)。 */
|
|
602
|
+
export function parsePlanItems(body ) {
|
|
603
|
+
const items = [];
|
|
604
|
+
const seen = new Set ();
|
|
605
|
+
for (const line of body.split('\n')) {
|
|
606
|
+
const m = line.match(/^\s*[-*]?\s*\[([A-Za-z0-9_-]{1,64})\]\s+(.+?)\s*$/);
|
|
607
|
+
if (m === null) continue;
|
|
608
|
+
const id = m[1] ;
|
|
609
|
+
if (seen.has(id)) continue;
|
|
610
|
+
seen.add(id);
|
|
611
|
+
items.push({ id, text: m[2] });
|
|
612
|
+
}
|
|
613
|
+
return items;
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
|
|
617
|
+
|
|
618
|
+
|
|
619
|
+
|
|
620
|
+
|
|
621
|
+
|
|
622
|
+
|
|
623
|
+
|
|
624
|
+
|
|
625
|
+
|
|
626
|
+
|
|
627
|
+
|
|
628
|
+
|
|
629
|
+
|
|
630
|
+
|
|
631
|
+
|
|
632
|
+
|
|
633
|
+
|
|
634
|
+
|
|
635
|
+
|
|
636
|
+
|
|
637
|
+
|
|
638
|
+
let DRIVER_SEQ = 0;
|
|
639
|
+
|
|
640
|
+
export class SingleStreamDriver {
|
|
641
|
+
#ports ;
|
|
642
|
+
#cfg
|
|
643
|
+
|
|
644
|
+
|
|
645
|
+
|
|
646
|
+
|
|
647
|
+
|
|
648
|
+
|
|
649
|
+
|
|
650
|
+
|
|
651
|
+
|
|
652
|
+
|
|
653
|
+
|
|
654
|
+
|
|
655
|
+
|
|
656
|
+
|
|
657
|
+
|
|
658
|
+
|
|
659
|
+
|
|
660
|
+
|
|
661
|
+
|
|
662
|
+
|
|
663
|
+
|
|
664
|
+
|
|
665
|
+
|
|
666
|
+
|
|
667
|
+
|
|
668
|
+
|
|
669
|
+
|
|
670
|
+
|
|
671
|
+
;
|
|
672
|
+
#renderer ;
|
|
673
|
+
#obs ;
|
|
674
|
+
#records = [];
|
|
675
|
+
#commands = new Map ();
|
|
676
|
+
#inFlight = new Set ();
|
|
677
|
+
#activeControllers = new Set ();
|
|
678
|
+
/** 当前流内命令序号(隐式写序:后续命令等待先闭合的同流 tf-write —— 上游 ThinkFlow 语义) */
|
|
679
|
+
#streamSeqCounter = 0;
|
|
680
|
+
#streamWrites = [];
|
|
681
|
+
/** unknown-handle 的 peek(同流乐观 peek):流末 drain 后重试一次,仍无此句柄才失败 */
|
|
682
|
+
#deferredPeeks = [];
|
|
683
|
+
/** 本任务内 tf-write 已成功写过的路径(规范化分隔符;修复限制 1 的自写回验判定) */
|
|
684
|
+
#writtenPaths = new Set ();
|
|
685
|
+
/** F5 计划与验收:计划状态放驱动器(宿主侧);请求只注差分。
|
|
686
|
+
* items 为当前 revision 的验收项全集;announced 保存上次注入时各验收项的状态,
|
|
687
|
+
* 差分 = 两次状态之差(新增 / 变已验证 / 移除)。 */
|
|
688
|
+
#plan = null;
|
|
689
|
+
#planAnnounced = null;
|
|
690
|
+
/** 运行中回合收到的 steer(修复限制 2:下一请求装配时进追加区,对齐内建"注入运行中回合的下一步") */
|
|
691
|
+
#pendingSteers = [];
|
|
692
|
+
|
|
693
|
+
#turnCounter = 0;
|
|
694
|
+
/** K4 取消链路:回合级 signal(runTurn 创建,cancel 时 abort)。所有工具派发
|
|
695
|
+
* (executeTools / executeCode)共用它——不再用独立且永不触发的 AbortController。 */
|
|
696
|
+
#turnController = null;
|
|
697
|
+
#requestCount = 0;
|
|
698
|
+
#reentryCount = 0;
|
|
699
|
+
#finalNudges = 0;
|
|
700
|
+
/** v0.3.2:上次 nudge 时的 ok 命令数(进度感知护栏的基准点;null = 本回合尚未 nudge)。 */
|
|
701
|
+
#nudgeMark = null;
|
|
702
|
+
#finalOnlyRequests = 0;
|
|
703
|
+
#deltaCursor = 0; // O3 directoryDelta 游标(obs seq 空间)
|
|
704
|
+
#usage = { inputTokens: 0, outputTokens: 0 };
|
|
705
|
+
#injectedChars = 0;
|
|
706
|
+
#stableHashes = [];
|
|
707
|
+
#aborted = false;
|
|
708
|
+
#abortReason ;
|
|
709
|
+
#ledger ;
|
|
710
|
+
#warn ;
|
|
711
|
+
#gate ;
|
|
712
|
+
#taskId = 'task';
|
|
713
|
+
#sessionId ;
|
|
714
|
+
/** 已上报的结构化问题(同一失败只注入一次) */
|
|
715
|
+
#reportedIssues = new Set ();
|
|
716
|
+
/** 已注入骨架的观测 key(driver seq 空间,避免重复注入) */
|
|
717
|
+
#reportedObservations = new Set ();
|
|
718
|
+
/** 已回灌结果的 peek 命令 id */
|
|
719
|
+
#reportedPeeks = new Set ();
|
|
720
|
+
/** 当前 agent 引用(executeTools 带上 agent;fs 工具 session 解析依赖,见 ToolBatchInputLike) */
|
|
721
|
+
#agentRef = undefined;
|
|
722
|
+
/** K2:会话工作区(factory 从 session header / workingDirectory 服务解析后回填;
|
|
723
|
+
* tf-code resolve 透传,与 tf-write/tf-read 的路径解析语义一致)。 */
|
|
724
|
+
#sessionCwd = undefined;
|
|
725
|
+
/** F6:resume 停机核对标记("有意图无回执"时由 factory 置位;置位后 runTurn 直接 blocked,
|
|
726
|
+
* 不发任何请求、零注入——由用户核对后重启/清除意图,不自动重放)。 */
|
|
727
|
+
#resumeHalt = null;
|
|
728
|
+
/** F7:当前任务块在追加区的起始下标(pushUserTask 时刻的块数)——段丢弃只丢它之前的旧段。 */
|
|
729
|
+
#segmentKeepFrom = 0;
|
|
730
|
+
/** ok 的 tf-final 候选(解析序);任务最终答案取最后一个(过早 final 可被后继覆盖) */
|
|
731
|
+
#finalCandidates = [];
|
|
732
|
+
/** v0.3.1 截断修复:回合级命令序(跨请求单调递增)。
|
|
733
|
+
* final 之后又发过命令 → 这条 final 已被后续工作作废,必须在流末重发(#lastNonFinalOrder > #lastFinalOrder)。 */
|
|
734
|
+
#cmdOrder = 0;
|
|
735
|
+
#lastFinalOrder = 0;
|
|
736
|
+
#lastNonFinalOrder = 0;
|
|
737
|
+
/** 已提示过的 final 拒绝(key = 拒绝 kind);同类问题只注入一次,二次不放行也不重复烧注入 */
|
|
738
|
+
#reportedFinalRejects = new Set ();
|
|
739
|
+
/** 重复命令的原结果回灌队列(幂等重发不重执行,但把内容回灌给丢失上下文的模型) */
|
|
740
|
+
#pendingReplays = [];
|
|
741
|
+
#replays = 0;
|
|
742
|
+
#replayCapped = false;
|
|
743
|
+
/**
|
|
744
|
+
* v0.3.2 连续性问题(真机 session-e4b9a89c):请求之间模型看不到自己上一步的正文、
|
|
745
|
+
* 命令与命令结果——0.3.x 只把观测注入"易变尾"一次(#reportedObservations 永不重放),
|
|
746
|
+
* 易变尾每请求重建、从不进追加区。于是第 2 个请求之后模型看到的只有 system + 任务 +
|
|
747
|
+
* 句柄目录行,模型侧原话"history is truncated / I don't have their content in context",
|
|
748
|
+
* 随后重复读同一文件、用占位 final 收场。修复:每步的正文 + 命令摘要落进追加区
|
|
749
|
+
*(assistant/message 语义),已发出的易变尾在下一请求装配后转正为历史(只追加,前缀单调)。
|
|
750
|
+
*/
|
|
751
|
+
#lastStepDigest
|
|
752
|
+
|
|
753
|
+
|
|
754
|
+
|
|
755
|
+
|
|
756
|
+
|
|
757
|
+
= null;
|
|
758
|
+
/** 已随请求发出、尚未转正进追加区的易变尾(含 step 归属,跨回合不转正)。 */
|
|
759
|
+
#deliveredTail = null;
|
|
760
|
+
/** 本步被截断的事实(parser truncated 事件 / finish=max-tokens);非空即强制续写一次。 */
|
|
761
|
+
#truncation = null;
|
|
762
|
+
#truncationRetries = 0;
|
|
763
|
+
/** 本步命令 id 与原生调用(摘要用;流开始时重置) */
|
|
764
|
+
#stepCommandIds = [];
|
|
765
|
+
#stepNatives = [];
|
|
766
|
+
/** v0.3.1:当前流内的 prose 累积(parser 的 text 事件拼接;落盘 assistant/message 的正文)。
|
|
767
|
+
* 0.3.0 落盘的是整段原文(含 tf-* 标记与 DSML 噪声)——桌面端过程区把协议标记渲染成乱码,
|
|
768
|
+
* 本版起落盘纯 prose:命令事实在台账(plugin:tf-agent/*),会话日志只留用户可读内容。 */
|
|
769
|
+
#streamProse = '';
|
|
770
|
+
/** v0.3.1 实时帧状态:agent 生命周期内的 attempt 序号与帧序号(revision 逐帧 +1,
|
|
771
|
+
* 契约见 dsh-api-session-controller SessionAssistantStreamAccumulator.accept)。 */
|
|
772
|
+
#attemptCounter = 0;
|
|
773
|
+
#frameRevision = 0;
|
|
774
|
+
#frameChunkIndex = 0;
|
|
775
|
+
#frameAttemptId = undefined;
|
|
776
|
+
/** 实时帧熔断:发射抛错(无监听器异常/宿主总线异常)后本会话不再发(fail-open)。 */
|
|
777
|
+
#frameBroken = false;
|
|
778
|
+
|
|
779
|
+
// ---------------------------------------------------------- v0.3.1 实时帧(agent/assistant-stream)
|
|
780
|
+
|
|
781
|
+
/**
|
|
782
|
+
* 思考过程实时帧(桌面端 live 显示的数据源)。契约对齐宿主两端的 fold:
|
|
783
|
+
* dsh-api-session-controller SessionAssistantStreamAccumulator.accept(服务端,要求
|
|
784
|
+
* revision 逐帧 +1、chunk index 逐块 +1)与客户端 ClientAssistantStream.acceptFrame
|
|
785
|
+
* (start 只在无活跃 attempt 时接受)。发射异常即熔断(本会话不再发,fail-open)。
|
|
786
|
+
*/
|
|
787
|
+
#frameEmit(frame ) {
|
|
788
|
+
if (this.#frameBroken || this.#ports.emitHostEvent === undefined || this.#agentRef === undefined) return;
|
|
789
|
+
try {
|
|
790
|
+
this.#ports.emitHostEvent('agent/assistant-stream', { agent: this.#agentRef, frame });
|
|
791
|
+
} catch (error) {
|
|
792
|
+
this.#frameBroken = true;
|
|
793
|
+
this.#warn('assistant-stream 实时帧发射失败(已熔断,本会话不再发)', error);
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
/** 流开始帧:分配 attemptId(session 内唯一),index 清零。 */
|
|
798
|
+
#frameStartAttempt(turn , step ) {
|
|
799
|
+
if (this.#ports.emitHostEvent === undefined || this.#agentRef === undefined || this.#sessionId === undefined) return;
|
|
800
|
+
this.#frameAttemptId = `${this.#sessionId}:${++this.#attemptCounter}`;
|
|
801
|
+
this.#frameChunkIndex = 0;
|
|
802
|
+
this.#frameEmit({ type: 'start', attemptId: this.#frameAttemptId, revision: ++this.#frameRevision, turn, step });
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
/** 思考 delta 帧(正文不逐帧透传:流文本是协议标记,实时显示会闪现乱码)。 */
|
|
806
|
+
#frameReasoningDelta(index , text ) {
|
|
807
|
+
if (this.#frameAttemptId === undefined) return;
|
|
808
|
+
this.#frameEmit({
|
|
809
|
+
type: 'chunk',
|
|
810
|
+
attemptId: this.#frameAttemptId,
|
|
811
|
+
revision: ++this.#frameRevision,
|
|
812
|
+
index: this.#frameChunkIndex++,
|
|
813
|
+
time: Date.now(),
|
|
814
|
+
chunk: { type: 'reasoning-delta', index, text },
|
|
815
|
+
});
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
/** 流末结算帧:durable 结算已落(有 seq)才发 committed,否则 abandoned。 */
|
|
819
|
+
#frameEndAttempt(settlement ) {
|
|
820
|
+
if (this.#frameAttemptId === undefined) return;
|
|
821
|
+
this.#frameEmit({
|
|
822
|
+
type: 'end',
|
|
823
|
+
attemptId: this.#frameAttemptId,
|
|
824
|
+
revision: ++this.#frameRevision,
|
|
825
|
+
index: this.#frameChunkIndex,
|
|
826
|
+
outcome: settlement !== undefined && settlement.seq !== undefined
|
|
827
|
+
? { kind: 'committed', eventType: settlement.eventType, seq: settlement.seq }
|
|
828
|
+
: { kind: 'abandoned' },
|
|
829
|
+
});
|
|
830
|
+
this.#frameAttemptId = undefined;
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
/**
|
|
834
|
+
* 工具广告前的 attempt 收束(abandoned)。客户端 fold 会把活跃 attempt 期间到达的
|
|
835
|
+
* assistant/message(广告消息)暂存进 pending,而 end 帧只消费一条结算——不先收束,
|
|
836
|
+
* 广告条目会永久滞留 pending,下一步的 start 帧触发 events.restart()(整窗重建)。
|
|
837
|
+
* 先收束:广告与后续 tool/call、落盘消息全部直接 publish,零 restart。
|
|
838
|
+
*/
|
|
839
|
+
#frameEndAbandonedIfOpen() {
|
|
840
|
+
this.#frameEndAttempt(undefined);
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
constructor(ports , config , renderer , obs ) {
|
|
844
|
+
this.#ports = ports;
|
|
845
|
+
this.#cfg = {
|
|
846
|
+
provider: config.provider,
|
|
847
|
+
model: config.model,
|
|
848
|
+
reasoningEffort: config.reasoningEffort,
|
|
849
|
+
maxParallelToolCalls: config.maxParallelToolCalls ?? 3,
|
|
850
|
+
maxReentries: config.maxReentries ?? 8,
|
|
851
|
+
streamIdleTimeoutMs: config.streamIdleTimeoutMs ?? 30_000,
|
|
852
|
+
budgetTokens: config.budgetTokens,
|
|
853
|
+
selfReadFeedback: config.selfReadFeedback ?? 'receipt',
|
|
854
|
+
// K1(0.3.0):默认关闭——只有显式 enableCode:true 且端口在位才启用。
|
|
855
|
+
// 0.2.0 的"端口在位即启用"(auto)语义已按 M2/K1 结论收口:协议段默认 0 字符。
|
|
856
|
+
codeEnabled: config.enableCode === true && ports.executeCode !== undefined,
|
|
857
|
+
codeTimeoutMs: config.codeTimeoutMs,
|
|
858
|
+
codeQuota: { ...DEFAULT_CODE_QUOTA, ...(config.codeQuota ?? {}) },
|
|
859
|
+
codeValueInjectLimit: config.codeValueInjectLimit ?? DEFAULT_CODE_VALUE_INJECT_LIMIT,
|
|
860
|
+
nativeResultLimit: config.nativeResultLimit ?? DEFAULT_NATIVE_RESULT_LIMIT,
|
|
861
|
+
nativeToolSchemasEnabled: config.nativeToolSchemas !== undefined,
|
|
862
|
+
enablePlan: config.enablePlan ?? true,
|
|
863
|
+
segmentMaxChars: config.segmentMaxChars ?? DEFAULT_SEGMENT_MAX_CHARS,
|
|
864
|
+
toolMapping: config.toolMapping ?? DEFAULT_TOOL_MAPPING,
|
|
865
|
+
};
|
|
866
|
+
// tf-code 协议段只在实际可执行时声明(稳定前缀构造期冻结:通道不存在就不会被模型幻觉调用)
|
|
867
|
+
const protocolText = (config.protocolText ?? DEFAULT_PROTOCOL_TEXT)
|
|
868
|
+
+ (this.#cfg.codeEnabled ? `\n\n${config.codeProtocolText ?? DEFAULT_CODE_PROTOCOL_SECTION}` : '');
|
|
869
|
+
this.#renderer = renderer ?? new ContextRenderer({
|
|
870
|
+
system: config.systemPrompt ?? DEFAULT_SYSTEM_PROMPT,
|
|
871
|
+
protocol: protocolText,
|
|
872
|
+
toolSchemas: config.nativeToolSchemas ?? '(本回合未启用原生工具;一切文件与命令操作走 tf-* 协议)',
|
|
873
|
+
invariants: config.invariants ?? DEFAULT_INVARIANTS,
|
|
874
|
+
});
|
|
875
|
+
this.#obs = obs ?? new ObservationLedger({ starvationThreshold: config.starvationThreshold });
|
|
876
|
+
this.#warn = ports.onWarning ?? (() => {});
|
|
877
|
+
this.#gate = ports.gate;
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
/** 注入 ledger 通道(探针 C 定案的 plugin:tf-agent/* 落盘口;缺省只进内存 records)。 */
|
|
881
|
+
attachLedger(sink ) {
|
|
882
|
+
this.#ledger = sink;
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
/** 运行时模型路由切换(Agent.model.select 的落点)。 */
|
|
886
|
+
applySelection(selection ) {
|
|
887
|
+
if (selection.provider !== undefined) this.#cfg.provider = selection.provider;
|
|
888
|
+
if (selection.model !== undefined) this.#cfg.model = selection.model;
|
|
889
|
+
if (selection.reasoningEffort !== undefined) this.#cfg.reasoningEffort = selection.reasoningEffort;
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
/** v0.3.2:assistant 消息宿主来源的实时值(写入时取,不缓存;applySelection 后随动)。
|
|
893
|
+
* 会话日志与请求装配共用;kind 固定 'model'。空串由 makeAssistantMessage 兜底为
|
|
894
|
+
* 'unknown'(宿主校验拒绝空字符串)。 */
|
|
895
|
+
modelSource() {
|
|
896
|
+
return { kind: 'model', provider: this.#cfg.provider, model: this.#cfg.model };
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
/** Agent 层接线:会话 id(请求路由 stamp)与任务 id(gate 凭据绑定)。 */
|
|
900
|
+
setIdentity(sessionId , taskId ) {
|
|
901
|
+
this.#sessionId = sessionId;
|
|
902
|
+
this.#taskId = taskId;
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
/** Agent 构造完成后回填引用:工具批的 agent 字段(fs 工具 session 解析依赖)。 */
|
|
906
|
+
setAgent(agent ) {
|
|
907
|
+
this.#agentRef = agent;
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
/** K2:回填会话工作区(tf-code resolve 透传用;factory 在 createDriver 闭包里解析)。 */
|
|
911
|
+
setSessionCwd(cwd ) {
|
|
912
|
+
this.#sessionCwd = cwd;
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
/** F6:置位 resume 停机核对("有意图无回执";零注入——只阻断,不进上下文)。 */
|
|
916
|
+
setResumeHalt(detail ) {
|
|
917
|
+
this.#resumeHalt = detail;
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
/** F6:清除停机核对(人工核对完成后的出口)。 */
|
|
921
|
+
clearResumeHalt() {
|
|
922
|
+
this.#resumeHalt = null;
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
/** F7:按句柄取回观测原文(段边界丢弃的旧段原文、命令产出等);未知句柄返回 null。
|
|
926
|
+
* 只读通道,不进上下文——供排障/回取与评测断言使用。 */
|
|
927
|
+
peekHandle(handle , fromLine = 1, toLine = Number.MAX_SAFE_INTEGER) {
|
|
928
|
+
return this.#obs.peek(handle, fromLine, toLine);
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
/**
|
|
932
|
+
* F5:命令成功回执 → 标记其 accepts 声明的验收项为已验证。
|
|
933
|
+
* 证据 = `cmdId(handle=…,fp=…)`——模型自述"已完成"不产生任何条目(无回执不验证)。
|
|
934
|
+
* 每次标记落台账;注入差分在 #buildInjections 里统一生成。
|
|
935
|
+
*/
|
|
936
|
+
#markAccepts(cmd , handle , fingerprint ) {
|
|
937
|
+
const accepts = cmd.attrs['accepts'];
|
|
938
|
+
if (accepts === undefined || this.#plan === null || !this.#cfg.enablePlan) return;
|
|
939
|
+
for (const rawId of accepts.split(',')) {
|
|
940
|
+
const id = rawId.trim();
|
|
941
|
+
if (id === '') continue;
|
|
942
|
+
const item = this.#plan.items.get(id);
|
|
943
|
+
if (item === undefined || item.status === 'verified') continue;
|
|
944
|
+
item.status = 'verified';
|
|
945
|
+
item.evidence = `${cmd.id}(handle=${handle ?? '-'} fp=${fingerprint})`;
|
|
946
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'plan-accept', acceptId: id, cmdId: cmd.id, evidence: item.evidence });
|
|
947
|
+
this.#ledgerWrite('plugin:tf-agent/plan', { revision: this.#plan.revision, verified: id, cmdId: cmd.id, evidence: item.evidence });
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
/** Agent 作用域的工具执行器重绑(桌面端 preset 层):
|
|
952
|
+
* web/desktop 组合把 tool-fs/tool-pwsh 从宿主平面挪进 agent preset 层(standard.patch.yml),
|
|
953
|
+
* entry 根 ctx 的 tools 服务解析不到 write/edit/bash → "unknown tool"。
|
|
954
|
+
* setup(preset 绑定)完成后用 agentCtx 的 tools 服务重绑;headless 回退根服务不变。 */
|
|
955
|
+
setToolsExecutor(execute ) {
|
|
956
|
+
this.#ports = { ...this.#ports, executeTools: execute };
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
snapshot() {
|
|
960
|
+
const obs = this.#obs;
|
|
961
|
+
return {
|
|
962
|
+
records: [...this.#records],
|
|
963
|
+
counters: () => {
|
|
964
|
+
const c = obs.counters();
|
|
965
|
+
return { injected: c.injected, produced: c.produced, peeked: c.peeked, injectedRatio: obs.injectedRatio() };
|
|
966
|
+
},
|
|
967
|
+
usage: { ...this.#usage },
|
|
968
|
+
requestCount: this.#requestCount,
|
|
969
|
+
stableHashes: [...this.#stableHashes],
|
|
970
|
+
};
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
// ------------------------------------------------------------------ 评测 dump(08 号 METRICS.md M3)
|
|
974
|
+
|
|
975
|
+
/**
|
|
976
|
+
* env STREAM_LOOP_EVAL_DUMP 门控:turn 结束把 snapshot 落 JSON 文件(<prefix>-turn<N>.json)。
|
|
977
|
+
* injected_ratio 权威口径的取证来源(07 号 §3.2 裁定:驱动器 snapshot 为准);
|
|
978
|
+
* 写入失败只告警不抛(fail-open,红线 5——记账不毁任务)。未设 env 时零开销直返。
|
|
979
|
+
*/
|
|
980
|
+
#dumpEval(turn , reason ) {
|
|
981
|
+
const prefix = process.env.STREAM_LOOP_EVAL_DUMP;
|
|
982
|
+
if (prefix === undefined || prefix === '') return;
|
|
983
|
+
try {
|
|
984
|
+
const snap = this.snapshot();
|
|
985
|
+
writeFileSync(
|
|
986
|
+
`${prefix}-turn${turn}.json`,
|
|
987
|
+
JSON.stringify({
|
|
988
|
+
sessionId: this.#sessionId, taskId: this.#taskId, turn, turnEndReason: reason,
|
|
989
|
+
requestCount: snap.requestCount, usage: snap.usage, stableHashes: snap.stableHashes,
|
|
990
|
+
counters: snap.counters(), records: snap.records,
|
|
991
|
+
}, null, 2),
|
|
992
|
+
);
|
|
993
|
+
} catch (error) {
|
|
994
|
+
this.#warn('eval dump 写入失败(fail-open)', error);
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
// ------------------------------------------------------------------ O5 阶梯
|
|
999
|
+
|
|
1000
|
+
/** 任务级 token 预算阶梯(README O5:<70% normal;70-90% high-only;>90% final-only)。 */
|
|
1001
|
+
budgetLevel() {
|
|
1002
|
+
const budget = this.#cfg.budgetTokens;
|
|
1003
|
+
if (budget === undefined || budget <= 0) return 'normal';
|
|
1004
|
+
const spent = this.#usage.inputTokens + this.#usage.outputTokens + Math.ceil(this.#injectedChars / 4);
|
|
1005
|
+
if (spent >= budget * 0.9) return 'final-only';
|
|
1006
|
+
if (spent >= budget * 0.7) return 'high-only';
|
|
1007
|
+
return 'normal';
|
|
1008
|
+
}
|
|
1009
|
+
|
|
1010
|
+
// ------------------------------------------------------------------ 任务入口
|
|
1011
|
+
|
|
1012
|
+
/** 追加一条用户任务(Agent.followup 的驱动器侧入口:只进装配历史,不发请求)。
|
|
1013
|
+
* F7:记录当前任务块的起始下标——段边界只丢弃它之前的旧段(整块、完整回合边界)。 */
|
|
1014
|
+
pushUserTask(text ) {
|
|
1015
|
+
this.#segmentKeepFrom = this.#renderer.appendBlockCount;
|
|
1016
|
+
this.#renderer.appendHistory({ role: 'user', content: text });
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
/** 运行中回合的 steer 入口(修复限制 2):下一请求装配时进追加区(对齐内建
|
|
1020
|
+
* "注入运行中回合的下一步");流内不打断的前提不变——当前流跑完才装配。 */
|
|
1021
|
+
pushSteer(text , message ) {
|
|
1022
|
+
this.#pendingSteers.push({ text, message });
|
|
1023
|
+
}
|
|
1024
|
+
|
|
1025
|
+
/** 尚未消费(未进装配历史)的 steer 的原始消息(Agent.inbox.nextStep 的如实暴露面)。 */
|
|
1026
|
+
get pendingSteerMessages() {
|
|
1027
|
+
return this.#pendingSteers.map((s) => s.message);
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
/**
|
|
1031
|
+
* resume 重放(修复限制 4 的另一半):把上一会话的 tf-* 台账事实回灌驱动器。
|
|
1032
|
+
* 只回放 'plugin:tf-agent/final'(finalCandidates → 最终答案跨 resume 可用)。
|
|
1033
|
+
* 刻意不回放命令记录:属性不回放则幂等指纹永不匹配,回放反而会占用 id 命名空间
|
|
1034
|
+
* 挡住合法重发;旧失败也不该在新回合里当作重入事由重新上报。finalCandidates
|
|
1035
|
+
* 不进 #commands,因此重放不会让 #finalSeen 立即为真——新回合仍须模型自己收尾。
|
|
1036
|
+
*/
|
|
1037
|
+
rehydrateRecords(records ) {
|
|
1038
|
+
let applied = 0;
|
|
1039
|
+
let skipped = 0;
|
|
1040
|
+
for (const rec of records) {
|
|
1041
|
+
const data = (rec.data !== null && typeof rec.data === 'object' ? rec.data : undefined) ;
|
|
1042
|
+
if (rec.kind !== 'plugin:tf-agent/final' || data === undefined || typeof data['summary'] !== 'string') {
|
|
1043
|
+
skipped += 1;
|
|
1044
|
+
continue;
|
|
1045
|
+
}
|
|
1046
|
+
const cmdId = typeof data['cmdId'] === 'string' ? data['cmdId'] : `replayed-final-${applied + 1}`;
|
|
1047
|
+
const existing = this.#finalCandidates.find((c) => c.cmdId === cmdId);
|
|
1048
|
+
if (existing !== undefined) {
|
|
1049
|
+
existing.summary = data['summary']; // 同 id 携带新 summary = 覆盖(与运行中 last-wins 语义一致)
|
|
1050
|
+
} else {
|
|
1051
|
+
this.#finalCandidates.push({ cmdId, summary: data['summary'], turn: 0, step: 0 });
|
|
1052
|
+
}
|
|
1053
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'final', summary: data['summary'] });
|
|
1054
|
+
applied += 1;
|
|
1055
|
+
}
|
|
1056
|
+
return { applied, skipped };
|
|
1057
|
+
}
|
|
1058
|
+
|
|
1059
|
+
/** 外部取消(Agent.cancel 的入口):中断当前流与在途请求,并 abort 回合 signal
|
|
1060
|
+
* (K4:取消传导到工具派发与 tf-code runtime;abort 后由 drain 等待在途清理再收束)。 */
|
|
1061
|
+
cancel(reason ) {
|
|
1062
|
+
this.#aborted = true;
|
|
1063
|
+
this.#abortReason = reason;
|
|
1064
|
+
for (const controller of this.#activeControllers) {
|
|
1065
|
+
controller.abort(reason instanceof Error ? reason : new Error(String(reason)));
|
|
1066
|
+
}
|
|
1067
|
+
this.#turnController?.abort(reason instanceof Error ? reason : new Error(String(reason)));
|
|
1068
|
+
}
|
|
1069
|
+
|
|
1070
|
+
/** K4:回合 signal(runTurn 期间有效;缺省 = 一次性从未触发的 controller,兼容直派发路径)。 */
|
|
1071
|
+
#commandSignal() {
|
|
1072
|
+
return this.#turnController?.signal ?? new AbortController().signal;
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
/** 跑一个回合(从当前装配历史到 FINISH/blocked)。异常一律上抛(fail-open,红线 5)。 */
|
|
1076
|
+
async runTurn() {
|
|
1077
|
+
// F6:resume 停机核对——"有意图无回执"时不发任何请求(零注入),直接 blocked,
|
|
1078
|
+
// 由用户核对意图日志(CLI `dsh-stream-agent intents`)后决定继续或放弃。
|
|
1079
|
+
if (this.#resumeHalt !== null) {
|
|
1080
|
+
const reason = { kind: 'blocked', detail: `resume 停机核对(F6):${this.#resumeHalt}——存在写前意图无回执,不自动重放;请人工核对后重试(CLI: dsh-stream-agent intents)。` };
|
|
1081
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'fault', fault: 'resume-halt-pending-intents', detail: reason.kind === 'blocked' ? reason.detail : undefined });
|
|
1082
|
+
this.#ledgerWrite('plugin:tf-agent/fault', { fault: 'resume-halt-pending-intents', turn: this.#turnCounter + 1 });
|
|
1083
|
+
this.#ports.events?.turnEnd(this.#turnCounter + 1, reason);
|
|
1084
|
+
return reason;
|
|
1085
|
+
}
|
|
1086
|
+
const turn = ++this.#turnCounter;
|
|
1087
|
+
const controller = new AbortController();
|
|
1088
|
+
this.#turnController = controller;
|
|
1089
|
+
// F7 长会话段边界:追加区超过阈值时,在新回合开始处整块丢弃旧段(保留当前任务块起
|
|
1090
|
+
// 的全部块)。被丢弃原文句柄化登记(可 tf-peek 回取),显式记录缓存重置点。
|
|
1091
|
+
if (this.#cfg.segmentMaxChars > 0 && this.#segmentKeepFrom > 0 && this.#renderer.appendChars > this.#cfg.segmentMaxChars) {
|
|
1092
|
+
const before = this.#renderer.appendChars;
|
|
1093
|
+
const { dropped } = this.#renderer.dropAppendHead(this.#segmentKeepFrom, {
|
|
1094
|
+
reason: `append chars ${before} > segmentMaxChars ${this.#cfg.segmentMaxChars}(turn ${turn} 开始处,完整回合边界)`,
|
|
1095
|
+
});
|
|
1096
|
+
for (const [i, text] of dropped.entries()) {
|
|
1097
|
+
// 句柄化登记(obs:first observation → high,但不在命令通道上,永不自动注入;
|
|
1098
|
+
// tf-peek 按句柄取回原文——"原文可按 request:N 回取"的落地形态)
|
|
1099
|
+
this.#obs.observe({
|
|
1100
|
+
tool: 'tf-read',
|
|
1101
|
+
ok: true,
|
|
1102
|
+
key: `segment:turn${turn}:${i}`,
|
|
1103
|
+
content: text,
|
|
1104
|
+
callId: `seg-t${turn}-${i}`,
|
|
1105
|
+
});
|
|
1106
|
+
}
|
|
1107
|
+
this.#record({
|
|
1108
|
+
seq: ++DRIVER_SEQ, kind: 'observation',
|
|
1109
|
+
handle: dropped.length > 0 ? `obs:read:seg-t${turn}-0@v1` : null,
|
|
1110
|
+
key: `segment:turn${turn}`, infoGain: 'low', reason: 'segment-drop-handleized',
|
|
1111
|
+
});
|
|
1112
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'fault', fault: 'segment-drop', detail: `dropped ${dropped.length} blocks (${before} chars) at turn ${turn} boundary; originals handleized (obs:read:seg-t${turn}-*)` });
|
|
1113
|
+
this.#ledgerWrite('plugin:tf-agent/fault', { fault: 'segment-drop', turn, droppedBlocks: dropped.length, chars: before });
|
|
1114
|
+
this.#segmentKeepFrom = 0;
|
|
1115
|
+
}
|
|
1116
|
+
debugTrace('turn.start', { turn });
|
|
1117
|
+
try {
|
|
1118
|
+
try {
|
|
1119
|
+
this.#ports.events?.turnStart(turn);
|
|
1120
|
+
const reason = await this.#turnLoop(turn);
|
|
1121
|
+
this.#dumpEval(turn, reason);
|
|
1122
|
+
return reason;
|
|
1123
|
+
} catch (error) {
|
|
1124
|
+
const failure = {
|
|
1125
|
+
kind: 'error',
|
|
1126
|
+
error: { message: error instanceof Error ? error.message : String(error), code: 'DRIVER_ERROR' },
|
|
1127
|
+
};
|
|
1128
|
+
this.#dumpEval(turn, failure);
|
|
1129
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'fault', fault: 'driver-error', detail: failure.error.message });
|
|
1130
|
+
this.#ledgerWrite('plugin:tf-agent/fault', { fault: 'driver-error', detail: failure.error.message, turn });
|
|
1131
|
+
try {
|
|
1132
|
+
this.#ports.events?.turnEnd(turn, failure);
|
|
1133
|
+
} catch (eventError) {
|
|
1134
|
+
this.#warn('turn/end 事件写入失败', eventError);
|
|
1135
|
+
}
|
|
1136
|
+
throw error;
|
|
1137
|
+
}
|
|
1138
|
+
} finally {
|
|
1139
|
+
// K4:回合收束前等待在途命令清理完成(0 后置写),再释放回合 signal。
|
|
1140
|
+
await this.#drain();
|
|
1141
|
+
// v0.3.2:回合已结束但最后一步的易变尾还没轮到"下一请求"转正——在此收编,
|
|
1142
|
+
// 保证下个回合(或 resume 后的同会话)仍能看到最后一步的观测事实。
|
|
1143
|
+
if (this.#deliveredTail !== null && this.#deliveredTail.turn === turn) {
|
|
1144
|
+
this.#commitDeliveredTail();
|
|
1145
|
+
}
|
|
1146
|
+
if (this.#turnController === controller) this.#turnController = null;
|
|
1147
|
+
}
|
|
1148
|
+
}
|
|
1149
|
+
|
|
1150
|
+
// ------------------------------------------------------------------ 回合主循环
|
|
1151
|
+
|
|
1152
|
+
async #turnLoop(turn ) {
|
|
1153
|
+
let step = 0;
|
|
1154
|
+
// 防震荡护栏按回合重置(maxReentries / final nudge / final-only 档都是回合级护栏)——
|
|
1155
|
+
// 不重置的话,多任务长会话会在第 N 个回合被历史累计计数误杀(F7 长会话测试实抓)。
|
|
1156
|
+
this.#reentryCount = 0;
|
|
1157
|
+
this.#finalNudges = 0;
|
|
1158
|
+
this.#nudgeMark = null;
|
|
1159
|
+
this.#finalOnlyRequests = 0;
|
|
1160
|
+
// v0.3.1:final 收束闸的回合级状态(命令序按回合重置——上一回合的 final 不得收敛本回合)
|
|
1161
|
+
this.#cmdOrder = 0;
|
|
1162
|
+
this.#lastFinalOrder = 0;
|
|
1163
|
+
this.#lastNonFinalOrder = 0;
|
|
1164
|
+
this.#reportedFinalRejects.clear();
|
|
1165
|
+
this.#pendingReplays = [];
|
|
1166
|
+
this.#replays = 0;
|
|
1167
|
+
this.#replayCapped = false;
|
|
1168
|
+
this.#truncationRetries = 0;
|
|
1169
|
+
this.#truncation = null;
|
|
1170
|
+
let reason = { kind: 'blocked', detail: 'turn loop exited without convergence' };
|
|
1171
|
+
|
|
1172
|
+
while (true) {
|
|
1173
|
+
// v0.3.2:上一步的正文 + 命令摘要先落追加区(assistant/message 语义),再发下一请求。
|
|
1174
|
+
// 顺序刻意为"摘要 → 易变尾":模型看到的时间线与真实发生顺序一致。
|
|
1175
|
+
this.#commitStepDigest();
|
|
1176
|
+
// ---- steer 注入(修复限制 2):运行中到达的 steer 在下一请求(内建的"下一步")生效
|
|
1177
|
+
// ——进追加区(只追加,前缀单调不破);流内不打断:当前流早已跑完才会走到这里。
|
|
1178
|
+
if (this.#pendingSteers.length > 0) {
|
|
1179
|
+
const steers = this.#pendingSteers.splice(0);
|
|
1180
|
+
for (const s of steers) {
|
|
1181
|
+
this.#renderer.appendHistory({
|
|
1182
|
+
role: 'user',
|
|
1183
|
+
content: `[tf-stream:steer]\n${s.text}\n(用户在回合进行中插入的指令;与本回合后续工作冲突时,以本指令为准)`,
|
|
1184
|
+
});
|
|
1185
|
+
}
|
|
1186
|
+
}
|
|
1187
|
+
const level = this.budgetLevel();
|
|
1188
|
+
step += 1;
|
|
1189
|
+
try {
|
|
1190
|
+
this.#ports.events?.stepStart(turn, step);
|
|
1191
|
+
} catch (error) {
|
|
1192
|
+
this.#warn('step/start 事件写入失败', error);
|
|
1193
|
+
}
|
|
1194
|
+
|
|
1195
|
+
// ---- REQUEST:装配 + O6 preflight(render() 内置断言,违反即抛 → fail-closed)----
|
|
1196
|
+
const messages = this.#renderer.render();
|
|
1197
|
+
// v0.3.2:刚刚发出去的易变尾(上一步的观测/错误/原生结果)转正为追加区历史——
|
|
1198
|
+
// 下一次请求仍可见(缓存读),不再"注入一次就消失"。只追加,前缀单调性不变。
|
|
1199
|
+
this.#commitDeliveredTail();
|
|
1200
|
+
const stableHash = this.#renderer.stableHash();
|
|
1201
|
+
this.#stableHashes.push(stableHash);
|
|
1202
|
+
const fullHash = renderHash(messages);
|
|
1203
|
+
this.#record({
|
|
1204
|
+
seq: ++DRIVER_SEQ, kind: 'request', turn, step,
|
|
1205
|
+
provider: this.#cfg.provider, model: this.#cfg.model,
|
|
1206
|
+
level, stableHash, renderHash: fullHash,
|
|
1207
|
+
injectionBlocks: 0,
|
|
1208
|
+
});
|
|
1209
|
+
|
|
1210
|
+
// ---- STREAMING:逐 delta 消费;命令闭合即派发,不结束流 ----
|
|
1211
|
+
const streamOutcome = await this.#consumeStream(turn, step, messages, level);
|
|
1212
|
+
|
|
1213
|
+
// 不可重试的流错误(凭据/配置层):fail-fast 终止回合,不进重入循环
|
|
1214
|
+
if (streamOutcome.finish.kind === 'error' && NON_RETRYABLE_STREAM_CODES.has(finishCode(streamOutcome.finish))) {
|
|
1215
|
+
// v0.3.0:step/end 之前必须等在途工具落定——流中途已派发的 tool/call 若在
|
|
1216
|
+
// step/end 之后才写 tool/result,v4 校验会判"tool/call 不在打开的 step 内"→ corrupt。
|
|
1217
|
+
await this.#drain();
|
|
1218
|
+
try {
|
|
1219
|
+
this.#ports.events?.stepEnd(turn, step);
|
|
1220
|
+
} catch (error) {
|
|
1221
|
+
this.#warn('step/end 事件写入失败', error);
|
|
1222
|
+
}
|
|
1223
|
+
reason = { kind: 'error', error: { message: finishMessage(streamOutcome.finish), code: finishCode(streamOutcome.finish) } };
|
|
1224
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'fault', fault: 'stream-fatal', detail: finishDetail(streamOutcome.finish) });
|
|
1225
|
+
this.#ledgerWrite('plugin:tf-agent/fault', { fault: 'stream-fatal', code: finishCode(streamOutcome.finish), detail: finishDetail(streamOutcome.finish), turn });
|
|
1226
|
+
break;
|
|
1227
|
+
}
|
|
1228
|
+
|
|
1229
|
+
// ---- 等 drain(F8 普通异步等待)----
|
|
1230
|
+
await this.#drain();
|
|
1231
|
+
await this.#resolveDeferredPeeks(turn, step);
|
|
1232
|
+
// v0.3.0:step/end 推迟到"收束判定"之后——final 答案是 assistant/message,
|
|
1233
|
+
// v4 格式要求它落在打开的 turn+step 内;此前在 step/end 之后写会被判
|
|
1234
|
+
// "assistant/message does not match an open turn and step" → 整条会话 corrupt。
|
|
1235
|
+
|
|
1236
|
+
// ---- 收束判定(仅三种重入事由:失败/拒绝、high 观测、peek 需求)----
|
|
1237
|
+
const issues = this.#collectIssues();
|
|
1238
|
+
const injections = this.#buildInjections(issues, level);
|
|
1239
|
+
// v0.3.2 截断修复:输出在命令中途被截断(max-tokens / 流异常终止 / DSML 块未闭合)时,
|
|
1240
|
+
// 0.3.1 只记一条 truncated 台账、不产生任何重入事由——模型以为任务结束,用户看到
|
|
1241
|
+
// 半截输出。这里强制一次续写注入(带上已生成内容尾部,便于从断点续写);
|
|
1242
|
+
// 回合级上限 MAX_TRUNCATION_RETRIES,超限如实 blocked,不无限烧请求。
|
|
1243
|
+
if (this.#truncation !== null && level !== 'final-only' && this.#truncationRetries < MAX_TRUNCATION_RETRIES) {
|
|
1244
|
+
this.#truncationRetries += 1;
|
|
1245
|
+
injections.blocks.push({ role: 'user', content: truncationNudge(this.#truncation) });
|
|
1246
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'fault', fault: 'output-truncated', detail: `${this.#truncation.reason}(第 ${this.#truncationRetries} 次续写)` });
|
|
1247
|
+
this.#ledgerWrite('plugin:tf-agent/fault', { fault: 'output-truncated', reason: this.#truncation.reason, retry: this.#truncationRetries, turn });
|
|
1248
|
+
}
|
|
1249
|
+
// 饥饿防线(07 号结果 §3.6 上报的断链,08 号评测前按其建议修复):
|
|
1250
|
+
// 升格骨架接入注入通路(按 high 观测同款格式;final-only 档不注入——预算已枯竭)。
|
|
1251
|
+
const promoted = this.#obs.noteStep(injections.highInjected);
|
|
1252
|
+
if (promoted !== null && level !== 'final-only' && !this.#reportedObservations.has(promoted.seq)) {
|
|
1253
|
+
this.#reportedObservations.add(promoted.seq);
|
|
1254
|
+
injections.blocks.push({
|
|
1255
|
+
role: 'user',
|
|
1256
|
+
content: `[tf-stream:observation handle=${promoted.handle ?? ''} key=starvation-promoted]\n${(promoted.payload ).rendered ?? ''}\n(细节用 tf-peek handle="${promoted.handle}" from_line=.. to_line=.. 取回)`,
|
|
1257
|
+
});
|
|
1258
|
+
}
|
|
1259
|
+
|
|
1260
|
+
if (streamOutcome.finish.kind === 'error' || streamOutcome.finish.kind === 'aborted') {
|
|
1261
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'fault', fault: `stream-${streamOutcome.finish.kind}`, detail: finishDetail(streamOutcome.finish) });
|
|
1262
|
+
this.#ledgerWrite('plugin:tf-agent/fault', { fault: `stream-${streamOutcome.finish.kind}`, detail: finishDetail(streamOutcome.finish), turn });
|
|
1263
|
+
}
|
|
1264
|
+
|
|
1265
|
+
// ---- final 收束闸(真连 R3/R4 教训 + v0.3.1 截断修复)----
|
|
1266
|
+
// 四类拒绝,任一成立都说明"这条 final 不能作为交付答案":
|
|
1267
|
+
// ① depends_on 未满足 / ② 仍有命令未完成(原有过早判定)
|
|
1268
|
+
// ③ summary 是占位(placeholder / 占位 / 空……)—— 0.3.1 真机证据:写成
|
|
1269
|
+
// `summary="placeholder"` 的 final 被照单全收,用户侧看到的就是"截断 + 一句占位"
|
|
1270
|
+
// ④ 这条 final 之后又发过命令 —— 模型写完 final 又继续干活,旧答案已过期,
|
|
1271
|
+
// 必须在本流末尾重新声明(0.3.1 同一会话:第 4 步的 final 被第 7 步复用为答案)
|
|
1272
|
+
// 拒绝只注入一次(同 cmdId+kind):二次不放行、也不重复烧注入,交给 nudge 护栏收束。
|
|
1273
|
+
const candidate = this.#finalCandidates.length > 0 ? this.#finalCandidates[this.#finalCandidates.length - 1] : undefined;
|
|
1274
|
+
// 回合归属:上一回合的 final(或 resume 回放 turn=0)不得充当本回合答案
|
|
1275
|
+
const lastFinal = candidate !== undefined && candidate.turn === turn ? candidate : undefined;
|
|
1276
|
+
let prematureFinal ;
|
|
1277
|
+
let rejectedFinal ;
|
|
1278
|
+
if (lastFinal !== undefined && level !== 'final-only') {
|
|
1279
|
+
const finalRec = this.#commands.get(lastFinal.cmdId);
|
|
1280
|
+
const unmetDeps = (finalRec?.cmd.depends_on ?? []).filter((d) => this.#commands.get(d)?.status !== 'ok');
|
|
1281
|
+
const unfinished = [...this.#commands.values()].filter((r) => r.cmd.name !== 'tf-final' && (r.status === 'pending' || r.status === 'dispatched'));
|
|
1282
|
+
prematureFinal = unmetDeps.length > 0
|
|
1283
|
+
? `tf-final 过早:depends_on 未满足(${unmetDeps.join(', ')})`
|
|
1284
|
+
: unfinished.length > 0
|
|
1285
|
+
? 'tf-final 过早:仍有命令未完成'
|
|
1286
|
+
: undefined;
|
|
1287
|
+
// F5:计划存在且还有未验证的验收项 → tf-final 过早(缺项或未验证不得标完成;
|
|
1288
|
+
// 验证只能来自命令成功回执,模型自述不算)。
|
|
1289
|
+
if (prematureFinal === undefined && this.#cfg.enablePlan && this.#plan !== null) {
|
|
1290
|
+
const open = [...this.#plan.items.entries()].filter(([, item]) => item.status === 'open');
|
|
1291
|
+
if (open.length > 0) {
|
|
1292
|
+
prematureFinal = `tf-final 过早:计划有 ${open.length} 项验收未验证(${open.map(([id]) => id).join(', ')})——完成对应命令并用 accepts="..." 声明回执,或用 tf-plan 修订计划(显式移除不再需要的项)。`;
|
|
1293
|
+
}
|
|
1294
|
+
}
|
|
1295
|
+
// ③④ 内容面:占位 summary / 过期 final
|
|
1296
|
+
let hardIssue ;
|
|
1297
|
+
if (prematureFinal === undefined) {
|
|
1298
|
+
const summaryIssue = checkFinalSummary(lastFinal.summary);
|
|
1299
|
+
if (summaryIssue !== null) {
|
|
1300
|
+
hardIssue = { kind: summaryIssue.kind, detail: `tf-final 无效:${summaryIssue.detail}` };
|
|
1301
|
+
} else if (this.#lastFinalOrder > 0 && this.#lastNonFinalOrder > this.#lastFinalOrder) {
|
|
1302
|
+
hardIssue = {
|
|
1303
|
+
kind: 'stale',
|
|
1304
|
+
detail: 'tf-final 无效:这条 final 之后又发出了命令(答案已过期)——请在本流末尾用新 id 重新输出 tf-final,summary 写最终答案原文',
|
|
1305
|
+
};
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
if (hardIssue !== undefined) {
|
|
1309
|
+
// key 只按 kind:换新 id 再写一次占位/过期 final,是同一个毛病,不再重复烧注入
|
|
1310
|
+
if (this.#reportedFinalRejects.has(hardIssue.kind)) {
|
|
1311
|
+
// 已提示过仍未改:不重复注入,也不放行收敛(走 nudge / blocked,如实收场)
|
|
1312
|
+
rejectedFinal = hardIssue.detail;
|
|
1313
|
+
} else {
|
|
1314
|
+
this.#reportedFinalRejects.add(hardIssue.kind);
|
|
1315
|
+
prematureFinal = hardIssue.detail;
|
|
1316
|
+
}
|
|
1317
|
+
}
|
|
1318
|
+
}
|
|
1319
|
+
|
|
1320
|
+
const finalSeen = lastFinal !== undefined && prematureFinal === undefined && rejectedFinal === undefined;
|
|
1321
|
+
// steer 在本流期间到达 → 不能带着未消费的 steer 收敛(对齐内建:插话必须被下一步看到)
|
|
1322
|
+
const pendingSteerCount = this.#pendingSteers.length;
|
|
1323
|
+
const needsReentry = issues.length > 0 || injections.blocks.length > 0 || prematureFinal !== undefined || pendingSteerCount > 0;
|
|
1324
|
+
|
|
1325
|
+
if (prematureFinal !== undefined && lastFinal !== undefined) {
|
|
1326
|
+
// v0.3.2:计划门槛拒绝时附上计划快照——模型看不到计划内容就无法验收
|
|
1327
|
+
//(真机里计划只在创建那一步的易变尾出现过一次,随后彻底消失)。
|
|
1328
|
+
const planBlock = prematureFinal.includes('计划') ? this.#planSnapshot() : '';
|
|
1329
|
+
injections.blocks.push({
|
|
1330
|
+
role: 'user' ,
|
|
1331
|
+
content: `[tf-stream:error id=${lastFinal.cmdId} cmd=tf-final] ${prematureFinal}\n`
|
|
1332
|
+
+ (planBlock !== '' ? `当前计划:\n${planBlock}\n` : '')
|
|
1333
|
+
+ '建议:先取回所需结果(tf-peek)或补齐未完成命令,然后在流末尾用新 id 重发 tf-final;summary 必须包含最终答案原文(数字/行内容/路径/结论),不得占位。',
|
|
1334
|
+
});
|
|
1335
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'fault', fault: 'premature-final', detail: prematureFinal });
|
|
1336
|
+
this.#ledgerWrite('plugin:tf-agent/fault', { fault: 'premature-final', detail: prematureFinal, turn });
|
|
1337
|
+
}
|
|
1338
|
+
|
|
1339
|
+
if (finalSeen && !needsReentry) {
|
|
1340
|
+
// 成功路径:零注入,只写 ledger —— 分派 06 核心命题
|
|
1341
|
+
reason = { kind: 'completed' };
|
|
1342
|
+
// 最终答案落会话:headless 输出与评测 checks 消费最后一条 assistant 消息。
|
|
1343
|
+
// v0.3.0:必须在 step/end 之前写(v4 的 assistant/message 要求打开的 turn+step)。
|
|
1344
|
+
if (lastFinal !== undefined && lastFinal.summary.trim() !== '') {
|
|
1345
|
+
try {
|
|
1346
|
+
this.#ports.events?.finalAnswer?.(turn, step, lastFinal.summary);
|
|
1347
|
+
} catch (error) {
|
|
1348
|
+
this.#warn('final 答案消息写入失败', error);
|
|
1349
|
+
}
|
|
1350
|
+
}
|
|
1351
|
+
try {
|
|
1352
|
+
this.#ports.events?.stepEnd(turn, step);
|
|
1353
|
+
} catch (error) {
|
|
1354
|
+
this.#warn('step/end 事件写入失败', error);
|
|
1355
|
+
}
|
|
1356
|
+
break;
|
|
1357
|
+
}
|
|
1358
|
+
|
|
1359
|
+
// 非成功路径(重入 / 阻断 / 取消):本步到此结束
|
|
1360
|
+
try {
|
|
1361
|
+
this.#ports.events?.stepEnd(turn, step);
|
|
1362
|
+
} catch (error) {
|
|
1363
|
+
this.#warn('step/end 事件写入失败', error);
|
|
1364
|
+
}
|
|
1365
|
+
|
|
1366
|
+
const finalOnlyGate = level === 'final-only' && this.#finalOnlyRequests >= 1;
|
|
1367
|
+
// v0.3.2:nudge 进度感知护栏。nudge 不再是一次性预算——被提示后模型**继续产出**
|
|
1368
|
+
// (新 ok 命令)就不算"提示失效",绝不因此中断生产性工作;只有"零产出的连续
|
|
1369
|
+
// nudge"(真打转)才 blocked。整体仍由 maxReentries / O5 预算阶梯兜底。
|
|
1370
|
+
// 真机取证(session-8f22c7a0):旧语义下 nudge 在写文件步被消耗,随后的崩溃步
|
|
1371
|
+
// (或任何无注入的写步)直接 nudgeExhausted → 任务中断。
|
|
1372
|
+
const okCommandCount = [...this.#commands.values()].filter((r) => r.status === 'ok').length;
|
|
1373
|
+
const progressSinceNudge = this.#nudgeMark === null || okCommandCount > this.#nudgeMark;
|
|
1374
|
+
const nudgeExhausted = !needsReentry && !finalSeen && this.#finalNudges >= 1 && !progressSinceNudge;
|
|
1375
|
+
if (this.#aborted || finalOnlyGate || nudgeExhausted || this.#reentryCount >= this.#cfg.maxReentries) {
|
|
1376
|
+
if (this.#aborted) {
|
|
1377
|
+
reason = { kind: 'aborted', reason: this.#abortReason instanceof Error ? this.#abortReason.message : String(this.#abortReason ?? 'cancelled') };
|
|
1378
|
+
} else if (finalOnlyGate) {
|
|
1379
|
+
reason = { kind: 'blocked', detail: '预算进入 final-only 档:停止一切注入,降级交付(已完成/未完成见台账)' };
|
|
1380
|
+
} else if (nudgeExhausted) {
|
|
1381
|
+
reason = {
|
|
1382
|
+
kind: 'blocked',
|
|
1383
|
+
detail: rejectedFinal !== undefined
|
|
1384
|
+
? `final 被拒且未重发(${rejectedFinal}):不把占位/过期答案当交付`
|
|
1385
|
+
: '流终止且无 tf-final、无重入事由(提示一次后仍未收敛)',
|
|
1386
|
+
};
|
|
1387
|
+
} else {
|
|
1388
|
+
reason = { kind: 'blocked', detail: `重入次数达到上限 ${this.#cfg.maxReentries}` };
|
|
1389
|
+
}
|
|
1390
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'fault', fault: 'turn-blocked', detail: reason.kind === 'blocked' ? reason.detail : reason.kind });
|
|
1391
|
+
break;
|
|
1392
|
+
}
|
|
1393
|
+
|
|
1394
|
+
// ---- INJECTING:O3 句柄目录差分(追加区)+ 易变尾注入,发下一请求 ----
|
|
1395
|
+
const delta = this.#obs.directoryDelta(this.#deltaCursor);
|
|
1396
|
+
const maxSeq = [...delta.added, ...delta.changed, ...delta.stale].reduce((m, e) => Math.max(m, e.seq), this.#deltaCursor);
|
|
1397
|
+
this.#deltaCursor = maxSeq;
|
|
1398
|
+
this.#renderer.appendHandleDelta(delta);
|
|
1399
|
+
|
|
1400
|
+
let tail = injections.blocks;
|
|
1401
|
+
// v0.3.1:重复命令的原结果回灌。只在此处(确实要发下一请求)才物化——
|
|
1402
|
+
// 上面所有收敛/阻断分支都已 break,不会白记账、也不会白读内容。
|
|
1403
|
+
const replays = this.#materializeReplays();
|
|
1404
|
+
if (replays.length > 0) tail = [...tail, ...replays];
|
|
1405
|
+
if (tail.length === 0 && !finalSeen) {
|
|
1406
|
+
if (level === 'final-only') {
|
|
1407
|
+
// O5 >90% 档:停止一切注入,输出降级交付(已完成/未完成/已排除见台账),只收 tf-final
|
|
1408
|
+
tail = [{
|
|
1409
|
+
role: 'user' ,
|
|
1410
|
+
content: `[tf-stream:degraded] 预算已进入 final-only 档:停止一切注入。请根据台账现状立即输出 tf-final 结束任务;未完成项将在交付说明中列为未完成。`,
|
|
1411
|
+
}];
|
|
1412
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'fault', fault: 'degraded-delivery' });
|
|
1413
|
+
this.#ledgerWrite('plugin:tf-agent/fault', { fault: 'degraded-delivery', turn });
|
|
1414
|
+
} else {
|
|
1415
|
+
// 无重入事由但也没 tf-final:进度感知提示(护栏防无限循环——真打转由
|
|
1416
|
+
// nudgeExhausted 的"零产出"判定收束,不靠提示次数)。
|
|
1417
|
+
this.#finalNudges += 1;
|
|
1418
|
+
this.#nudgeMark = [...this.#commands.values()].filter((r) => r.status === 'ok').length;
|
|
1419
|
+
tail = [{
|
|
1420
|
+
role: 'user' ,
|
|
1421
|
+
content: rejectedFinal !== undefined
|
|
1422
|
+
? `[tf-stream:nudge] 上一条 tf-final 被拒(${rejectedFinal})。请继续任务并在流末尾用新 id 重发 tf-final,summary 写最终答案原文;任务确实没做完就如实写明未完成项。`
|
|
1423
|
+
: '[tf-stream:nudge] 输出已终止但未收到 tf-final。若任务已完成请输出 tf-final;否则继续输出剩余 tf-* 命令。',
|
|
1424
|
+
}];
|
|
1425
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'fault', fault: 'missing-final-nudge' });
|
|
1426
|
+
}
|
|
1427
|
+
}
|
|
1428
|
+
this.#injectedChars += tail.reduce((n, b) => n + b.content.length, 0);
|
|
1429
|
+
if (level === 'final-only') this.#finalOnlyRequests += 1;
|
|
1430
|
+
this.#renderer.setTail(tail);
|
|
1431
|
+
// v0.3.2:这批尾块会随下一请求发出;发出后由 #commitDeliveredTail 转正为历史。
|
|
1432
|
+
this.#deliveredTail = {
|
|
1433
|
+
turn,
|
|
1434
|
+
step,
|
|
1435
|
+
blocks: tail.map((b) => ({ role: (b.role ?? 'user') , content: b.content })),
|
|
1436
|
+
};
|
|
1437
|
+
this.#reentryCount += 1;
|
|
1438
|
+
}
|
|
1439
|
+
|
|
1440
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'turn-end', reason });
|
|
1441
|
+
try {
|
|
1442
|
+
this.#ports.events?.turnEnd(turn, reason);
|
|
1443
|
+
} catch (error) {
|
|
1444
|
+
this.#warn('turn/end 事件写入失败', error);
|
|
1445
|
+
}
|
|
1446
|
+
this.#ledgerWrite('plugin:tf-agent/step', { turn, steps: step, requests: this.#requestCount, usage: { ...this.#usage }, reason: reason.kind });
|
|
1447
|
+
return reason;
|
|
1448
|
+
}
|
|
1449
|
+
|
|
1450
|
+
// ------------------------------------------------------------------ 流消费
|
|
1451
|
+
|
|
1452
|
+
/** 诊断探针:会话对象的事件账面(内存事件数/末尾 seq)。 */
|
|
1453
|
+
#sessionProbe() {
|
|
1454
|
+
const session = (this.#agentRef )?.session;
|
|
1455
|
+
if (session === undefined || typeof session.snapshotEvents !== 'function') return 'no-session-probe';
|
|
1456
|
+
try {
|
|
1457
|
+
const all = session.snapshotEvents(0) ?? [];
|
|
1458
|
+
const last = all[all.length - 1];
|
|
1459
|
+
return {
|
|
1460
|
+
count: all.length,
|
|
1461
|
+
lastSeq: last?.seq,
|
|
1462
|
+
lastType: last?.type,
|
|
1463
|
+
types: all.slice(-6).map((e) => `${e.type ?? '?'}#${e.seq ?? '?'}`),
|
|
1464
|
+
};
|
|
1465
|
+
} catch (error) {
|
|
1466
|
+
return `probe-error: ${String(error)}`;
|
|
1467
|
+
}
|
|
1468
|
+
}
|
|
1469
|
+
|
|
1470
|
+
async #consumeStream(
|
|
1471
|
+
turn ,
|
|
1472
|
+
step ,
|
|
1473
|
+
messages ,
|
|
1474
|
+
level ,
|
|
1475
|
+
) {
|
|
1476
|
+
// 新流:隐式写序的流内序号清零(跨流依赖仍由 depends_on 显式声明)
|
|
1477
|
+
this.#streamSeqCounter = 0;
|
|
1478
|
+
this.#streamWrites = [];
|
|
1479
|
+
// v0.3.2:本步摘要与截断事实(续写注入 + 追加区转录用)
|
|
1480
|
+
this.#stepCommandIds = [];
|
|
1481
|
+
this.#stepNatives = [];
|
|
1482
|
+
this.#truncation = null;
|
|
1483
|
+
const parser = new TfStreamParser();
|
|
1484
|
+
const controller = new AbortController();
|
|
1485
|
+
this.#activeControllers.add(controller);
|
|
1486
|
+
let textBuf = '';
|
|
1487
|
+
this.#streamProse = '';
|
|
1488
|
+
let reasoningChars = 0;
|
|
1489
|
+
// v0.3.1:思考过程捕获(按块 index 分段,落盘时按到达序拼接为单个 reasoning 块)
|
|
1490
|
+
const reasoningParts = [];
|
|
1491
|
+
let reasoningLastIndex = null;
|
|
1492
|
+
const natives = new Map ();
|
|
1493
|
+
let finish = null;
|
|
1494
|
+
let usageSeen ;
|
|
1495
|
+
|
|
1496
|
+
// 看门狗:流空闲超时 → abort(fault-timeout 路径;消费方掐断面)
|
|
1497
|
+
const idleMs = this.#cfg.streamIdleTimeoutMs;
|
|
1498
|
+
const armWatchdog = () => {
|
|
1499
|
+
if (idleMs <= 0) return undefined;
|
|
1500
|
+
return setTimeout(() => controller.abort(new Error(`stream idle beyond ${idleMs}ms (watchdog)`)), idleMs);
|
|
1501
|
+
};
|
|
1502
|
+
let watchdog = armWatchdog();
|
|
1503
|
+
const bump = () => {
|
|
1504
|
+
if (watchdog !== undefined) {
|
|
1505
|
+
clearTimeout(watchdog);
|
|
1506
|
+
watchdog = armWatchdog();
|
|
1507
|
+
}
|
|
1508
|
+
};
|
|
1509
|
+
|
|
1510
|
+
const feed = (delta ) => {
|
|
1511
|
+
const events = parser.feed(delta);
|
|
1512
|
+
for (const event of events) this.#handleParserEvent(event, turn, step);
|
|
1513
|
+
};
|
|
1514
|
+
|
|
1515
|
+
// v0.3.1 实时帧:流开始即发 start 帧(契约见 #frameEmit)。思考过程
|
|
1516
|
+
// (reasoning-delta)逐帧透传——桌面端思考区 live 渲染的数据源。正文不逐帧透传:
|
|
1517
|
+
// 流文本是协议标记(tf-*),实时显示会把标记闪成乱码;落盘后以纯 prose 消息呈现。
|
|
1518
|
+
// 发射异常即熔断(本会话不再发),任务不受影响(fail-open)。
|
|
1519
|
+
const frameStart = () => this.#frameStartAttempt(turn, step);
|
|
1520
|
+
const frameEnd = (settlement ) =>
|
|
1521
|
+
this.#frameEndAttempt(settlement);
|
|
1522
|
+
|
|
1523
|
+
try {
|
|
1524
|
+
if (this.#cfg.provider === '' || this.#cfg.model === '') {
|
|
1525
|
+
// 无模型路由(桌面端未选择模型且无默认):失败注入引导,不静默烧流
|
|
1526
|
+
return {
|
|
1527
|
+
finish: {
|
|
1528
|
+
kind: 'error' ,
|
|
1529
|
+
message: '未解析到可用模型路由(provider/model 为空):请先在界面选择模型后重试',
|
|
1530
|
+
code: 'NO_MODEL_ROUTE',
|
|
1531
|
+
},
|
|
1532
|
+
};
|
|
1533
|
+
}
|
|
1534
|
+
const stream = this.#ports.stream({
|
|
1535
|
+
provider: this.#cfg.provider,
|
|
1536
|
+
model: this.#cfg.model,
|
|
1537
|
+
reasoningEffort: this.#cfg.reasoningEffort,
|
|
1538
|
+
messages: toWireMessages(messages),
|
|
1539
|
+
signal: controller.signal,
|
|
1540
|
+
sessionId: this.#sessionId,
|
|
1541
|
+
});
|
|
1542
|
+
this.#requestCount += 1;
|
|
1543
|
+
debugTrace('stream.call', {
|
|
1544
|
+
turn,
|
|
1545
|
+
step,
|
|
1546
|
+
provider: this.#cfg.provider,
|
|
1547
|
+
model: this.#cfg.model,
|
|
1548
|
+
messages: messages.length,
|
|
1549
|
+
sessionProbe: this.#sessionProbe(),
|
|
1550
|
+
});
|
|
1551
|
+
frameStart();
|
|
1552
|
+
|
|
1553
|
+
for await (const chunk of stream) {
|
|
1554
|
+
bump();
|
|
1555
|
+
switch (chunk.type) {
|
|
1556
|
+
case 'text-delta':
|
|
1557
|
+
textBuf += chunk.text;
|
|
1558
|
+
feed(chunk.text);
|
|
1559
|
+
break;
|
|
1560
|
+
case 'reasoning-delta': {
|
|
1561
|
+
reasoningChars += chunk.text.length; // 思维链不进协议解析,只计体积
|
|
1562
|
+
// v0.3.1:思考过程捕获 + 实时帧(桌面端思考过程 live 显示的数据源)
|
|
1563
|
+
if (reasoningLastIndex !== chunk.index) {
|
|
1564
|
+
reasoningParts.push(chunk.text);
|
|
1565
|
+
reasoningLastIndex = chunk.index;
|
|
1566
|
+
} else {
|
|
1567
|
+
reasoningParts[reasoningParts.length - 1] += chunk.text;
|
|
1568
|
+
}
|
|
1569
|
+
this.#frameReasoningDelta(chunk.index, chunk.text);
|
|
1570
|
+
break;
|
|
1571
|
+
}
|
|
1572
|
+
case 'tool-call-delta': {
|
|
1573
|
+
const acc = natives.get(chunk.id) ?? { id: chunk.id, arguments: '' };
|
|
1574
|
+
if (chunk.name !== undefined) acc.name = chunk.name;
|
|
1575
|
+
acc.arguments += chunk.argumentsDelta;
|
|
1576
|
+
natives.set(chunk.id, acc);
|
|
1577
|
+
break;
|
|
1578
|
+
}
|
|
1579
|
+
case 'block-end':
|
|
1580
|
+
if (chunk.block.type === 'tool-call' && chunk.block.id !== undefined) {
|
|
1581
|
+
const acc = natives.get(chunk.block.id) ?? { id: chunk.block.id, name: chunk.block.name, arguments: '' };
|
|
1582
|
+
if (chunk.block.name !== undefined) acc.name = chunk.block.name;
|
|
1583
|
+
if (chunk.block.arguments !== undefined && acc.arguments.length === 0) acc.arguments = chunk.block.arguments;
|
|
1584
|
+
natives.set(chunk.block.id, acc);
|
|
1585
|
+
} else if (chunk.block.type === 'text' && typeof chunk.block.text === 'string') {
|
|
1586
|
+
// 完整性对账:block-end 全量文本 vs text-delta 拼接(不一致如实告警,不静默)
|
|
1587
|
+
if (chunk.block.text !== textBuf) {
|
|
1588
|
+
this.#warn('block-end 全量文本与 text-delta 拼接不一致', { expectedChars: textBuf.length, actualChars: chunk.block.text.length });
|
|
1589
|
+
}
|
|
1590
|
+
}
|
|
1591
|
+
break;
|
|
1592
|
+
case 'usage':
|
|
1593
|
+
usageSeen = chunk.usage;
|
|
1594
|
+
this.#usage.inputTokens += chunk.usage.inputTokens;
|
|
1595
|
+
this.#usage.outputTokens += chunk.usage.outputTokens;
|
|
1596
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'usage', turn, inputTokens: chunk.usage.inputTokens, outputTokens: chunk.usage.outputTokens });
|
|
1597
|
+
break;
|
|
1598
|
+
case 'finish':
|
|
1599
|
+
finish = chunk.reason;
|
|
1600
|
+
break;
|
|
1601
|
+
default:
|
|
1602
|
+
break;
|
|
1603
|
+
}
|
|
1604
|
+
}
|
|
1605
|
+
} catch (error) {
|
|
1606
|
+
// 契约归一化(types.d.ts:456):适配器异常 → 终止 error finish。
|
|
1607
|
+
// 真实宿主的 LlmRuntime 已归一化,这里兜底离线/直连适配器路径。
|
|
1608
|
+
if (finish === null) {
|
|
1609
|
+
finish = {
|
|
1610
|
+
kind: 'error',
|
|
1611
|
+
message: error instanceof Error ? error.message : String(error),
|
|
1612
|
+
code: 'ADAPTER_THROWN',
|
|
1613
|
+
};
|
|
1614
|
+
}
|
|
1615
|
+
} finally {
|
|
1616
|
+
if (watchdog !== undefined) clearTimeout(watchdog);
|
|
1617
|
+
this.#activeControllers.delete(controller);
|
|
1618
|
+
}
|
|
1619
|
+
|
|
1620
|
+
if (finish === null) {
|
|
1621
|
+
finish = { kind: 'error', message: 'stream ended without a finish chunk', code: 'NO_FINISH' };
|
|
1622
|
+
this.#warn('流未以 finish chunk 终止(按契约这是异常,已归一为 error)');
|
|
1623
|
+
}
|
|
1624
|
+
debugTrace('stream.finish', finish);
|
|
1625
|
+
|
|
1626
|
+
// 流终止:冲刷 parser(truncated / done)
|
|
1627
|
+
for (const event of parser.end()) this.#handleParserEvent(event, turn, step);
|
|
1628
|
+
|
|
1629
|
+
// v0.3.2:finish=max-tokens 本身就是"输出被截断"的硬信号(即使命令恰好闭合,
|
|
1630
|
+
// 正文也可能停在半句)。与 parser 的 truncated 事件合并成一次续写事由。
|
|
1631
|
+
if (finish.kind === 'max-tokens' && this.#truncation === null) {
|
|
1632
|
+
this.#truncation = { reason: 'max-tokens', raw: this.#streamProse };
|
|
1633
|
+
}
|
|
1634
|
+
// 本步摘要:下一步请求装配前落追加区(#commitStepDigest)
|
|
1635
|
+
this.#stepNatives = (finish.kind === 'stop' || finish.kind === 'tool-calls')
|
|
1636
|
+
? [...natives.values()].map((c) => ({ id: c.id, name: c.name ?? 'unknown' }))
|
|
1637
|
+
: [];
|
|
1638
|
+
this.#lastStepDigest = {
|
|
1639
|
+
turn,
|
|
1640
|
+
step,
|
|
1641
|
+
prose: this.#streamProse,
|
|
1642
|
+
cmdIds: [...this.#stepCommandIds],
|
|
1643
|
+
natives: [...this.#stepNatives],
|
|
1644
|
+
};
|
|
1645
|
+
|
|
1646
|
+
// 会话落盘:assistant 消息(成功 → assistant/message;error/aborted → attempt / 中断消息)
|
|
1647
|
+
// v0.3.0:原生 tool_call 通道要在**同一条** assistant 消息里广告 tool-call 块,
|
|
1648
|
+
// 否则随后宿主写出的 tool/call 在 v4 格式校验里没有生命周期 → 历史加载被判 corrupt。
|
|
1649
|
+
// 只有确定会执行的批次才广告(error/aborted 的残缺调用如实丢弃,不能留下未解广告)。
|
|
1650
|
+
// v0.3.1:正文落盘从整段原文改为纯 prose(#streamProse,parser text 事件拼接)——
|
|
1651
|
+
// 协议标记(tf-*/DSML)留在台账与会话事实层,桌面端过程区只显示可读文本。
|
|
1652
|
+
const nativeCallsWillRun = (finish.kind === 'stop' || finish.kind === 'tool-calls') && natives.size > 0;
|
|
1653
|
+
const nativeAds = nativeCallsWillRun
|
|
1654
|
+
? [...natives.values()].map((c) => ({ id: c.id, name: c.name ?? 'unknown', arguments: c.arguments || '{}' }))
|
|
1655
|
+
: [];
|
|
1656
|
+
const reasoningText = reasoningParts.join('\n');
|
|
1657
|
+
let settlement ;
|
|
1658
|
+
try {
|
|
1659
|
+
// v0.3.2:落盘正文归一化(去纯空白消息 / 压缩连续空行)——0.3.1 常见 "\n\n\n\n"
|
|
1660
|
+
// 空气泡,桌面端过程区看起来就是"被截断的空白"。
|
|
1661
|
+
settlement = this.#ports.events?.assistantMessage(turn, step, normalizeProse(this.#streamProse), {
|
|
1662
|
+
finish,
|
|
1663
|
+
usage: usageSeen,
|
|
1664
|
+
toolCalls: nativeAds,
|
|
1665
|
+
...(reasoningText !== '' ? { reasoning: reasoningText } : {}),
|
|
1666
|
+
});
|
|
1667
|
+
} catch (error) {
|
|
1668
|
+
this.#warn('assistant 事件写入失败', error);
|
|
1669
|
+
}
|
|
1670
|
+
frameEnd(settlement);
|
|
1671
|
+
if (reasoningChars > 0) {
|
|
1672
|
+
this.#ledgerWrite('plugin:tf-agent/step', { turn, step, reasoningChars });
|
|
1673
|
+
}
|
|
1674
|
+
|
|
1675
|
+
// 原生 tool_call 通道(阻塞式回灌):只在流正常终止时执行;中断/错误的残缺调用如实丢弃
|
|
1676
|
+
if (natives.size > 0) {
|
|
1677
|
+
if (finish.kind === 'stop' || finish.kind === 'tool-calls') {
|
|
1678
|
+
await this.#executeNativeCalls(turn, step, [...natives.values()], controller.signal, level);
|
|
1679
|
+
} else {
|
|
1680
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'fault', fault: 'native-calls-discarded', detail: `finish=${finish.kind} calls=${natives.size}` });
|
|
1681
|
+
}
|
|
1682
|
+
}
|
|
1683
|
+
|
|
1684
|
+
return { finish };
|
|
1685
|
+
}
|
|
1686
|
+
|
|
1687
|
+
// ------------------------------------------------------------------ parser 事件处理
|
|
1688
|
+
|
|
1689
|
+
#handleParserEvent(event , turn , step ) {
|
|
1690
|
+
switch (event.type) {
|
|
1691
|
+
case 'text':
|
|
1692
|
+
// v0.3.1:prose 累积(落盘 assistant/message 的正文;0.3.0 落整段原文,协议
|
|
1693
|
+
// 标记会在桌面端渲染成乱码)。命令本体已作为 command 事件处理,不进 prose。
|
|
1694
|
+
this.#streamProse += event.text;
|
|
1695
|
+
break;
|
|
1696
|
+
case 'command':
|
|
1697
|
+
this.#onCommand(event.command, turn, step);
|
|
1698
|
+
break;
|
|
1699
|
+
case 'malformed':
|
|
1700
|
+
// fail-soft:记 ledger,流继续(分派 06 硬性要求 + 05 号故障剧本口径)
|
|
1701
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'malformed', raw: event.raw, reason: event.reason });
|
|
1702
|
+
this.#ledgerWrite('plugin:tf-agent/fault', { fault: 'malformed-command', reason: event.reason, raw: event.raw.slice(0, 200) });
|
|
1703
|
+
break;
|
|
1704
|
+
case 'truncated':
|
|
1705
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'truncated', raw: event.raw, reason: event.reason });
|
|
1706
|
+
this.#ledgerWrite('plugin:tf-agent/fault', { fault: 'truncated-command', reason: event.reason });
|
|
1707
|
+
// v0.3.2:截断不再只是台账——本步结束前由 #turnLoop 强制一次续写注入。
|
|
1708
|
+
this.#truncation = { reason: event.reason, raw: event.raw };
|
|
1709
|
+
break;
|
|
1710
|
+
case 'cycle':
|
|
1711
|
+
// 环上的命令永不就绪 → 收束判定以结构化错误重入
|
|
1712
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'cycle', cycle: event.cycle });
|
|
1713
|
+
for (const id of event.cycle) {
|
|
1714
|
+
const rec = this.#commands.get(id);
|
|
1715
|
+
if (rec !== undefined && rec.status === 'pending') {
|
|
1716
|
+
rec.status = 'failed';
|
|
1717
|
+
rec.detail = `depends_on 环:${event.cycle.join(' -> ')}`;
|
|
1718
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'command', id, name: rec.cmd.name, status: 'failed', detail: rec.detail });
|
|
1719
|
+
}
|
|
1720
|
+
}
|
|
1721
|
+
break;
|
|
1722
|
+
case 'done':
|
|
1723
|
+
break;
|
|
1724
|
+
}
|
|
1725
|
+
}
|
|
1726
|
+
|
|
1727
|
+
#onCommand(cmd , turn , step ) {
|
|
1728
|
+
// v0.3.1:回合级命令序(跨请求单调)。final 之后又发过非 final 命令 → 那条 final 过期
|
|
1729
|
+
//(模型写完 final 又继续干活;旧答案不能当成交付内容)。
|
|
1730
|
+
const order = ++this.#cmdOrder;
|
|
1731
|
+
// v0.3.2:本步摘要(含重复 id 的命令——模型确实发过它们,历史要如实)
|
|
1732
|
+
this.#stepCommandIds.push(cmd.id);
|
|
1733
|
+
if (cmd.name !== 'tf-final') this.#lastNonFinalOrder = order;
|
|
1734
|
+
const prev = this.#commands.get(cmd.id);
|
|
1735
|
+
if (prev !== undefined) {
|
|
1736
|
+
// ---- 重复 id 语义(对齐上游 ThinkFlow DESIGN.md:重复 id 不能伪造成功)----
|
|
1737
|
+
// ① 同 id 同内容且已有回执 → 幂等返回原回执(含句柄),不重复执行;
|
|
1738
|
+
// ② 同 id 不同内容 → 明确拒绝(换新 id);
|
|
1739
|
+
// ③ 原命令仍在执行 → 拒绝;
|
|
1740
|
+
// ④ 原命令被拒绝(无副作用)→ 允许同 id 修正重发(上游:"拒绝的命令没有副作用,
|
|
1741
|
+
// 可用原 id 修正重发,不因无效输入制造第二次重复编号错误")。
|
|
1742
|
+
const fp = commandFingerprint(cmd);
|
|
1743
|
+
if (prev.status === 'ok' && cmd.name === 'tf-final') {
|
|
1744
|
+
// tf-final 无副作用,且模型反复复用同一 id 更新答案(deepseek-flash 真连实证):
|
|
1745
|
+
// 同 id 携带新 summary = 覆盖最终答案(last-wins);同 summary = 幂等原回执。
|
|
1746
|
+
// "重复 id 不能伪造成功"不受影响——final 不产生副作用,只是声明。
|
|
1747
|
+
// v0.3.1:无论覆盖还是幂等,都算"本流末尾又声明了一次" → 刷新 final 序(不再判过期)。
|
|
1748
|
+
this.#lastFinalOrder = order;
|
|
1749
|
+
if (commandFingerprint(prev.cmd) === fp) {
|
|
1750
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'command', id: cmd.id, name: cmd.name, status: 'ok', detail: 'duplicate-idempotent: 返回原回执' });
|
|
1751
|
+
} else {
|
|
1752
|
+
const summary = cmd.attrs['summary'] ?? '';
|
|
1753
|
+
const cand = this.#finalCandidates.find((c) => c.cmdId === cmd.id);
|
|
1754
|
+
if (cand !== undefined) {
|
|
1755
|
+
cand.summary = summary;
|
|
1756
|
+
cand.turn = turn;
|
|
1757
|
+
cand.step = step;
|
|
1758
|
+
}
|
|
1759
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'command', id: cmd.id, name: cmd.name, status: 'ok', detail: summary });
|
|
1760
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'final', summary });
|
|
1761
|
+
this.#ledgerWrite('plugin:tf-agent/final', { summary, turn, step, cmdId: cmd.id, superseded: true });
|
|
1762
|
+
}
|
|
1763
|
+
return;
|
|
1764
|
+
}
|
|
1765
|
+
if (prev.status === 'ok' || prev.status === 'failed') {
|
|
1766
|
+
if (commandFingerprint(prev.cmd) === fp) {
|
|
1767
|
+
this.#record({
|
|
1768
|
+
seq: ++DRIVER_SEQ, kind: 'command', id: cmd.id, name: cmd.name, status: prev.status,
|
|
1769
|
+
detail: `duplicate-idempotent: 返回原回执${prev.handle !== undefined ? `(handle=${prev.handle})` : ''}`,
|
|
1770
|
+
handle: prev.handle,
|
|
1771
|
+
});
|
|
1772
|
+
this.#ledgerWrite('plugin:tf-agent/command', { cmdId: cmd.id, name: cmd.name, status: 'duplicate-idempotent' });
|
|
1773
|
+
this.#queueReplay(cmd, prev);
|
|
1774
|
+
} else {
|
|
1775
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'command', id: cmd.id, name: cmd.name, status: 'rejected', detail: 'duplicate-id: 同 id 已被不同内容占用,请换新 id' });
|
|
1776
|
+
}
|
|
1777
|
+
return;
|
|
1778
|
+
}
|
|
1779
|
+
if (prev.status === 'pending' || prev.status === 'dispatched') {
|
|
1780
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'command', id: cmd.id, name: cmd.name, status: 'rejected', detail: 'duplicate-id: 命令执行中' });
|
|
1781
|
+
return;
|
|
1782
|
+
}
|
|
1783
|
+
// prev.status === 'rejected':登记位让给修正重发(记录历史保留在 #records)
|
|
1784
|
+
this.#commands.delete(cmd.id);
|
|
1785
|
+
}
|
|
1786
|
+
const record = { cmd, status: 'pending' };
|
|
1787
|
+
record.streamSeq = ++this.#streamSeqCounter;
|
|
1788
|
+
this.#commands.set(cmd.id, record);
|
|
1789
|
+
if (cmd.name === 'tf-write') {
|
|
1790
|
+
// 同流写序(上游 DESIGN:信息工具先等之前的写入)——#dispatchReady 里的隐式依赖
|
|
1791
|
+
this.#streamWrites.push({ id: cmd.id, seq: record.streamSeq });
|
|
1792
|
+
}
|
|
1793
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'command', id: cmd.id, name: cmd.name, status: 'pending' });
|
|
1794
|
+
if (cmd.name === 'tf-final') {
|
|
1795
|
+
// 终结命令:不派发工具,标记完成(推进依赖图);台账同时落 command + final 两条。
|
|
1796
|
+
// 过早性在流末收束判定(#turnLoop):依赖未满足/有命令未完成 → 注入 premature-final
|
|
1797
|
+
// 引导用新 id 重发(2026-11-15 真连 R3/R4 教训:占位 final 会永久占用 finalSeen)。
|
|
1798
|
+
record.status = 'ok';
|
|
1799
|
+
record.detail = cmd.attrs['summary'] ?? '';
|
|
1800
|
+
this.#lastFinalOrder = order;
|
|
1801
|
+
this.#finalCandidates.push({ cmdId: cmd.id, summary: record.detail, turn, step });
|
|
1802
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'command', id: cmd.id, name: cmd.name, status: 'ok', detail: record.detail });
|
|
1803
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'final', summary: record.detail });
|
|
1804
|
+
this.#ledgerWrite('plugin:tf-agent/final', { summary: record.detail, turn, step, cmdId: cmd.id });
|
|
1805
|
+
}
|
|
1806
|
+
this.#dispatchReady(turn, step);
|
|
1807
|
+
}
|
|
1808
|
+
|
|
1809
|
+
/**
|
|
1810
|
+
* v0.3.1 截断修复:重复命令的原结果回灌(幂等语义不变,不重执行)。
|
|
1811
|
+
*
|
|
1812
|
+
* 为什么需要:观测内容只在"易变尾"注入一次,跨请求即消失(历史里只剩句柄目录行)。
|
|
1813
|
+
* 模型丢失上下文后最自然的动作就是把同一条 read/glob 再发一次——0.3.1 只回
|
|
1814
|
+
* "duplicate-idempotent(handle=…)",模型仍然一无所获,于是原地打转(真机会话
|
|
1815
|
+
* `session-84274277` 第 3–7 步连续 glob 同一 pattern),最后用 `summary="placeholder"`
|
|
1816
|
+
* 收场。这里把原观测按既有上限回灌一次,给模型一条低成本的恢复路径。
|
|
1817
|
+
*/
|
|
1818
|
+
#queueReplay(cmd , prev ) {
|
|
1819
|
+
if (prev.status !== 'ok') return;
|
|
1820
|
+
if (prev.handle === undefined || prev.handle === '') return;
|
|
1821
|
+
if (!REPLAYABLE_COMMANDS.has(cmd.name)) return;
|
|
1822
|
+
if (this.#pendingReplays.length >= MAX_REPLAY_INJECTIONS) {
|
|
1823
|
+
// 同一条重复命令反复重发:只记一次 fault,不重复刷台账
|
|
1824
|
+
if (!this.#replayCapped) {
|
|
1825
|
+
this.#replayCapped = true;
|
|
1826
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'fault', fault: 'replay-capped', detail: `重复命令回灌已达上限 ${MAX_REPLAY_INJECTIONS}` });
|
|
1827
|
+
this.#ledgerWrite('plugin:tf-agent/fault', { fault: 'replay-capped', cap: MAX_REPLAY_INJECTIONS });
|
|
1828
|
+
}
|
|
1829
|
+
return;
|
|
1830
|
+
}
|
|
1831
|
+
// 只登记意图:内容在真正装配进下一次请求时才 peek(收敛路径直接丢弃,
|
|
1832
|
+
// 不占 injected 计数——injected 口径是"确实进入模型上下文的观测负载")。
|
|
1833
|
+
this.#pendingReplays.push({ cmdId: cmd.id, name: cmd.name, handle: prev.handle });
|
|
1834
|
+
}
|
|
1835
|
+
|
|
1836
|
+
/** 把待回灌的重复命令物化成注入块(仅在轮到它们进入下一次请求时调用)。 */
|
|
1837
|
+
#materializeReplays() {
|
|
1838
|
+
if (this.#pendingReplays.length === 0) return [];
|
|
1839
|
+
const limit = this.#cfg.readFeedbackLimit ?? DEFAULT_READ_FEEDBACK_LIMIT;
|
|
1840
|
+
const out = [];
|
|
1841
|
+
for (const item of this.#pendingReplays) {
|
|
1842
|
+
const content = this.#obs.peek(item.handle, 1, Number.MAX_SAFE_INTEGER);
|
|
1843
|
+
if (content === null || content === '') continue;
|
|
1844
|
+
this.#replays += 1;
|
|
1845
|
+
const body = content.length <= limit
|
|
1846
|
+
? content
|
|
1847
|
+
: `${content.slice(0, limit)}\n……(原结果超长,已截断 ${content.length - limit} 字符;用 tf-peek handle="${item.handle}" from_line=.. to_line=.. 精确取回)`;
|
|
1848
|
+
out.push({
|
|
1849
|
+
role: 'user',
|
|
1850
|
+
content: `[tf-stream:replay id=${item.cmdId} name=${item.name} handle=${item.handle}]\n`
|
|
1851
|
+
+ '这条命令与之前完全相同(幂等):没有重复执行,以下回灌它的原结果。\n'
|
|
1852
|
+
+ `${body}\n(需要其它行段用 tf-peek handle="${item.handle}" from_line=.. to_line=..)`,
|
|
1853
|
+
});
|
|
1854
|
+
this.#record({
|
|
1855
|
+
seq: ++DRIVER_SEQ, kind: 'observation',
|
|
1856
|
+
handle: item.handle, key: `replay:${item.cmdId}`, infoGain: 'high', reason: 'duplicate-replay',
|
|
1857
|
+
});
|
|
1858
|
+
this.#ledgerWrite('plugin:tf-agent/command', { cmdId: item.cmdId, name: item.name, status: 'duplicate-replay', handle: item.handle, chars: content.length });
|
|
1859
|
+
}
|
|
1860
|
+
this.#pendingReplays = [];
|
|
1861
|
+
return out;
|
|
1862
|
+
}
|
|
1863
|
+
|
|
1864
|
+
/**
|
|
1865
|
+
* v0.3.2:把上一步的正文 + 命令摘要落进追加区(assistant/message 语义)。
|
|
1866
|
+
*
|
|
1867
|
+
* 为什么必须有:渲染器只持有"稳定前缀 + 追加区 + 易变尾"。0.3.x 从不往追加区写
|
|
1868
|
+
* assistant/工具事实,易变尾又每请求重建——模型在第 2 个请求起就只看到 system + 任务 +
|
|
1869
|
+
* 句柄目录行。真机 session-e4b9a89c 里模型的原话是"The history is truncated. I don't see
|
|
1870
|
+
* the plan content",随后反复重读、计划无法验收、9 步后 blocked。
|
|
1871
|
+
*
|
|
1872
|
+
* 对齐内建 dsh-agent-loop 的语义:`session.deriveMessages()` 每步都把完整的
|
|
1873
|
+
* assistant/message(含 tool-call 块)与 tool/result 回放给模型;这里用压缩摘要
|
|
1874
|
+
*(id/命令/目标/状态/句柄/字符数)落追加区,原结果由随后的易变尾转正承载。
|
|
1875
|
+
*/
|
|
1876
|
+
#commitStepDigest() {
|
|
1877
|
+
const digest = this.#lastStepDigest;
|
|
1878
|
+
this.#lastStepDigest = null;
|
|
1879
|
+
if (digest === null) return;
|
|
1880
|
+
const prose = normalizeProse(digest.prose);
|
|
1881
|
+
if (prose !== '') {
|
|
1882
|
+
// v0.3.2:assistant 历史块必须带 source(宿主 forAdapter 无防护读
|
|
1883
|
+
// source.replayState;缺失 = 请求崩溃。provider/model 取驱动器实时路由)。
|
|
1884
|
+
this.#renderer.appendHistory({ role: 'assistant', content: capText(prose, STEP_PROSE_COMMIT_LIMIT), source: this.modelSource() });
|
|
1885
|
+
}
|
|
1886
|
+
const lines = [];
|
|
1887
|
+
for (const id of digest.cmdIds) {
|
|
1888
|
+
const rec = this.#commands.get(id);
|
|
1889
|
+
if (rec === undefined) continue;
|
|
1890
|
+
const target = rec.cmd.attrs['path'] ?? rec.cmd.attrs['cmd'] ?? rec.cmd.attrs['pattern']
|
|
1891
|
+
?? rec.cmd.attrs['handle'] ?? rec.cmd.attrs['summary'] ?? '';
|
|
1892
|
+
const detail = rec.detail !== undefined && rec.detail !== '' ? ` · ${capText(rec.detail, 120)}` : '';
|
|
1893
|
+
lines.push(
|
|
1894
|
+
`- ${id} ${rec.cmd.name}${target !== '' ? ` ${capText(target, 120)}` : ''} → ${rec.status}`
|
|
1895
|
+
+ `${rec.handle !== undefined ? ` handle=${rec.handle}` : ''}${detail}`,
|
|
1896
|
+
);
|
|
1897
|
+
}
|
|
1898
|
+
for (const native of digest.natives) {
|
|
1899
|
+
lines.push(`- native ${native.name} (callId=${native.id}) → 已执行,结果见随后注入块`);
|
|
1900
|
+
}
|
|
1901
|
+
if (lines.length === 0) return;
|
|
1902
|
+
this.#renderer.appendHistory({
|
|
1903
|
+
role: 'user',
|
|
1904
|
+
content: `[tf-stream:step step=${digest.step} 上一步动作与结果]\n${lines.join('\n')}`,
|
|
1905
|
+
});
|
|
1906
|
+
}
|
|
1907
|
+
|
|
1908
|
+
/** v0.3.2:把已随请求发出的易变尾转正为追加区历史(下一请求仍可见,不再一次性蒸发)。
|
|
1909
|
+
* 只转正"事实类"块(观测/peek/原生结果/回灌);nudge / degraded / error 这类
|
|
1910
|
+
* 瞬态指令不回灌历史——否则下一回合模型会把过期的"预算告急""final 被拒"当现状。 */
|
|
1911
|
+
#commitDeliveredTail() {
|
|
1912
|
+
const delivered = this.#deliveredTail;
|
|
1913
|
+
this.#deliveredTail = null;
|
|
1914
|
+
if (delivered === null) return;
|
|
1915
|
+
for (const block of delivered.blocks) {
|
|
1916
|
+
if (!DURABLE_TAIL_PREFIXES.some((prefix) => block.content.startsWith(prefix))) continue;
|
|
1917
|
+
this.#renderer.appendHistory({ role: block.role, content: block.content });
|
|
1918
|
+
}
|
|
1919
|
+
}
|
|
1920
|
+
|
|
1921
|
+
/** F5 计划快照(final 被计划门槛拒绝时随注入一起给出,模型不必凭记忆猜验收项)。 */
|
|
1922
|
+
#planSnapshot() {
|
|
1923
|
+
if (this.#plan === null) return '';
|
|
1924
|
+
return [...this.#plan.items.entries()]
|
|
1925
|
+
.map(([id, item]) => `- [${id}] ${item.text}(${item.status})`)
|
|
1926
|
+
.join('\n');
|
|
1927
|
+
}
|
|
1928
|
+
|
|
1929
|
+
/** 派发所有就绪命令(依赖全部 ok、未派发),并发上限 maxParallelToolCalls。
|
|
1930
|
+
* 隐式写序(上游 ThinkFlow 语义):任何命令隐式等待同流内先闭合且尚未 ok 的 tf-write——
|
|
1931
|
+
* 先写后读不会读到旧内容;写族自身按 FIFO 排队(同流多写不再并发竞态)。 */
|
|
1932
|
+
#dispatchReady(turn , step ) {
|
|
1933
|
+
if (this.#aborted) return;
|
|
1934
|
+
for (const rec of this.#commands.values()) {
|
|
1935
|
+
if (rec.status !== 'pending') continue;
|
|
1936
|
+
if (this.#inFlight.size >= this.#cfg.maxParallelToolCalls) return;
|
|
1937
|
+
const depsMet = rec.cmd.depends_on.every((d) => this.#commands.get(d)?.status === 'ok');
|
|
1938
|
+
if (!depsMet) continue;
|
|
1939
|
+
const pendingWrites = rec.streamSeq !== undefined
|
|
1940
|
+
? this.#streamWrites.filter((w) => w.seq < rec.streamSeq && this.#commands.get(w.id)?.status !== 'ok')
|
|
1941
|
+
: [];
|
|
1942
|
+
if (pendingWrites.length > 0) continue;
|
|
1943
|
+
rec.status = 'dispatched';
|
|
1944
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'command', id: rec.cmd.id, name: rec.cmd.name, status: 'dispatched' });
|
|
1945
|
+
const task = this.#executeCommand(rec, turn, step)
|
|
1946
|
+
.catch((error) => {
|
|
1947
|
+
// 驱动器自身异常(fail-open):结构化失败 + 告警,不静默吞
|
|
1948
|
+
rec.status = 'failed';
|
|
1949
|
+
rec.detail = error instanceof Error ? error.message : String(error);
|
|
1950
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'command', id: rec.cmd.id, name: rec.cmd.name, status: 'failed', detail: rec.detail });
|
|
1951
|
+
this.#warn(`命令 ${rec.cmd.id} 执行异常`, error);
|
|
1952
|
+
})
|
|
1953
|
+
.finally(() => {
|
|
1954
|
+
this.#inFlight.delete(task);
|
|
1955
|
+
this.#ports.onToolSettled?.();
|
|
1956
|
+
this.#dispatchReady(turn, step);
|
|
1957
|
+
});
|
|
1958
|
+
this.#inFlight.add(task);
|
|
1959
|
+
}
|
|
1960
|
+
}
|
|
1961
|
+
|
|
1962
|
+
async #executeCommand(rec , turn , step ) {
|
|
1963
|
+
const cmd = rec.cmd;
|
|
1964
|
+
|
|
1965
|
+
// ---- 准入(kernel/gate.ts 的 admit 面;缺省无门)----
|
|
1966
|
+
if (this.#gate !== undefined) {
|
|
1967
|
+
const verdict = await this.#gate.admit({
|
|
1968
|
+
action: cmd.name,
|
|
1969
|
+
taskId: this.#taskId,
|
|
1970
|
+
detail: cmd.name === 'tf-write' ? `path=${cmd.attrs['path'] ?? ''}` : cmd.attrs['cmd'] ?? cmd.attrs['description'] ?? cmd.attrs['path'] ?? '',
|
|
1971
|
+
});
|
|
1972
|
+
if (verdict.verdict === 'deny') {
|
|
1973
|
+
rec.status = 'rejected';
|
|
1974
|
+
rec.detail = `${verdict.reason}: ${verdict.detail}`;
|
|
1975
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'command', id: cmd.id, name: cmd.name, status: 'rejected', detail: rec.detail });
|
|
1976
|
+
this.#ledgerWrite('plugin:tf-agent/command', { cmdId: cmd.id, name: cmd.name, status: 'rejected', detail: rec.detail });
|
|
1977
|
+
return;
|
|
1978
|
+
}
|
|
1979
|
+
}
|
|
1980
|
+
|
|
1981
|
+
// ---- tf-peek:内核 obs 直接取回(need_result 通道)----
|
|
1982
|
+
if (cmd.name === 'tf-peek') {
|
|
1983
|
+
const handle = cmd.attrs['handle'] ?? '';
|
|
1984
|
+
const from = Number(cmd.attrs['from_line'] ?? '1');
|
|
1985
|
+
const to = cmd.attrs['to_line'] === undefined ? Number.MAX_SAFE_INTEGER : Number(cmd.attrs['to_line']);
|
|
1986
|
+
const content = this.#obs.peek(handle, from, to);
|
|
1987
|
+
if (content === null) {
|
|
1988
|
+
// 同流乐观 peek(句柄所在命令还在执行):延迟到流末 drain 后重试一次(上游语义
|
|
1989
|
+
// "信息工具先等之前的写入"的驱动器侧实现);流末仍无此句柄才按失败注入。
|
|
1990
|
+
const workInFlight = [...this.#commands.values()].some(
|
|
1991
|
+
(r) => r.cmd.name !== 'tf-peek' && (r.status === 'pending' || r.status === 'dispatched'),
|
|
1992
|
+
);
|
|
1993
|
+
if (workInFlight) {
|
|
1994
|
+
rec.status = 'dispatched';
|
|
1995
|
+
rec.detail = 'deferred: handle 未就绪,流末重试';
|
|
1996
|
+
this.#deferredPeeks.push({ rec, turn, step });
|
|
1997
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'command', id: cmd.id, name: cmd.name, status: 'dispatched', detail: rec.detail });
|
|
1998
|
+
return;
|
|
1999
|
+
}
|
|
2000
|
+
rec.status = 'failed';
|
|
2001
|
+
rec.detail = `unknown-handle:${handle}`;
|
|
2002
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'command', id: cmd.id, name: cmd.name, status: 'failed', detail: rec.detail });
|
|
2003
|
+
this.#ledgerWrite('plugin:tf-agent/command', { cmdId: cmd.id, name: cmd.name, status: 'failed', detail: rec.detail });
|
|
2004
|
+
return;
|
|
2005
|
+
}
|
|
2006
|
+
rec.status = 'ok';
|
|
2007
|
+
rec.output = content;
|
|
2008
|
+
rec.detail = `${content.length} chars`;
|
|
2009
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'command', id: cmd.id, name: cmd.name, status: 'ok', handle, detail: rec.detail });
|
|
2010
|
+
this.#ledgerWrite('plugin:tf-agent/command', { cmdId: cmd.id, name: cmd.name, status: 'ok', handle, chars: content.length });
|
|
2011
|
+
return;
|
|
2012
|
+
}
|
|
2013
|
+
|
|
2014
|
+
// ---- tf-plan:计划与验收(F5;驱动器内部处理,不映射工具)----
|
|
2015
|
+
if (cmd.name === 'tf-plan') {
|
|
2016
|
+
if (!this.#cfg.enablePlan) {
|
|
2017
|
+
rec.status = 'failed';
|
|
2018
|
+
rec.detail = 'plan-disabled: 计划与验收未启用(enablePlan: false)';
|
|
2019
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'command', id: cmd.id, name: cmd.name, status: 'failed', detail: rec.detail });
|
|
2020
|
+
this.#ledgerWrite('plugin:tf-agent/command', { cmdId: cmd.id, name: cmd.name, status: 'failed', detail: rec.detail });
|
|
2021
|
+
return;
|
|
2022
|
+
}
|
|
2023
|
+
const items = parsePlanItems(cmd.body ?? '');
|
|
2024
|
+
if (items.length === 0) {
|
|
2025
|
+
rec.status = 'failed';
|
|
2026
|
+
rec.detail = 'bad-plan: tf-plan body 需要至少一行验收项(格式:- [id] 描述)';
|
|
2027
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'command', id: cmd.id, name: cmd.name, status: 'failed', detail: rec.detail });
|
|
2028
|
+
this.#ledgerWrite('plugin:tf-agent/command', { cmdId: cmd.id, name: cmd.name, status: 'failed', detail: rec.detail });
|
|
2029
|
+
return;
|
|
2030
|
+
}
|
|
2031
|
+
// 计划修订 = 整体替换(修订必须在显式 tf-plan 里声明,不接受隐式改计划);
|
|
2032
|
+
// 已验证项在新计划中同名重声明时保留证据(显式重声明显式保留),缺席项 = 显式移除。
|
|
2033
|
+
const next = new Map ();
|
|
2034
|
+
for (const item of items) {
|
|
2035
|
+
const prev = this.#plan?.items.get(item.id);
|
|
2036
|
+
next.set(item.id, prev !== undefined && prev.status === 'verified'
|
|
2037
|
+
? { text: item.text, status: 'verified', evidence: prev.evidence }
|
|
2038
|
+
: { text: item.text, status: 'open' });
|
|
2039
|
+
}
|
|
2040
|
+
const revision = (this.#plan?.revision ?? 0) + 1;
|
|
2041
|
+
this.#plan = { revision, items: next };
|
|
2042
|
+
rec.status = 'ok';
|
|
2043
|
+
rec.detail = `plan v${revision}: ${items.length} 验收项`;
|
|
2044
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'command', id: cmd.id, name: cmd.name, status: 'ok', detail: rec.detail });
|
|
2045
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'plan', revision, open: [...next.values()].filter((i) => i.status === 'open').length, total: next.size });
|
|
2046
|
+
this.#ledgerWrite('plugin:tf-agent/plan', { revision, cmdId: cmd.id, items: items.map((i) => ({ id: i.id, text: i.text, status: next.get(i.id) .status })) });
|
|
2047
|
+
return;
|
|
2048
|
+
}
|
|
2049
|
+
|
|
2050
|
+
// ---- tf-code:程序化工具调用(PTC 桥接;缺端口或未显式开启 → 命令级失败并引导改道)----
|
|
2051
|
+
if (cmd.name === 'tf-code') {
|
|
2052
|
+
const executor = this.#ports.executeCode;
|
|
2053
|
+
if (executor === undefined || !this.#cfg.codeEnabled) {
|
|
2054
|
+
rec.status = 'failed';
|
|
2055
|
+
rec.detail = 'no-code-channel: tf-code 未开启(K1 默认关闭;需显式 enableCode: true 且宿主提供 ctx.ptcRuntime 服务缝(@deepseek-ai/dsh-ptc-runtime)后才可用),改道 tf-bash/tf-write';
|
|
2056
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'command', id: cmd.id, name: cmd.name, status: 'failed', detail: rec.detail });
|
|
2057
|
+
this.#ledgerWrite('plugin:tf-agent/command', { cmdId: cmd.id, name: cmd.name, status: 'failed', detail: rec.detail });
|
|
2058
|
+
return;
|
|
2059
|
+
}
|
|
2060
|
+
const timeoutAttr = cmd.attrs['timeout'];
|
|
2061
|
+
const timeoutMs = timeoutAttr !== undefined && /^\d+$/.test(timeoutAttr) ? Number(timeoutAttr) : this.#cfg.codeTimeoutMs;
|
|
2062
|
+
let outcome;
|
|
2063
|
+
try {
|
|
2064
|
+
outcome = await executor({
|
|
2065
|
+
callId: cmd.id,
|
|
2066
|
+
code: cmd.body ?? '',
|
|
2067
|
+
...(timeoutMs === undefined ? {} : { timeoutMs }),
|
|
2068
|
+
// K4:回合 signal 直通(cancel 传导到 runtime;不再用独立且永不触发的 controller)
|
|
2069
|
+
signal: this.#commandSignal(),
|
|
2070
|
+
// K2:会话工作区(与 tf-write/tf-read 同一解析语义;未解析到则由宿主取默认目录)
|
|
2071
|
+
...(this.#sessionCwd === undefined ? {} : { cwd: this.#sessionCwd }),
|
|
2072
|
+
...(this.#agentRef === undefined ? {} : { agent: this.#agentRef }),
|
|
2073
|
+
});
|
|
2074
|
+
} catch (error) {
|
|
2075
|
+
// 执行器自身异常(fail-open):结构化失败 + 告警,不静默吞
|
|
2076
|
+
rec.status = 'failed';
|
|
2077
|
+
rec.detail = `code-executor-error: ${error instanceof Error ? error.message : String(error)}`.slice(0, 500);
|
|
2078
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'command', id: cmd.id, name: cmd.name, status: 'failed', detail: rec.detail });
|
|
2079
|
+
this.#ledgerWrite('plugin:tf-agent/command', { cmdId: cmd.id, name: cmd.name, status: 'failed', detail: rec.detail.slice(0, 200) });
|
|
2080
|
+
this.#warn(`tf-code ${cmd.id} 执行异常`, error);
|
|
2081
|
+
return;
|
|
2082
|
+
}
|
|
2083
|
+
// 观测登记(code 族:成功 high 首次/变化注骨架;失败一律 high)
|
|
2084
|
+
const observation = this.#obs.observe({
|
|
2085
|
+
tool: 'tf-code',
|
|
2086
|
+
ok: outcome.ok,
|
|
2087
|
+
key: observationKey(cmd),
|
|
2088
|
+
content: outcome.ok ? (outcome.valueJson ?? '') : (outcome.error ?? 'unknown'),
|
|
2089
|
+
callId: cmd.id,
|
|
2090
|
+
});
|
|
2091
|
+
rec.observation = observation;
|
|
2092
|
+
rec.handle = observation.handle ?? undefined;
|
|
2093
|
+
this.#record({
|
|
2094
|
+
seq: ++DRIVER_SEQ, kind: 'observation',
|
|
2095
|
+
handle: observation.handle, key: observationKey(cmd),
|
|
2096
|
+
infoGain: observation.info_gain, reason: observation.reason,
|
|
2097
|
+
});
|
|
2098
|
+
// K2 沙箱事实记账(成功与失败都记;enforcement=partial 必须显式可见)
|
|
2099
|
+
const sandbox = outcome.sandbox;
|
|
2100
|
+
if (sandbox !== undefined) {
|
|
2101
|
+
this.#record({
|
|
2102
|
+
seq: ++DRIVER_SEQ, kind: 'sandbox',
|
|
2103
|
+
cmdId: cmd.id, mode: sandbox.mode, enforcement: sandbox.enforcement,
|
|
2104
|
+
deniedCount: sandbox.denied?.length ?? 0,
|
|
2105
|
+
});
|
|
2106
|
+
this.#ledgerWrite('plugin:tf-agent/command', {
|
|
2107
|
+
cmdId: cmd.id, name: cmd.name, sandbox: true,
|
|
2108
|
+
mode: sandbox.mode, enforcement: sandbox.enforcement, denied: sandbox.denied,
|
|
2109
|
+
cwd: outcome.cwd ?? this.#sessionCwd ?? null,
|
|
2110
|
+
});
|
|
2111
|
+
}
|
|
2112
|
+
if (!outcome.ok) {
|
|
2113
|
+
rec.status = 'failed';
|
|
2114
|
+
// K3 结构化失败注入:kind + 可重试结论 + 建议 + 日志尾(200 字符)。
|
|
2115
|
+
const kind = outcome.kind ?? 'exception';
|
|
2116
|
+
const retryable = outcome.retryable === true;
|
|
2117
|
+
const logsTail = outcome.logs === undefined ? '' : `\nlogs tail: ${outcome.logs.slice(-200)}`;
|
|
2118
|
+
rec.detail = `[kind=${kind} retry=${retryable ? 'yes' : 'no'}] ${outcome.error ?? 'unknown'}${logsTail}`.slice(0, 800);
|
|
2119
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'command', id: cmd.id, name: cmd.name, status: 'failed', detail: rec.detail });
|
|
2120
|
+
this.#ledgerWrite('plugin:tf-agent/command', { cmdId: cmd.id, name: cmd.name, status: 'failed', kind, retryable, detail: (outcome.error ?? '').slice(0, 200) });
|
|
2121
|
+
return;
|
|
2122
|
+
}
|
|
2123
|
+
rec.status = 'ok';
|
|
2124
|
+
rec.detail = `${(outcome.valueJson ?? '').length} chars${outcome.logs === undefined ? '' : ` + logs ${outcome.logs.length} chars`}`;
|
|
2125
|
+
// F3:首成功/变化结果完整注入——值在上限内时挂到 rec.output(need_result 通道),
|
|
2126
|
+
// 超限保持骨架 + 句柄形态(中间结果不回灌的红线不破)。
|
|
2127
|
+
const valueJson = outcome.valueJson ?? '';
|
|
2128
|
+
if (observation.payload.kind === 'skeleton' && valueJson.length <= this.#cfg.codeValueInjectLimit) {
|
|
2129
|
+
rec.output = valueJson;
|
|
2130
|
+
}
|
|
2131
|
+
// F5:tf-code 成功(有回执)→ 声明的验收项记为已验证(证据 = 命令 id + 值指纹)
|
|
2132
|
+
this.#markAccepts(cmd, rec.handle, contentFingerprint(valueJson));
|
|
2133
|
+
this.#record({
|
|
2134
|
+
seq: ++DRIVER_SEQ, kind: 'command', id: cmd.id, name: cmd.name, status: 'ok',
|
|
2135
|
+
handle: rec.handle, infoGain: observation.info_gain, detail: rec.detail,
|
|
2136
|
+
});
|
|
2137
|
+
this.#ledgerWrite('plugin:tf-agent/command', {
|
|
2138
|
+
cmdId: cmd.id, name: cmd.name, status: 'ok',
|
|
2139
|
+
handle: rec.handle, infoGain: observation.info_gain, chars: valueJson.length,
|
|
2140
|
+
valueInjected: rec.output !== undefined,
|
|
2141
|
+
enforcement: sandbox?.enforcement,
|
|
2142
|
+
});
|
|
2143
|
+
return;
|
|
2144
|
+
}
|
|
2145
|
+
|
|
2146
|
+
// ---- tf-write / tf-read / tf-edit / tf-append / tf-grep / tf-glob / tf-bash:映射原生工具,单命令批执行 ----
|
|
2147
|
+
let mapped = null;
|
|
2148
|
+
let result ;
|
|
2149
|
+
// F6 写前意图:变更类命令(tf-write/tf-edit/tf-append)在派发到宿主工具**之前**落盘(fsync)。
|
|
2150
|
+
// 崩溃后"有意图无回执"即可判定写入可能已发生 → resume 停机核对。零注入:只进账本。
|
|
2151
|
+
const intentOp = cmd.name === 'tf-write'
|
|
2152
|
+
? 'write'
|
|
2153
|
+
: cmd.name === 'tf-edit'
|
|
2154
|
+
? 'edit'
|
|
2155
|
+
: cmd.name === 'tf-append'
|
|
2156
|
+
? 'append'
|
|
2157
|
+
: null;
|
|
2158
|
+
if (intentOp !== null) {
|
|
2159
|
+
try {
|
|
2160
|
+
this.#ports.onIntent?.({
|
|
2161
|
+
cmdId: cmd.id,
|
|
2162
|
+
op: intentOp,
|
|
2163
|
+
path: cmd.attrs['path'] ?? '',
|
|
2164
|
+
fingerprint: contentFingerprint(cmd.body ?? ''),
|
|
2165
|
+
});
|
|
2166
|
+
} catch (intentError) {
|
|
2167
|
+
// fail-open(红线 6:可选功能 fail-open 且必须告警)——不因意图落盘失败阻断写入
|
|
2168
|
+
this.#warn('F6 写前意图落盘失败(fail-open,继续派发;崩溃窗口内该写入不可判定)', intentError);
|
|
2169
|
+
}
|
|
2170
|
+
}
|
|
2171
|
+
try {
|
|
2172
|
+
mapped = this.#cfg.toolMapping.toToolCall(cmd);
|
|
2173
|
+
if (mapped === null) {
|
|
2174
|
+
// tf-edit body 标记解析失败等:映射层无法产出参数——结构化失败,不静默改全文。
|
|
2175
|
+
rec.status = 'failed';
|
|
2176
|
+
rec.detail = cmd.name === 'tf-edit'
|
|
2177
|
+
? 'tf-edit body 解析失败:需要 "<<<<<<< OLD" / "=======" / ">>>>>>> NEW" 三行标记各出现一次且顺序正确(结构化失败,不做模糊匹配、不改全文)'
|
|
2178
|
+
: `no-tool-mapping:${cmd.name}`;
|
|
2179
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'command', id: cmd.id, name: cmd.name, status: 'failed', detail: rec.detail });
|
|
2180
|
+
this.#ledgerWrite('plugin:tf-agent/command', { cmdId: cmd.id, name: cmd.name, status: 'failed', detail: rec.detail.slice(0, 200) });
|
|
2181
|
+
return;
|
|
2182
|
+
}
|
|
2183
|
+
// v0.3.0(会话格式修复):先广告 tool-call 生命周期,再让宿主工具管线落 tool/call。
|
|
2184
|
+
// 宿主的 v4 校验要求 assistant/message(tool-call) → tool/call → tool/result 三段齐全;
|
|
2185
|
+
// 只写 tool/call 会让整条会话日志被判 corrupt(桌面端历史对话加载失败)。
|
|
2186
|
+
// v0.3.1:广告是流中落盘的 assistant/message——若实时 attempt 还开着,客户端 fold 会把它
|
|
2187
|
+
// 暂存进 pending 且 end 帧只消费一条结算 → 滞留到下一步触发 events.restart()。
|
|
2188
|
+
// 先收束(abandoned)再广告:广告与后续 tool/call、落盘消息全部直接 publish。
|
|
2189
|
+
this.#frameEndAbandonedIfOpen();
|
|
2190
|
+
const advertised = { id: cmd.id, name: mapped.name, arguments: JSON.stringify(mapped.arguments) };
|
|
2191
|
+
try {
|
|
2192
|
+
this.#ports.events?.advertiseToolCalls?.(turn, step, [advertised]);
|
|
2193
|
+
} catch (adError) {
|
|
2194
|
+
this.#warn('tool-call 广告写入失败(fail-open:工具照常派发,但该条会话日志可能不可读)', adError);
|
|
2195
|
+
}
|
|
2196
|
+
result = await this.#ports.executeTools({
|
|
2197
|
+
calls: [{ type: 'tool-call', id: cmd.id, name: advertised.name, arguments: advertised.arguments }],
|
|
2198
|
+
// K4:回合 signal(cancel 时传导;不再用独立且永不触发的 AbortController)
|
|
2199
|
+
signal: this.#commandSignal(),
|
|
2200
|
+
maxParallelToolCalls: 1,
|
|
2201
|
+
...(this.#agentRef === undefined ? {} : { agent: this.#agentRef }),
|
|
2202
|
+
log: safeToolLog(this.#ports, turn, step),
|
|
2203
|
+
});
|
|
2204
|
+
} catch (error) {
|
|
2205
|
+
rec.status = 'failed';
|
|
2206
|
+
rec.detail = isAbortError(error) ? `aborted: 回合取消(K4),未产生后置结果` : describeToolError(error);
|
|
2207
|
+
// v0.3.0:广告已落但派发失败 → 闭合工具生命周期(否则 step/end 留下未解调用)
|
|
2208
|
+
try {
|
|
2209
|
+
this.#ports.events?.repairToolCall?.(turn, step, cmd.id);
|
|
2210
|
+
} catch (repairError) {
|
|
2211
|
+
this.#warn('tool-call 生命周期闭合事件写入失败(fail-open)', repairError);
|
|
2212
|
+
}
|
|
2213
|
+
// F6 写后回执(失败路径):意图闭合为"已发生但失败",不算"无回执"
|
|
2214
|
+
if (intentOp !== null) {
|
|
2215
|
+
try {
|
|
2216
|
+
this.#ports.onIntentReceipt?.({ cmdId: cmd.id, ok: false, detail: rec.detail.slice(0, 120) });
|
|
2217
|
+
} catch (receiptError) {
|
|
2218
|
+
this.#warn('F6 意图回执落盘失败(fail-open)', receiptError);
|
|
2219
|
+
}
|
|
2220
|
+
}
|
|
2221
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'command', id: cmd.id, name: cmd.name, status: 'failed', detail: rec.detail });
|
|
2222
|
+
this.#ledgerWrite('plugin:tf-agent/command', { cmdId: cmd.id, name: cmd.name, status: 'failed', detail: rec.detail.slice(0, 200) });
|
|
2223
|
+
return;
|
|
2224
|
+
}
|
|
2225
|
+
|
|
2226
|
+
const first = result.results[0];
|
|
2227
|
+
// v0.3.0:批次返回里没有本调用的结果(宿主静默丢弃/未派发)→ 补闭合,避免未解广告。
|
|
2228
|
+
if (first === undefined) {
|
|
2229
|
+
try {
|
|
2230
|
+
this.#ports.events?.repairToolCall?.(turn, step, cmd.id);
|
|
2231
|
+
} catch (repairError) {
|
|
2232
|
+
this.#warn('tool-call 生命周期闭合事件写入失败(fail-open)', repairError);
|
|
2233
|
+
}
|
|
2234
|
+
}
|
|
2235
|
+
const contentText = blockTextOf(first?.result?.content);
|
|
2236
|
+
const isError = first?.result?.isError === true;
|
|
2237
|
+
|
|
2238
|
+
// ---- 观测登记(O1 三档返回;失败一律 high)----
|
|
2239
|
+
const observation = this.#obs.observe({
|
|
2240
|
+
tool: cmd.name,
|
|
2241
|
+
ok: !isError,
|
|
2242
|
+
key: observationKey(cmd),
|
|
2243
|
+
content: contentText,
|
|
2244
|
+
callId: cmd.id,
|
|
2245
|
+
});
|
|
2246
|
+
rec.observation = observation;
|
|
2247
|
+
this.#record({
|
|
2248
|
+
seq: ++DRIVER_SEQ, kind: 'observation',
|
|
2249
|
+
handle: observation.handle, key: observationKey(cmd),
|
|
2250
|
+
infoGain: observation.info_gain, reason: observation.reason,
|
|
2251
|
+
});
|
|
2252
|
+
|
|
2253
|
+
if (isError) {
|
|
2254
|
+
rec.status = 'failed';
|
|
2255
|
+
rec.detail = contentText.slice(0, 500);
|
|
2256
|
+
rec.handle = observation.handle ?? undefined;
|
|
2257
|
+
// F6 写后回执(工具级失败路径):意图闭合为"已发生但失败"
|
|
2258
|
+
if (intentOp !== null) {
|
|
2259
|
+
try {
|
|
2260
|
+
this.#ports.onIntentReceipt?.({ cmdId: cmd.id, ok: false, detail: rec.detail.slice(0, 120) });
|
|
2261
|
+
} catch (receiptError) {
|
|
2262
|
+
this.#warn('F6 意图回执落盘失败(fail-open)', receiptError);
|
|
2263
|
+
}
|
|
2264
|
+
}
|
|
2265
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'command', id: cmd.id, name: cmd.name, status: 'failed', detail: rec.detail });
|
|
2266
|
+
this.#ledgerWrite('plugin:tf-agent/command', { cmdId: cmd.id, name: cmd.name, status: 'failed', detail: rec.detail.slice(0, 200) });
|
|
2267
|
+
return;
|
|
2268
|
+
}
|
|
2269
|
+
|
|
2270
|
+
rec.status = 'ok';
|
|
2271
|
+
rec.detail = `${contentText.length} chars`;
|
|
2272
|
+
rec.handle = observation.handle ?? undefined;
|
|
2273
|
+
if (cmd.name === 'tf-write' && typeof cmd.attrs['path'] === 'string') {
|
|
2274
|
+
// 修复限制 1:登记本任务自写路径(tf-read 命中时只注入回执,掐断"写→读回验"循环)
|
|
2275
|
+
this.#writtenPaths.add(normalizeTaskPath(cmd.attrs['path']));
|
|
2276
|
+
}
|
|
2277
|
+
// F6 写后回执(成功路径)
|
|
2278
|
+
if (intentOp !== null) {
|
|
2279
|
+
try {
|
|
2280
|
+
this.#ports.onIntentReceipt?.({ cmdId: cmd.id, ok: true, detail: rec.detail.slice(0, 120) });
|
|
2281
|
+
} catch (receiptError) {
|
|
2282
|
+
this.#warn('F6 意图回执落盘失败(fail-open)', receiptError);
|
|
2283
|
+
}
|
|
2284
|
+
}
|
|
2285
|
+
// F5:命令成功(有回执)→ 声明的验收项记为已验证(证据 = 命令 id + 句柄/指纹)
|
|
2286
|
+
this.#markAccepts(cmd, rec.handle, contentFingerprint(contentText));
|
|
2287
|
+
this.#record({
|
|
2288
|
+
seq: ++DRIVER_SEQ, kind: 'command', id: cmd.id, name: cmd.name, status: 'ok',
|
|
2289
|
+
handle: rec.handle, infoGain: observation.info_gain, detail: rec.detail,
|
|
2290
|
+
});
|
|
2291
|
+
this.#ledgerWrite('plugin:tf-agent/command', {
|
|
2292
|
+
cmdId: cmd.id, name: cmd.name, status: 'ok',
|
|
2293
|
+
handle: rec.handle, infoGain: observation.info_gain, chars: contentText.length,
|
|
2294
|
+
});
|
|
2295
|
+
}
|
|
2296
|
+
|
|
2297
|
+
/** 原生 tool_call 通道:阻塞式执行 + 结果回灌下一请求(信息型工具的即时需求)。 */
|
|
2298
|
+
async #executeNativeCalls(
|
|
2299
|
+
turn ,
|
|
2300
|
+
step ,
|
|
2301
|
+
calls ,
|
|
2302
|
+
signal ,
|
|
2303
|
+
level ,
|
|
2304
|
+
) {
|
|
2305
|
+
let result ;
|
|
2306
|
+
try {
|
|
2307
|
+
result = await this.#ports.executeTools({
|
|
2308
|
+
calls: calls.map((c) => ({ type: 'tool-call' , id: c.id, name: c.name ?? 'unknown', arguments: c.arguments || '{}' })),
|
|
2309
|
+
...(this.#agentRef === undefined ? {} : { agent: this.#agentRef }),
|
|
2310
|
+
signal,
|
|
2311
|
+
log: safeToolLog(this.#ports, turn, step),
|
|
2312
|
+
});
|
|
2313
|
+
} catch (error) {
|
|
2314
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'fault', fault: 'native-tool-batch-error', detail: error instanceof Error ? error.message : String(error) });
|
|
2315
|
+
}
|
|
2316
|
+
// v0.3.0:广告已随 assistant 消息落盘;批次异常/缺项时逐个闭合,避免未解工具生命周期。
|
|
2317
|
+
for (const call of calls) {
|
|
2318
|
+
if (result !== undefined && result.results.some((r) => r.callId === call.id)) continue;
|
|
2319
|
+
try {
|
|
2320
|
+
this.#ports.events?.repairToolCall?.(turn, step, call.id);
|
|
2321
|
+
} catch (repairError) {
|
|
2322
|
+
this.#warn('原生 tool-call 生命周期闭合事件写入失败(fail-open)', repairError);
|
|
2323
|
+
}
|
|
2324
|
+
}
|
|
2325
|
+
const results = (result?.results ?? []).map((r) => ({
|
|
2326
|
+
callId: r.callId,
|
|
2327
|
+
name: calls.find((c) => c.id === r.callId)?.name ?? 'unknown',
|
|
2328
|
+
content: blockTextOf(r.result?.content),
|
|
2329
|
+
isError: r.result?.isError === true,
|
|
2330
|
+
}));
|
|
2331
|
+
for (const _call of calls) this.#ports.onToolSettled?.();
|
|
2332
|
+
if (results.length === 0 || level === 'final-only') return;
|
|
2333
|
+
|
|
2334
|
+
// 原生通道结果即需求(阻塞语义):注入易变尾,下一请求立即可见。
|
|
2335
|
+
// F4:仅在声明了 nativeToolSchemas(原生通道显式启用)时执行上限策略——
|
|
2336
|
+
// 首成功/短结果完整注入;超限块登记 obs 并转"骨架 + 句柄",杜绝全量回灌。
|
|
2337
|
+
const capped = this.#cfg.nativeToolSchemasEnabled === true;
|
|
2338
|
+
const blocks = results.map((r) => {
|
|
2339
|
+
if (!capped || r.isError || r.content.length <= this.#cfg.nativeResultLimit) {
|
|
2340
|
+
return {
|
|
2341
|
+
role: 'user' ,
|
|
2342
|
+
content: `[tf-stream:tool-result callId=${r.callId} tool=${r.name}${r.isError ? ' isError=true' : ''}]\n${r.content}`,
|
|
2343
|
+
};
|
|
2344
|
+
}
|
|
2345
|
+
const observation = this.#obs.observe({
|
|
2346
|
+
tool: r.name,
|
|
2347
|
+
ok: true,
|
|
2348
|
+
key: `native:${r.name}:${r.callId}`,
|
|
2349
|
+
content: r.content,
|
|
2350
|
+
callId: r.callId,
|
|
2351
|
+
});
|
|
2352
|
+
const skeleton = observation.payload.kind === 'skeleton' ? observation.payload.rendered : '';
|
|
2353
|
+
this.#record({
|
|
2354
|
+
seq: ++DRIVER_SEQ, kind: 'observation',
|
|
2355
|
+
handle: observation.handle, key: `native:${r.name}:${r.callId}`,
|
|
2356
|
+
infoGain: observation.info_gain, reason: `${observation.reason}:native-capped`,
|
|
2357
|
+
});
|
|
2358
|
+
return {
|
|
2359
|
+
role: 'user' ,
|
|
2360
|
+
content: `[tf-stream:tool-result callId=${r.callId} tool=${r.name}] ${r.content.length} 字符超出原生通道注入上限(${this.#cfg.nativeResultLimit}),已句柄化:${skeleton}\n(原文用 tf-peek handle="${observation.handle ?? ''}" from_line=.. to_line=.. 取回)`,
|
|
2361
|
+
};
|
|
2362
|
+
});
|
|
2363
|
+
this.#injectedChars += blocks.reduce((n, b) => n + b.content.length, 0);
|
|
2364
|
+
this.#pendingNativeBlocks.push(...blocks);
|
|
2365
|
+
}
|
|
2366
|
+
|
|
2367
|
+
#pendingNativeBlocks = [];
|
|
2368
|
+
|
|
2369
|
+
// ------------------------------------------------------------------ drain / 收束
|
|
2370
|
+
|
|
2371
|
+
async #drain() {
|
|
2372
|
+
while (this.#inFlight.size > 0) {
|
|
2373
|
+
await Promise.allSettled([...this.#inFlight]);
|
|
2374
|
+
// 全部落定后再开一轮派发(依赖在 drain 期间满足的命令)
|
|
2375
|
+
this.#dispatchReady(this.#turnCounter, 0);
|
|
2376
|
+
}
|
|
2377
|
+
}
|
|
2378
|
+
|
|
2379
|
+
/** 流末重试延迟的 peek(同流乐观 peek;句柄已由 drain 期间完成的命令注册)。
|
|
2380
|
+
* 仍无此句柄才按失败注入——上游"信息工具先等之前的写入"的驱动器侧闭环。 */
|
|
2381
|
+
async #resolveDeferredPeeks(turn , step ) {
|
|
2382
|
+
const deferred = this.#deferredPeeks;
|
|
2383
|
+
this.#deferredPeeks = [];
|
|
2384
|
+
for (const { rec } of deferred) {
|
|
2385
|
+
if (rec.status !== 'dispatched') continue; // 已被其它路径终结
|
|
2386
|
+
const handle = rec.cmd.attrs['handle'] ?? '';
|
|
2387
|
+
const from = Number(rec.cmd.attrs['from_line'] ?? '1');
|
|
2388
|
+
const to = rec.cmd.attrs['to_line'] === undefined ? Number.MAX_SAFE_INTEGER : Number(rec.cmd.attrs['to_line']);
|
|
2389
|
+
const content = this.#obs.peek(handle, from, to);
|
|
2390
|
+
if (content === null) {
|
|
2391
|
+
rec.status = 'failed';
|
|
2392
|
+
rec.detail = `unknown-handle:${handle}`;
|
|
2393
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'command', id: rec.cmd.id, name: rec.cmd.name, status: 'failed', detail: rec.detail });
|
|
2394
|
+
this.#ledgerWrite('plugin:tf-agent/command', { cmdId: rec.cmd.id, name: rec.cmd.name, status: 'failed', detail: rec.detail });
|
|
2395
|
+
continue;
|
|
2396
|
+
}
|
|
2397
|
+
rec.status = 'ok';
|
|
2398
|
+
rec.output = content;
|
|
2399
|
+
rec.detail = `${content.length} chars`;
|
|
2400
|
+
rec.handle = handle;
|
|
2401
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'command', id: rec.cmd.id, name: rec.cmd.name, status: 'ok', handle, detail: rec.detail });
|
|
2402
|
+
this.#ledgerWrite('plugin:tf-agent/command', { cmdId: rec.cmd.id, name: rec.cmd.name, status: 'ok', handle, chars: content.length });
|
|
2403
|
+
}
|
|
2404
|
+
}
|
|
2405
|
+
|
|
2406
|
+
/**
|
|
2407
|
+
* 结构化重入事由收集(仅三种:失败/拒绝、依赖未满足)。
|
|
2408
|
+
* 收集即上报:同一命令只注入一次(模型修复与否由它自己负责,tf-final 是最终裁决)。
|
|
2409
|
+
*/
|
|
2410
|
+
#collectIssues() {
|
|
2411
|
+
const issues = [];
|
|
2412
|
+
for (const rec of this.#commands.values()) {
|
|
2413
|
+
if (rec.status === 'failed' || rec.status === 'rejected') {
|
|
2414
|
+
if (this.#reportedIssues.has(rec.cmd.id)) continue;
|
|
2415
|
+
this.#reportedIssues.add(rec.cmd.id);
|
|
2416
|
+
issues.push({
|
|
2417
|
+
cmdId: rec.cmd.id,
|
|
2418
|
+
name: rec.cmd.name,
|
|
2419
|
+
target: rec.cmd.attrs['path'] ?? rec.cmd.attrs['cmd'] ?? rec.cmd.attrs['handle'] ?? '',
|
|
2420
|
+
reason: rec.detail ?? 'unknown',
|
|
2421
|
+
suggestion: suggestFor(rec.cmd),
|
|
2422
|
+
});
|
|
2423
|
+
} else if (rec.status === 'pending') {
|
|
2424
|
+
// drain 后仍 pending:依赖永不满足(依赖失败 / 依赖 id 不存在)
|
|
2425
|
+
const missing = rec.cmd.depends_on.filter((d) => {
|
|
2426
|
+
const dep = this.#commands.get(d);
|
|
2427
|
+
return dep === undefined || dep.status !== 'ok';
|
|
2428
|
+
});
|
|
2429
|
+
if (missing.length > 0) {
|
|
2430
|
+
rec.status = 'failed';
|
|
2431
|
+
rec.detail = `依赖未满足:${missing.join(', ')}`;
|
|
2432
|
+
if (this.#reportedIssues.has(rec.cmd.id)) continue;
|
|
2433
|
+
this.#reportedIssues.add(rec.cmd.id);
|
|
2434
|
+
this.#record({ seq: ++DRIVER_SEQ, kind: 'command', id: rec.cmd.id, name: rec.cmd.name, status: 'failed', detail: rec.detail });
|
|
2435
|
+
issues.push({
|
|
2436
|
+
cmdId: rec.cmd.id,
|
|
2437
|
+
name: rec.cmd.name,
|
|
2438
|
+
target: rec.cmd.attrs['path'] ?? rec.cmd.attrs['cmd'] ?? '',
|
|
2439
|
+
reason: rec.detail,
|
|
2440
|
+
suggestion: `依赖 ${missing.join(', ')} 未成功(失败或不存在)。请检查依赖 id 是否正确,或改道重发本命令。`,
|
|
2441
|
+
});
|
|
2442
|
+
}
|
|
2443
|
+
}
|
|
2444
|
+
}
|
|
2445
|
+
return issues;
|
|
2446
|
+
}
|
|
2447
|
+
|
|
2448
|
+
/** 组装易变尾注入块(结构化错误 / high 骨架 / peek 结果 / 原生工具结果)。 */
|
|
2449
|
+
#buildInjections(issues , level ) {
|
|
2450
|
+
const blocks = [];
|
|
2451
|
+
let highInjected = false;
|
|
2452
|
+
|
|
2453
|
+
// 1. 结构化失败/拒绝/依赖错误(三种重入事由之一;final-only 档除外——预算已枯竭)
|
|
2454
|
+
if (level !== 'final-only') {
|
|
2455
|
+
for (const issue of issues) {
|
|
2456
|
+
blocks.push({
|
|
2457
|
+
role: 'user',
|
|
2458
|
+
content: `[tf-stream:error id=${issue.cmdId} cmd=${issue.name}${issue.target ? ` target=${issue.target}` : ''}] ${issue.reason}\n建议:${issue.suggestion}`,
|
|
2459
|
+
});
|
|
2460
|
+
}
|
|
2461
|
+
}
|
|
2462
|
+
|
|
2463
|
+
// 2. high 观测反馈(info_gain=high;none/low 永不注入;final-only 停止)
|
|
2464
|
+
// v0.2 语义对齐上游 ThinkFlow:"成功结果按序完整反馈一次"(省 token 的主因是消灭回合数,
|
|
2465
|
+
// 不是骨架——2026-11-15 真连证据:模型不 peek 直接幻觉确认,R2/R4/C1 因此失败)。
|
|
2466
|
+
// tf-read 成功 → 注入完整原文;超过 READ_FEEDBACK_LIMIT 截断为中段省略 + 头尾保留,
|
|
2467
|
+
// 并提示 tf-peek 精确取回;骨架只作为超大文件的替代形态。
|
|
2468
|
+
if (level === 'normal' || level === 'high-only') {
|
|
2469
|
+
for (const rec of this.#commands.values()) {
|
|
2470
|
+
const obs = rec.observation;
|
|
2471
|
+
if (obs === undefined || obs.info_gain !== 'high') continue;
|
|
2472
|
+
// 失败命令的 obs 也是 high,但失败走结构化错误块,这里跳过(避免双重注入)
|
|
2473
|
+
if (rec.status !== 'ok') continue;
|
|
2474
|
+
if (obs.payload.kind !== 'skeleton') continue;
|
|
2475
|
+
if (this.#reportedObservations.has(obs.seq)) continue;
|
|
2476
|
+
this.#reportedObservations.add(obs.seq);
|
|
2477
|
+
let body ;
|
|
2478
|
+
if (rec.cmd.name === 'tf-read') {
|
|
2479
|
+
const full = this.#obs.peek(obs.handle ?? '', 1, Number.MAX_SAFE_INTEGER);
|
|
2480
|
+
// 修复限制 1:自写回验 receipt——tf-read 命中本任务 tf-write 已写过的路径时,
|
|
2481
|
+
// 全文就在模型上下文里,不再重复回灌(掐断"写→读回验"循环,写批任务的主要 token 开销)。
|
|
2482
|
+
const selfWritten = this.#cfg.selfReadFeedback !== 'full'
|
|
2483
|
+
&& typeof rec.cmd.attrs['path'] === 'string'
|
|
2484
|
+
&& this.#writtenPaths.has(normalizeTaskPath(rec.cmd.attrs['path']));
|
|
2485
|
+
if (selfWritten) {
|
|
2486
|
+
const lines = full === null ? 'unknown' : String(full.split('\n').length);
|
|
2487
|
+
const fp = full === null ? 'unavailable' : contentFingerprint(full);
|
|
2488
|
+
blocks.push({
|
|
2489
|
+
role: 'user',
|
|
2490
|
+
// v0.3.2 文案修正:写入正文不回灌——跨流步骤后"全文已在你的上下文中"是假的
|
|
2491
|
+
// (真机 session-8f22c7a0:模型自述 "I don't have the exact text visible",
|
|
2492
|
+
// 被迫全量重写四个文件)。如实说明 + 给 tf-peek 取回路径。
|
|
2493
|
+
content: `[tf-stream:receipt handle=${obs.handle ?? ''} path=${rec.cmd.attrs['path']} lines=${lines} sha256=${fp}]`
|
|
2494
|
+
+ `\n该路径由你本任务的 tf-write 写入,写入成功(写失败会有 [tf-stream:error];没有错误注入即写成功)。`
|
|
2495
|
+
+ `写入正文不回灌(回验纪律)——若它是在更早的流步骤写的,你当前上下文里没有原文。`
|
|
2496
|
+
+ `需要原文(全量或行段)用 tf-peek handle="${obs.handle}" 取回;需要修改用 tf-edit 的 OLD 精确字面量可先 tf-peek 取回后再改。`,
|
|
2497
|
+
});
|
|
2498
|
+
highInjected = true;
|
|
2499
|
+
continue;
|
|
2500
|
+
}
|
|
2501
|
+
body = readFeedbackBody(full, obs.payload.rendered, this.#cfg.readFeedbackLimit ?? DEFAULT_READ_FEEDBACK_LIMIT);
|
|
2502
|
+
} else if (rec.cmd.name === 'tf-code' && rec.output !== undefined) {
|
|
2503
|
+
// F3:code 结果可见性——上限内的首成功/变化值完整注入(省一次 tf-peek 往返);
|
|
2504
|
+
// 句柄仍然有效,需要原文行段时照常 tf-peek。仅 tf-code 显式开启时此路径可达。
|
|
2505
|
+
body = rec.output;
|
|
2506
|
+
} else {
|
|
2507
|
+
body = obs.payload.rendered;
|
|
2508
|
+
}
|
|
2509
|
+
blocks.push({
|
|
2510
|
+
role: 'user',
|
|
2511
|
+
content: `[tf-stream:observation handle=${obs.handle ?? ''} key=${observationKey(rec.cmd)}]\n${body}\n(细节用 tf-peek handle="${obs.handle}" from_line=.. to_line=.. 取回)`,
|
|
2512
|
+
});
|
|
2513
|
+
highInjected = true;
|
|
2514
|
+
}
|
|
2515
|
+
}
|
|
2516
|
+
|
|
2517
|
+
// 3. tf-peek 结果(need_result 通道;high-only/final-only 档暂停——预算紧张先保失败通道)
|
|
2518
|
+
if (level === 'normal') {
|
|
2519
|
+
for (const rec of this.#commands.values()) {
|
|
2520
|
+
if (rec.cmd.name !== 'tf-peek' || rec.status !== 'ok') continue;
|
|
2521
|
+
if (this.#reportedPeeks.has(rec.cmd.id)) continue;
|
|
2522
|
+
this.#reportedPeeks.add(rec.cmd.id);
|
|
2523
|
+
blocks.push({
|
|
2524
|
+
role: 'user',
|
|
2525
|
+
content: `[tf-stream:peek handle=${rec.cmd.attrs['handle'] ?? ''} lines=${rec.cmd.attrs['from_line'] ?? 1}-${rec.cmd.attrs['to_line'] ?? 'end'}]\n${rec.output ?? ''}`,
|
|
2526
|
+
});
|
|
2527
|
+
}
|
|
2528
|
+
}
|
|
2529
|
+
|
|
2530
|
+
// 4. F5 计划差分(只注差分:新计划全量一次,此后只注变化——新增/验证/移除;净增 ≤0 的关键)
|
|
2531
|
+
if (this.#cfg.enablePlan && this.#plan !== null) {
|
|
2532
|
+
const announced = this.#planAnnounced;
|
|
2533
|
+
const planBlock = renderPlanDiff(this.#plan.revision, this.#plan.items, announced);
|
|
2534
|
+
if (planBlock !== null) blocks.push({ role: 'user', content: planBlock });
|
|
2535
|
+
// 更新已宣布快照(与本次注入一致;空差分不推进——下请求继续携带)
|
|
2536
|
+
if (announced === null) {
|
|
2537
|
+
this.#planAnnounced = new Map([...this.#plan.items].map(([id, item]) => [id, item.status]));
|
|
2538
|
+
} else if (planBlock !== null) {
|
|
2539
|
+
for (const [id, status] of this.#plan.items) announced.set(id, status);
|
|
2540
|
+
for (const id of [...announced.keys()]) {
|
|
2541
|
+
if (!this.#plan.items.has(id)) announced.delete(id);
|
|
2542
|
+
}
|
|
2543
|
+
}
|
|
2544
|
+
}
|
|
2545
|
+
|
|
2546
|
+
// 5. 原生 tool_call 结果(阻塞通道回灌,任意档都注入——它们是模型的即时需求)
|
|
2547
|
+
blocks.push(...this.#pendingNativeBlocks);
|
|
2548
|
+
this.#pendingNativeBlocks = [];
|
|
2549
|
+
|
|
2550
|
+
return { blocks, highInjected };
|
|
2551
|
+
}
|
|
2552
|
+
|
|
2553
|
+
// ------------------------------------------------------------------ 账本
|
|
2554
|
+
|
|
2555
|
+
#record(record ) {
|
|
2556
|
+
this.#records.push(record);
|
|
2557
|
+
}
|
|
2558
|
+
|
|
2559
|
+
#ledgerWrite(type , data ) {
|
|
2560
|
+
if (this.#ledger === undefined) return;
|
|
2561
|
+
try {
|
|
2562
|
+
this.#ledger.record(type, data);
|
|
2563
|
+
} catch (error) {
|
|
2564
|
+
// 账本落盘失败不毁任务:内存 records 已有全量事实,告警出口保证不静默(红线 5)
|
|
2565
|
+
this.#warn(`ledger 落盘失败(${type}),事实已保留在内存 records`, error);
|
|
2566
|
+
}
|
|
2567
|
+
}
|
|
2568
|
+
}
|
|
2569
|
+
|
|
2570
|
+
function safeToolLog(ports , turn , step ) {
|
|
2571
|
+
try {
|
|
2572
|
+
return ports.events?.toolLog(turn, step);
|
|
2573
|
+
} catch {
|
|
2574
|
+
return undefined;
|
|
2575
|
+
}
|
|
2576
|
+
}
|
|
2577
|
+
|
|
2578
|
+
/** 任务内路径规范化(自写回验判定用):统一分隔符;大小写保留(不做平台猜测试)。 */
|
|
2579
|
+
function normalizeTaskPath(path ) {
|
|
2580
|
+
return path.replace(/\\/g, '/');
|
|
2581
|
+
}
|
|
2582
|
+
|
|
2583
|
+
/** 内容指纹(receipt 行):sha256 前 16 位十六进制——够对账,不泄露内容。 */
|
|
2584
|
+
function contentFingerprint(content ) {
|
|
2585
|
+
return createHash('sha256').update(content, 'utf8').digest('hex').slice(0, 16);
|
|
2586
|
+
}
|
|
2587
|
+
|
|
2588
|
+
/** 命令指纹(重复 id 幂等判定):名称 + 属性 + 正文(tf-write)。确定性序列化。 */
|
|
2589
|
+
function commandFingerprint(cmd ) {
|
|
2590
|
+
const attrs = Object.keys(cmd.attrs).sort().map((k) => `${k}=${cmd.attrs[k]}`).join('&');
|
|
2591
|
+
return `${cmd.name}|${attrs}|${cmd.body ?? ''}`;
|
|
2592
|
+
}
|
|
2593
|
+
|
|
2594
|
+
/** tf-read 成功反馈的完整原文默认上限(字符)——超过则头尾保留、中段省略。
|
|
2595
|
+
* 8000 字符 ≈ 4k tokens:上游 ThinkFlow 实证"省 token 主因是消灭回合数",完整反馈
|
|
2596
|
+
* 远省于基线的多回合重读;截断边界 lottery(恰好切掉答案行)在 2026-11-15 sanity 实测,
|
|
2597
|
+
* 故阈值取宽。 */
|
|
2598
|
+
export const DEFAULT_READ_FEEDBACK_LIMIT = 8000;
|
|
2599
|
+
|
|
2600
|
+
function readFeedbackBody(full , skeleton , limit ) {
|
|
2601
|
+
if (full === null) return `${skeleton}\n(原文不可取回,仅骨架;tf-peek 可按行段重试)`;
|
|
2602
|
+
if (full.length <= limit) return full;
|
|
2603
|
+
const headCut = Math.max(0, Math.floor(limit * 0.7));
|
|
2604
|
+
const tailCut = Math.max(0, Math.floor(limit * 0.2));
|
|
2605
|
+
const omitted = full.length - headCut - tailCut;
|
|
2606
|
+
return `${full.slice(0, headCut)}\n……(中段省略 ${omitted} 字符;tf-peek handle=<句柄> from_line=.. to_line=.. 精确取回)……\n${full.slice(full.length - tailCut)}`;
|
|
2607
|
+
}
|
|
2608
|
+
|
|
2609
|
+
/** v0.3.1 截断修复:可回灌原结果的重复命令(信息类,无副作用)。
|
|
2610
|
+
* 模型把同一条读/搜/命令又发一次时,原实现只回"duplicate-idempotent(handle=…)"——
|
|
2611
|
+
* 上下文里已没有内容(观测只在易变尾注入一次),模型拿不到任何事实,只能再猜再读,
|
|
2612
|
+
* 直到用占位 final 收场。幂等语义不变(不重复执行),但把原结果回灌一次。 */
|
|
2613
|
+
const REPLAYABLE_COMMANDS = new Set(['tf-read', 'tf-grep', 'tf-glob', 'tf-bash']);
|
|
2614
|
+
|
|
2615
|
+
/** 每回合最多回灌次数(防"模型原地打转 → 每步都回灌"的 token 黑洞;超限记 fault 不静默) */
|
|
2616
|
+
const MAX_REPLAY_INJECTIONS = 4;
|
|
2617
|
+
|
|
2618
|
+
/** K4:识别取消类错误(AbortError / DOMException AbortError / 显式 abort 消息),与超时分账。 */
|
|
2619
|
+
function isAbortError(error ) {
|
|
2620
|
+
if (error instanceof Error) {
|
|
2621
|
+
return error.name === 'AbortError'
|
|
2622
|
+
|| (error ).code === 20
|
|
2623
|
+
|| /(^|\b)(abort|aborted)(\b|$)/i.test(error.message);
|
|
2624
|
+
}
|
|
2625
|
+
return false;
|
|
2626
|
+
}
|
|
2627
|
+
|
|
2628
|
+
/** 工具批失败取因:ToolBatchExecutionError 把真实错误包在 cause/partial 里(dsh-tools
|
|
2629
|
+
* shared-DTdn5dXO.js),只记 message 会把根因吞掉(2026-11-15 真连 W1 教训)。 */
|
|
2630
|
+
function describeToolError(error ) {
|
|
2631
|
+
const top = error instanceof Error ? error.message : String(error);
|
|
2632
|
+
const cause = (error )?.cause;
|
|
2633
|
+
const parts = [top];
|
|
2634
|
+
let cur = cause;
|
|
2635
|
+
for (let depth = 0; cur !== undefined && depth < 4; depth += 1) {
|
|
2636
|
+
if (cur instanceof Error) {
|
|
2637
|
+
parts.push(`cause: ${cur.message}`);
|
|
2638
|
+
cur = (cur ).cause;
|
|
2639
|
+
} else if (cur !== null && typeof cur === 'object') {
|
|
2640
|
+
const partial = (cur ).partial ?? cur;
|
|
2641
|
+
parts.push(`cause: ${JSON.stringify(partial).slice(0, 400)}`);
|
|
2642
|
+
cur = (cur ).cause;
|
|
2643
|
+
} else {
|
|
2644
|
+
parts.push(`cause: ${String(cur)}`);
|
|
2645
|
+
cur = undefined;
|
|
2646
|
+
}
|
|
2647
|
+
}
|
|
2648
|
+
return parts.join(' | ').slice(0, 500);
|
|
2649
|
+
}
|
|
2650
|
+
|
|
2651
|
+
function suggestFor(cmd ) {
|
|
2652
|
+
if (cmd.name === 'tf-write') return '请换一个可写的路径重发(可换新 id 避免冲突),或修正文件内容后重试。';
|
|
2653
|
+
if (cmd.name === 'tf-bash') return '请检查命令本身(语法/依赖/工作目录),修正后重发,或改道用 tf-write 落地产物。';
|
|
2654
|
+
if (cmd.name === 'tf-read') return '请确认路径存在(可先用 tf-bash ls 查看),或改用其他来源。';
|
|
2655
|
+
if (cmd.name === 'tf-peek') return 'handle 必须来自句柄目录增量(obs:<family>:<callId>@v<version>),请核对后重发。';
|
|
2656
|
+
if (cmd.name === 'tf-code') {
|
|
2657
|
+
return '请按错误诊断修复程序体(语法/绑定参数/超时),换新 id 重发;简单场景可改道 tf-bash 或 tf-write。';
|
|
2658
|
+
}
|
|
2659
|
+
return '请根据失败原因修正后重发该命令(可换新 id)。';
|
|
2660
|
+
}
|
|
2661
|
+
|
|
2662
|
+
function observationKey(cmd ) {
|
|
2663
|
+
const base = cmd.attrs['path'] ?? cmd.attrs['cmd'] ?? cmd.attrs['handle'];
|
|
2664
|
+
if (base !== undefined) return base;
|
|
2665
|
+
// tf-code 没有稳定目标:description 优先,缺省用程序体指纹(同 id 重复才归并,不同程序各自成 key)
|
|
2666
|
+
if (cmd.name === 'tf-code') {
|
|
2667
|
+
return cmd.attrs['description'] !== undefined
|
|
2668
|
+
? `code:${cmd.attrs['description']}`
|
|
2669
|
+
: `code:${contentFingerprint(cmd.body ?? '')}`;
|
|
2670
|
+
}
|
|
2671
|
+
return cmd.name;
|
|
2672
|
+
}
|
|
2673
|
+
|
|
2674
|
+
/**
|
|
2675
|
+
* F5 计划差分渲染:首个计划注全量清单;其后只注变化(新增 / 已验证 / 已移除)。
|
|
2676
|
+
* 无变化返回 null(不产生任何块——请求体积不变)。计划状态本身在驱动器侧,
|
|
2677
|
+
* 请求里永远只出现差分(净增 ≤0 的关键设计)。
|
|
2678
|
+
*/
|
|
2679
|
+
function renderPlanDiff(
|
|
2680
|
+
revision ,
|
|
2681
|
+
items ,
|
|
2682
|
+
announced ,
|
|
2683
|
+
) {
|
|
2684
|
+
const lines = [];
|
|
2685
|
+
if (announced === null) {
|
|
2686
|
+
// 首次:全量清单一次(带每项当前验证状态)
|
|
2687
|
+
lines.push(`[tf-stream:plan v${revision}]`, '任务计划与验收项(完成对应命令时用 accepts="<id>" 声明回执;全部验收项有回执后 tf-final 才会通过):');
|
|
2688
|
+
for (const [id, item] of items) {
|
|
2689
|
+
lines.push(item.status === 'verified'
|
|
2690
|
+
? `- [${id}] ${item.text} ✓ 已验证(回执:${item.evidence ?? '-'})`
|
|
2691
|
+
: `- [${id}] ${item.text}(未验证)`);
|
|
2692
|
+
}
|
|
2693
|
+
return lines.join('\n');
|
|
2694
|
+
}
|
|
2695
|
+
const added = [];
|
|
2696
|
+
const verified = [];
|
|
2697
|
+
const removed = [];
|
|
2698
|
+
for (const [id, item] of items) {
|
|
2699
|
+
const prev = announced.get(id);
|
|
2700
|
+
if (prev === undefined) added.push(`+ [${id}] ${item.text}`);
|
|
2701
|
+
else if (prev === 'open' && item.status === 'verified') verified.push(`✓ [${id}] 已验证(回执:${item.evidence ?? '-'})`);
|
|
2702
|
+
}
|
|
2703
|
+
for (const id of announced.keys()) {
|
|
2704
|
+
if (!items.has(id)) removed.push(`- [${id}] 已从计划移除`);
|
|
2705
|
+
}
|
|
2706
|
+
if (added.length === 0 && verified.length === 0 && removed.length === 0) return null;
|
|
2707
|
+
lines.push(`[tf-stream:plan-diff v${revision}]`);
|
|
2708
|
+
lines.push(...added, ...verified, ...removed);
|
|
2709
|
+
return lines.join('\n');
|
|
2710
|
+
}
|
|
2711
|
+
|
|
2712
|
+
function blockTextOf(content ) {
|
|
2713
|
+
if (content === undefined || content === null) return '';
|
|
2714
|
+
if (typeof content === 'string') return content;
|
|
2715
|
+
if (Array.isArray(content)) {
|
|
2716
|
+
return content.map((block) => {
|
|
2717
|
+
if (typeof block === 'string') return block;
|
|
2718
|
+
if (block !== null && typeof block === 'object' && 'text' in block && typeof (block ).text === 'string') {
|
|
2719
|
+
return (block ).text;
|
|
2720
|
+
}
|
|
2721
|
+
return JSON.stringify(block);
|
|
2722
|
+
}).join('\n');
|
|
2723
|
+
}
|
|
2724
|
+
return String(content);
|
|
2725
|
+
}
|
|
2726
|
+
|
|
2727
|
+
function finishDetail(finish ) {
|
|
2728
|
+
if (finish.kind === 'error') return `${finishCode(finish)}: ${finishMessage(finish)}`;
|
|
2729
|
+
return finishMessage(finish);
|
|
2730
|
+
}
|
|
2731
|
+
|
|
2732
|
+
/** RenderMessage → GenerateOptions.messages 线格式(loop-built 请求:首条 system 携带系统提示)。 */
|
|
2733
|
+
function toWireMessages(messages ) {
|
|
2734
|
+
// v0.3.2:assistant 消息必须携带 source(宿主 LlmRuntime.forAdapter 无防护读
|
|
2735
|
+
// `message.source.replayState`,GitHub master 同源;缺失 = 流 error → 回合中断)。
|
|
2736
|
+
return messages.map((m) => ({
|
|
2737
|
+
role: m.role,
|
|
2738
|
+
content: [{ type: 'text' , text: m.content }],
|
|
2739
|
+
...(m.source === undefined ? {} : { source: { ...m.source } }),
|
|
2740
|
+
}));
|
|
2741
|
+
}
|
|
2742
|
+
|
|
2743
|
+
/**
|
|
2744
|
+
* 流归一化 shim(镜像 LlmRuntime.stream 的异常归一化契约,types.d.ts:456)。
|
|
2745
|
+
* 真实宿主路径不需要(ctx.llm.stream 已归一化);离线直连适配器(mock)时使用。
|
|
2746
|
+
*/
|
|
2747
|
+
export function normalizeStreamShim(inner ) {
|
|
2748
|
+
let finished = false;
|
|
2749
|
+
async function* run() {
|
|
2750
|
+
try {
|
|
2751
|
+
for await (const chunk of inner) {
|
|
2752
|
+
if (chunk.type === 'finish') finished = true;
|
|
2753
|
+
yield chunk;
|
|
2754
|
+
}
|
|
2755
|
+
} catch (error) {
|
|
2756
|
+
if (!finished) {
|
|
2757
|
+
finished = true;
|
|
2758
|
+
yield {
|
|
2759
|
+
type: 'finish',
|
|
2760
|
+
reason: {
|
|
2761
|
+
kind: 'error',
|
|
2762
|
+
message: error instanceof Error ? error.message : String(error),
|
|
2763
|
+
code: 'ADAPTER_THROWN',
|
|
2764
|
+
},
|
|
2765
|
+
};
|
|
2766
|
+
}
|
|
2767
|
+
}
|
|
2768
|
+
}
|
|
2769
|
+
return run();
|
|
2770
|
+
}
|
|
2771
|
+
|
|
2772
|
+
// ---------------------------------------------------------------------------
|
|
2773
|
+
// 会话事件写入器(真实宿主路径;形状镜像内建 loop 的 append 调用)
|
|
2774
|
+
// ---------------------------------------------------------------------------
|
|
2775
|
+
|
|
2776
|
+
/**
|
|
2777
|
+
* 会话日志 assistant 消息的 model source(v0.3.2 修复)。
|
|
2778
|
+
* 宿主校验器(dsh-session assertMessageEventShape → hasProviderModel)要求
|
|
2779
|
+
* `source = {kind:'model', provider:<非空字符串>, model:<非空字符串>}`;缺 provider/model
|
|
2780
|
+
* 的日志在读取时抛 `message must have model source`,整条会话被判 corrupt——桌面端
|
|
2781
|
+
* 表现为"历史加载失败"。0.3.1 及更早版本只写了 `{kind:'model'}`,本类型把实时
|
|
2782
|
+
* provider/model 带进写入路径(applySelection 换模后随动)。
|
|
2783
|
+
*/
|
|
2784
|
+
/** v0.3.2:assistant 消息的宿主来源(会话日志 source 与请求装配的 RenderMessage.source
|
|
2785
|
+
* 共用)。kind 固定 'model'(宿主 forAdapter/validateReplay 都先读 source.kind)。 */
|
|
2786
|
+
|
|
2787
|
+
|
|
2788
|
+
|
|
2789
|
+
|
|
2790
|
+
|
|
2791
|
+
|
|
2792
|
+
/**
|
|
2793
|
+
* 从 duck-typed Session 构造 TurnEventWriter。
|
|
2794
|
+
* 事件形状对照:turn/start {turn}(:731)、step/start {turn,step}(:757)、
|
|
2795
|
+
* step/end {turn,step}(:781)、turn/end {turn,reason}(:819)、
|
|
2796
|
+
* assistant/message {turn,step,message,usage?,stream}(:949,surfaceOp:'append')、
|
|
2797
|
+
* assistant/attempt {turn,step,stream}(:924)。assistant message 形状镜像
|
|
2798
|
+
* dsh-llm createAssistantMessage(lib/types/message.js:64-73):{id, role:'assistant',
|
|
2799
|
+
* content:[{type:'text',text}], source:{kind:'model', provider, model}}(探针 C 实测可写)。
|
|
2800
|
+
*
|
|
2801
|
+
* v0.3.2:modelInfo 在**写入时**调用(不缓存)——applySelection 运行时换模后随动;
|
|
2802
|
+
* 缺省(离线/无模型路由信息)时 provider/model 落 'unknown',保证日志形状仍可通过
|
|
2803
|
+
* 宿主校验(空字符串同样会被 hasProviderModel 拒绝)。
|
|
2804
|
+
*/
|
|
2805
|
+
export function createSessionEventWriter(session , modelInfo ) {
|
|
2806
|
+
const s = session ;
|
|
2807
|
+
if (s === undefined || typeof s.append !== 'function') return undefined;
|
|
2808
|
+
const append = (type , data , opts ) => {
|
|
2809
|
+
s.append (type, data, opts);
|
|
2810
|
+
};
|
|
2811
|
+
/** v0.3.1:带结算信息的 append(seq 供 assistant-stream end 帧配对)。 */
|
|
2812
|
+
const appendSettling = (type , data , opts ) => {
|
|
2813
|
+
const appended = s.append (type, data, opts) ;
|
|
2814
|
+
return { eventType: type, ...(appended !== null && typeof appended === 'object' && typeof appended.seq === 'number' ? { seq: appended.seq } : {}) };
|
|
2815
|
+
};
|
|
2816
|
+
return {
|
|
2817
|
+
turnStart(turn) {
|
|
2818
|
+
append('turn/start', { turn });
|
|
2819
|
+
},
|
|
2820
|
+
stepStart(turn, step) {
|
|
2821
|
+
append('step/start', { turn, step });
|
|
2822
|
+
},
|
|
2823
|
+
assistantMessage(turn, step, text, info) {
|
|
2824
|
+
const usageField = info.usage === undefined ? {} : { usage: info.usage };
|
|
2825
|
+
const toolCalls = info.toolCalls ?? [];
|
|
2826
|
+
const reasoning = info.reasoning;
|
|
2827
|
+
if (info.finish.kind === 'error' || info.finish.kind === 'aborted') {
|
|
2828
|
+
if (text.length > 0) {
|
|
2829
|
+
// 中断但有部分正文:assistant/message + interrupted(镜像内建 :891-905)
|
|
2830
|
+
return appendSettling('assistant/message', {
|
|
2831
|
+
turn, step,
|
|
2832
|
+
message: makeAssistantMessage(text, [], reasoning, modelInfo?.()),
|
|
2833
|
+
interrupted: true,
|
|
2834
|
+
...usageField,
|
|
2835
|
+
stream: [],
|
|
2836
|
+
}, { surfaceOp: 'append' });
|
|
2837
|
+
}
|
|
2838
|
+
return appendSettling('assistant/attempt', { turn, step, stream: [] });
|
|
2839
|
+
}
|
|
2840
|
+
if (text.length === 0 && toolCalls.length === 0) {
|
|
2841
|
+
// 成功终止但无文本也无原生调用:assistant/attempt(镜像内建 :906-915 的空内容分支)
|
|
2842
|
+
return appendSettling('assistant/attempt', { turn, step, stream: [] });
|
|
2843
|
+
}
|
|
2844
|
+
return appendSettling('assistant/message', {
|
|
2845
|
+
turn, step,
|
|
2846
|
+
message: makeAssistantMessage(text, toolCalls, reasoning, modelInfo?.()),
|
|
2847
|
+
...usageField,
|
|
2848
|
+
stream: [],
|
|
2849
|
+
}, { surfaceOp: 'append' });
|
|
2850
|
+
},
|
|
2851
|
+
advertiseToolCalls(turn, step, calls) {
|
|
2852
|
+
if (calls.length === 0) return;
|
|
2853
|
+
// v0.3.0:v4 会话格式的工具生命周期广告。形状 = 内建 loop 的 assistant/message
|
|
2854
|
+
// (content 里的 tool-call 块),arguments 必须与随后 tool/call 里的字符串逐字节相同
|
|
2855
|
+
// (宿主校验器用严格相等比对 name/arguments)。
|
|
2856
|
+
append('assistant/message', {
|
|
2857
|
+
turn, step,
|
|
2858
|
+
message: makeAssistantMessage('', calls, undefined, modelInfo?.()),
|
|
2859
|
+
stream: [],
|
|
2860
|
+
}, { surfaceOp: 'append' });
|
|
2861
|
+
},
|
|
2862
|
+
repairToolCall(turn, step, callId) {
|
|
2863
|
+
// v0.3.0:派发异常后的生命周期闭合。先读会话快照确认事实,已有 result 就什么都不写
|
|
2864
|
+
// (重复 result 会让日志再次 corrupt)。
|
|
2865
|
+
const snap = (s ).snapshotEvents;
|
|
2866
|
+
const events = typeof snap === 'function' ? snap.call(s) : [];
|
|
2867
|
+
let started = false;
|
|
2868
|
+
let settled = false;
|
|
2869
|
+
for (const event of events) {
|
|
2870
|
+
const e = event ;
|
|
2871
|
+
if (e.type === 'tool/call' && e.data?.callId === callId) started = true;
|
|
2872
|
+
if (e.type === 'tool/result' && e.data?.message?.toolCallId === callId) settled = true;
|
|
2873
|
+
}
|
|
2874
|
+
if (settled) return;
|
|
2875
|
+
if (started) {
|
|
2876
|
+
append('tool/result', {
|
|
2877
|
+
turn, step,
|
|
2878
|
+
message: {
|
|
2879
|
+
id: `tool-result-${callId}-${randomUUID()}`,
|
|
2880
|
+
role: 'tool',
|
|
2881
|
+
source: { kind: 'tool', callId },
|
|
2882
|
+
toolCallId: callId,
|
|
2883
|
+
isError: true,
|
|
2884
|
+
content: [{ type: 'text', text: 'Error: tool call ended without a recorded result(插件在派发异常后补写的闭合结果)' }],
|
|
2885
|
+
},
|
|
2886
|
+
}, { surfaceOp: 'append' });
|
|
2887
|
+
return;
|
|
2888
|
+
}
|
|
2889
|
+
// 未开始:宿主 v4 校验唯一接受的形状(notStartedRepair:id 前缀 / 固定正文 /
|
|
2890
|
+
// error.name=ToolNotStartedError + code=TOOL_NOT_STARTED / 无 sourceEventSeqs)。
|
|
2891
|
+
append('tool/result', {
|
|
2892
|
+
turn, step,
|
|
2893
|
+
message: {
|
|
2894
|
+
id: `interrupted-tool-result-${callId}-0`,
|
|
2895
|
+
role: 'tool',
|
|
2896
|
+
source: { kind: 'tool', callId },
|
|
2897
|
+
toolCallId: callId,
|
|
2898
|
+
isError: true,
|
|
2899
|
+
content: [{ type: 'text', text: 'The tool call was interrupted before the Harness recorded it as started. Retry it if it is still needed.' }],
|
|
2900
|
+
},
|
|
2901
|
+
error: { name: 'ToolNotStartedError', code: 'TOOL_NOT_STARTED' },
|
|
2902
|
+
}, { surfaceOp: 'append' });
|
|
2903
|
+
},
|
|
2904
|
+
stepEnd(turn, step) {
|
|
2905
|
+
append('step/end', { turn, step });
|
|
2906
|
+
},
|
|
2907
|
+
turnEnd(turn, reason) {
|
|
2908
|
+
append('turn/end', { turn, reason });
|
|
2909
|
+
},
|
|
2910
|
+
finalAnswer(turn, step, text) {
|
|
2911
|
+
append('assistant/message', {
|
|
2912
|
+
turn, step,
|
|
2913
|
+
message: makeAssistantMessage(text, [], undefined, modelInfo?.()),
|
|
2914
|
+
stream: [],
|
|
2915
|
+
}, { surfaceOp: 'append' });
|
|
2916
|
+
},
|
|
2917
|
+
toolLog(turn, step) {
|
|
2918
|
+
return { turn, step };
|
|
2919
|
+
},
|
|
2920
|
+
};
|
|
2921
|
+
}
|
|
2922
|
+
|
|
2923
|
+
|
|
2924
|
+
|
|
2925
|
+
/**
|
|
2926
|
+
* 构造 assistant 消息(形状镜像 dsh-llm createAssistantMessage,lib/types/message.js:64-73)。
|
|
2927
|
+
* v0.3.2:source 必须携带非空 provider/model(宿主 hasProviderModel 校验,缺了整条日志
|
|
2928
|
+
* 判 corrupt);缺写入方未提供或为空串时落 'unknown'——日志保持可加载,不谎报模型。
|
|
2929
|
+
*/
|
|
2930
|
+
function makeAssistantMessage(text , toolCalls = [], reasoning , modelInfo ) {
|
|
2931
|
+
const content = [];
|
|
2932
|
+
// v0.3.1:reasoning 块在首位(镜像内建 BlockAssembler 的流序:思考先于正文)。
|
|
2933
|
+
if (reasoning !== undefined && reasoning.trim() !== '') content.push({ type: 'reasoning', text: reasoning });
|
|
2934
|
+
if (text.length > 0) content.push({ type: 'text', text });
|
|
2935
|
+
for (const call of toolCalls) content.push({ type: 'tool-call', id: call.id, name: call.name, arguments: call.arguments });
|
|
2936
|
+
const provider = modelInfo?.provider !== undefined && modelInfo.provider !== '' ? modelInfo.provider : 'unknown';
|
|
2937
|
+
const model = modelInfo?.model !== undefined && modelInfo.model !== '' ? modelInfo.model : 'unknown';
|
|
2938
|
+
return {
|
|
2939
|
+
id: randomUUID(),
|
|
2940
|
+
role: 'assistant',
|
|
2941
|
+
content,
|
|
2942
|
+
source: { kind: 'model', provider, model },
|
|
2943
|
+
};
|
|
2944
|
+
}
|
|
2945
|
+
|
|
2946
|
+
// ---------------------------------------------------------------------------
|
|
2947
|
+
// ③ StreamLoopAgent —— duck-typed Agent(dsh-agent/lib/types/runtime-types.d.ts 的运行面)
|
|
2948
|
+
// ---------------------------------------------------------------------------
|
|
2949
|
+
|
|
2950
|
+
|
|
2951
|
+
|
|
2952
|
+
|
|
2953
|
+
|
|
2954
|
+
|
|
2955
|
+
|
|
2956
|
+
|
|
2957
|
+
|
|
2958
|
+
|
|
2959
|
+
|
|
2960
|
+
|
|
2961
|
+
|
|
2962
|
+
|
|
2963
|
+
|
|
2964
|
+
|
|
2965
|
+
|
|
2966
|
+
|
|
2967
|
+
|
|
2968
|
+
|
|
2969
|
+
|
|
2970
|
+
|
|
2971
|
+
|
|
2972
|
+
|
|
2973
|
+
|
|
2974
|
+
|
|
2975
|
+
|
|
2976
|
+
/**
|
|
2977
|
+
* StreamLoopAgent:headless 消费的最小运行面(dsh-headless/lib/index.js:336-376 实测):
|
|
2978
|
+
* .id / .session / .status / .model / .whenIdle() / .followup(message) /
|
|
2979
|
+
* .cancel(cause, options?) / .ctx(工具管线用)。
|
|
2980
|
+
* 不是 Cordis Service(本地插件无 cordis 副本可用,见文件头);生命周期由工厂的 dispose 承担。
|
|
2981
|
+
*/
|
|
2982
|
+
export class StreamLoopAgent {
|
|
2983
|
+
id ;
|
|
2984
|
+
session ;
|
|
2985
|
+
ctx ;
|
|
2986
|
+
#driver ;
|
|
2987
|
+
#storedHandle ;
|
|
2988
|
+
#warning ;
|
|
2989
|
+
#inbox = [];
|
|
2990
|
+
#status = 'idle';
|
|
2991
|
+
#running ;
|
|
2992
|
+
#cancelCause ;
|
|
2993
|
+
#selection ;
|
|
2994
|
+
#disposeScope ;
|
|
2995
|
+
#disposed = false;
|
|
2996
|
+
/** v0.3.2:agent/status 发射出口(宿主事件总线;缺省 = 不发)。 */
|
|
2997
|
+
#emitStatus = undefined;
|
|
2998
|
+
|
|
2999
|
+
constructor(deps ) {
|
|
3000
|
+
this.id = deps.id;
|
|
3001
|
+
this.session = deps.session;
|
|
3002
|
+
this.#driver = deps.driver;
|
|
3003
|
+
this.#storedHandle = deps.storedHandle;
|
|
3004
|
+
this.#warning = deps.onWarning ?? (() => {});
|
|
3005
|
+
this.#emitStatus = deps.emitStatus;
|
|
3006
|
+
this.#selection = deps.modelSelection ?? { provider: '', model: '' };
|
|
3007
|
+
// 作用域 key = agent 实例本身(镜像内建 createScope(loopCtx, this))。宿主工具执行器
|
|
3008
|
+
// selectExecutor(input.agent) 与守卫 chainLayers(exec.agent) 都按 scopeChainOf(agent)
|
|
3009
|
+
// 选层(dsh-tools / dsh-tools-guards rc.3):key 用别的对象时永远解析到根层——
|
|
3010
|
+
// desktop/web 组合的根层没有 fs/shell 工具(standard.patch.yml 挪进了 preset 层)。
|
|
3011
|
+
if (deps.scopeModule !== undefined && deps.ctx !== undefined && deps.ctx !== null) {
|
|
3012
|
+
try {
|
|
3013
|
+
const scope = deps.scopeModule.createScope(deps.ctx, this);
|
|
3014
|
+
this.ctx = scope.ctx;
|
|
3015
|
+
this.#disposeScope = () => scope.dispose();
|
|
3016
|
+
debugTrace('agent.scope.minted', { id: this.id });
|
|
3017
|
+
} catch (error) {
|
|
3018
|
+
this.ctx = deps.ctx;
|
|
3019
|
+
this.#warning(`agent "${this.id}": dsh-scope.createScope 失败:回退 ownerCtx(桌面端 preset 绑定/工具解析可能失败)`, error);
|
|
3020
|
+
}
|
|
3021
|
+
} else {
|
|
3022
|
+
this.ctx = deps.ctx;
|
|
3023
|
+
}
|
|
3024
|
+
}
|
|
3025
|
+
|
|
3026
|
+
get status() {
|
|
3027
|
+
return this.#status;
|
|
3028
|
+
}
|
|
3029
|
+
|
|
3030
|
+
/** dsh-agent runtime-types.d.ts:46-64 Model 面。 */
|
|
3031
|
+
get model()
|
|
3032
|
+
|
|
3033
|
+
|
|
3034
|
+
{
|
|
3035
|
+
return {
|
|
3036
|
+
current: () => (this.#selection.provider === '' ? undefined : { ...this.#selection }),
|
|
3037
|
+
select: (selection) => {
|
|
3038
|
+
this.#selection = { ...selection };
|
|
3039
|
+
this.#driver.applySelection(selection);
|
|
3040
|
+
// model/selection 是 known-event 类型(dsh-session known-event-types.js);shape = ModelSelection
|
|
3041
|
+
this.#appendSessionEvent('model/selection', { ...selection });
|
|
3042
|
+
},
|
|
3043
|
+
};
|
|
3044
|
+
}
|
|
3045
|
+
|
|
3046
|
+
/** 提交一条用户消息(headless:361 的入口)。语义:入队 → 空闲时开新回合。 */
|
|
3047
|
+
followup(message ) {
|
|
3048
|
+
if (this.#disposed) throw new Error(`agent "${this.id}": followup after dispose`);
|
|
3049
|
+
const text = message.content
|
|
3050
|
+
.map((block) => (typeof block === 'object' && block !== null && 'text' in block && typeof (block ).text === 'string' ? (block ).text : ''))
|
|
3051
|
+
.join('\n');
|
|
3052
|
+
if (text.trim() === '') throw new Error(`agent "${this.id}": followup 消息没有文本内容`);
|
|
3053
|
+
debugTrace('followup', { id: this.id, chars: text.length });
|
|
3054
|
+
// 会话落盘(user/message 是 surface 事件,须 surfaceOp:'append';镜像内建 :865)
|
|
3055
|
+
this.#appendSessionEvent('user/message', message, { surfaceOp: 'append' });
|
|
3056
|
+
this.#inbox.push({ text, message });
|
|
3057
|
+
if (this.#status === 'idle') this.#startNextTurn();
|
|
3058
|
+
}
|
|
3059
|
+
|
|
3060
|
+
/** 桌面端 prompt(mode:'steer') 入口(dsh-api-session-controller prompt:38770)。
|
|
3061
|
+
* 修复限制 2(对齐内建语义):回合运行中 → 注入运行中回合的下一步(下一请求装配时
|
|
3062
|
+
* 进追加区,[tf-stream:steer] 用户块);单流"流内不打断"前提不变——不掐当前流。
|
|
3063
|
+
* 空闲 → 与内建一致按新回合任务处理(插队队首)。 */
|
|
3064
|
+
steer(message ) {
|
|
3065
|
+
if (this.#disposed) throw new Error(`agent "${this.id}": steer after dispose`);
|
|
3066
|
+
const text = message.content
|
|
3067
|
+
.map((block) => (typeof block === 'object' && block !== null && 'text' in block && typeof (block ).text === 'string' ? (block ).text : ''))
|
|
3068
|
+
.join('\n');
|
|
3069
|
+
if (text.trim() === '') throw new Error(`agent "${this.id}": steer 消息没有文本内容`);
|
|
3070
|
+
debugTrace('steer', { id: this.id, chars: text.length, running: this.#status === 'running' });
|
|
3071
|
+
this.#appendSessionEvent('user/message', message, { surfaceOp: 'append' });
|
|
3072
|
+
if (this.#status === 'running') {
|
|
3073
|
+
this.#driver.pushSteer(text, message);
|
|
3074
|
+
return;
|
|
3075
|
+
}
|
|
3076
|
+
this.#inbox.unshift({ text, message });
|
|
3077
|
+
if (this.#status === 'idle') this.#startNextTurn();
|
|
3078
|
+
}
|
|
3079
|
+
|
|
3080
|
+
/** v0.3.2:桌面端命令路径的通知注入(dsh-user-approval setPolicy:127 实测调用
|
|
3081
|
+
* `agent.inject(...)`——0.3.1 缺这个方法,改审批策略的命令以
|
|
3082
|
+
* "agent.inject is not a function" 报错收场)。镜像内建 send(input,'next-step',false):
|
|
3083
|
+
* 落盘 + 并入"下一步"装配,但**不唤醒空闲 agent**(通知型注入不该自己开回合)。
|
|
3084
|
+
* pendingSteers 在 runTurn 的每次请求前消费(含下一回合首请求)——无论运行中还是
|
|
3085
|
+
* 空闲都走同一通道,下一请求必然可见;steer/inject 的区别只在唤醒,与内建一致。 */
|
|
3086
|
+
inject(message ) {
|
|
3087
|
+
if (this.#disposed) throw new Error(`agent "${this.id}": inject after dispose`);
|
|
3088
|
+
const text = message.content
|
|
3089
|
+
.map((block) => (typeof block === 'object' && block !== null && 'text' in block && typeof (block ).text === 'string' ? (block ).text : ''))
|
|
3090
|
+
.join('\n');
|
|
3091
|
+
debugTrace('inject', { id: this.id, chars: text.length, running: this.#status === 'running' });
|
|
3092
|
+
this.#appendSessionEvent('user/message', message, { surfaceOp: 'append' });
|
|
3093
|
+
if (text.trim() === '') return;
|
|
3094
|
+
this.#driver.pushSteer(text, message);
|
|
3095
|
+
}
|
|
3096
|
+
|
|
3097
|
+
/** 桌面端空内容续跑路径读取的 inbox 面(prompt:37548)。修复限制 2 后:
|
|
3098
|
+
* nextStep 如实暴露尚未消费的 steer(已注入装配历史的从队列移除);
|
|
3099
|
+
* nextTurn 恒为空(单流没有跨回合排队注入)。 */
|
|
3100
|
+
get inbox() {
|
|
3101
|
+
return { nextTurn: [], nextStep: [...this.#driver.pendingSteerMessages] };
|
|
3102
|
+
}
|
|
3103
|
+
|
|
3104
|
+
/** 桌面端维护包裹(prompt/agent 生命周期路径)。无独立维护面 → 直通透传。 */
|
|
3105
|
+
runMaintenance (operation ) {
|
|
3106
|
+
return operation();
|
|
3107
|
+
}
|
|
3108
|
+
|
|
3109
|
+
/** dsh-agent runtime-types.d.ts:191 whenIdle:回合与队列全部落定后 resolve。 */
|
|
3110
|
+
whenIdle() {
|
|
3111
|
+
if (this.#running !== undefined) return this.#running;
|
|
3112
|
+
return Promise.resolve();
|
|
3113
|
+
}
|
|
3114
|
+
|
|
3115
|
+
/** dsh-agent runtime-types.d.ts:184 cancel。keepInbox 缺省 true(保留待处理输入)。 */
|
|
3116
|
+
cancel(cause , options ) {
|
|
3117
|
+
const keepInbox = options?.keepInbox ?? true;
|
|
3118
|
+
this.#cancelCause = { cause, keepInbox };
|
|
3119
|
+
this.#driver.cancel(cause);
|
|
3120
|
+
if (!keepInbox) this.#inbox.length = 0;
|
|
3121
|
+
}
|
|
3122
|
+
|
|
3123
|
+
/** 取消并释放(工厂 dispose 的内部路径)。 */
|
|
3124
|
+
async dispose() {
|
|
3125
|
+
if (this.#disposed) return;
|
|
3126
|
+
this.#disposed = true;
|
|
3127
|
+
if (this.#cancelCause === undefined) this.cancel(new Error(`agent "${this.id}" lifecycle disposed`), { keepInbox: true });
|
|
3128
|
+
try {
|
|
3129
|
+
await this.#running;
|
|
3130
|
+
} catch (error) {
|
|
3131
|
+
this.#warning(`agent "${this.id}": 回合协程退出异常(dispose 吸收并告警,不静默)`, error);
|
|
3132
|
+
}
|
|
3133
|
+
try {
|
|
3134
|
+
await this.#storedHandle?.close();
|
|
3135
|
+
} catch (error) {
|
|
3136
|
+
this.#warning(`agent "${this.id}": 持久化句柄关闭失败`, error);
|
|
3137
|
+
}
|
|
3138
|
+
try {
|
|
3139
|
+
await this.#disposeScope?.();
|
|
3140
|
+
} catch (error) {
|
|
3141
|
+
this.#warning(`agent "${this.id}": agent scope 释放失败(不阻断 dispose)`, error);
|
|
3142
|
+
}
|
|
3143
|
+
}
|
|
3144
|
+
|
|
3145
|
+
/** v0.3.2:运行态转换统一出口(只在真正变化时发 agent/status,镜像内建 setPhase 语义)。
|
|
3146
|
+
* 发射失败不阻断回合(fail-open,告警不静默)。 */
|
|
3147
|
+
#setStatus(next ) {
|
|
3148
|
+
if (this.#status === next) return;
|
|
3149
|
+
this.#status = next;
|
|
3150
|
+
try {
|
|
3151
|
+
this.#emitStatus?.({ agent: this, status: next });
|
|
3152
|
+
} catch (error) {
|
|
3153
|
+
this.#warning(`agent "${this.id}": agent/status 发射失败(不阻断回合)`, error);
|
|
3154
|
+
}
|
|
3155
|
+
}
|
|
3156
|
+
|
|
3157
|
+
/** 开下一回合(inbox 逐条串行驱动)。 */
|
|
3158
|
+
#startNextTurn() {
|
|
3159
|
+
const next = this.#inbox.shift();
|
|
3160
|
+
if (next === undefined) return;
|
|
3161
|
+
this.#setStatus('running');
|
|
3162
|
+
this.#running = (async () => {
|
|
3163
|
+
try {
|
|
3164
|
+
this.#driver.pushUserTask(next.text);
|
|
3165
|
+
await this.#driver.runTurn();
|
|
3166
|
+
} catch (error) {
|
|
3167
|
+
// fail-open:回合异常必须浮出(headless 靠 whenIdle 拒绝感知失败);告警出口保证有日志
|
|
3168
|
+
this.#warning(`agent "${this.id}": 回合异常上抛`, error);
|
|
3169
|
+
throw error;
|
|
3170
|
+
} finally {
|
|
3171
|
+
this.#running = undefined;
|
|
3172
|
+
if (this.#cancelCause !== undefined) {
|
|
3173
|
+
this.#setStatus('idle');
|
|
3174
|
+
if (!this.#cancelCause.keepInbox) this.#inbox.length = 0;
|
|
3175
|
+
this.#cancelCause = undefined;
|
|
3176
|
+
return;
|
|
3177
|
+
}
|
|
3178
|
+
if (this.#inbox.length > 0 && !this.#disposed) {
|
|
3179
|
+
this.#startNextTurn();
|
|
3180
|
+
return;
|
|
3181
|
+
}
|
|
3182
|
+
this.#setStatus('idle');
|
|
3183
|
+
}
|
|
3184
|
+
})();
|
|
3185
|
+
}
|
|
3186
|
+
|
|
3187
|
+
#appendSessionEvent(type , data , opts ) {
|
|
3188
|
+
const session = this.session ;
|
|
3189
|
+
if (session === undefined || typeof session.append !== 'function') return;
|
|
3190
|
+
try {
|
|
3191
|
+
const appended = session.append(type, data, opts);
|
|
3192
|
+
debugTrace('session.append', { type, seq: (appended )?.seq });
|
|
3193
|
+
} catch (error) {
|
|
3194
|
+
this.#warning(`agent "${this.id}": 会话事件 ${type} 写入失败(fail-open 继续,事实见内存台账)`, error);
|
|
3195
|
+
}
|
|
3196
|
+
}
|
|
3197
|
+
}
|
|
3198
|
+
|
|
3199
|
+
// ---------------------------------------------------------------------------
|
|
3200
|
+
// ④ createStreamAgentFactory —— AgentFactory(dsh-agent/lib/types/index.d.ts:155-190)
|
|
3201
|
+
// ---------------------------------------------------------------------------
|
|
3202
|
+
|
|
3203
|
+
|
|
3204
|
+
|
|
3205
|
+
|
|
3206
|
+
|
|
3207
|
+
|
|
3208
|
+
|
|
3209
|
+
/**
|
|
3210
|
+
* sessions.prepare() 返回原始 Session(rc.3 实测:内建 loop 用 SessionPreparation.create
|
|
3211
|
+
* 包一层才得到 {session, [dispose]},dsh-session/lib/index.js:949-973)。这里归一化两种形态。
|
|
3212
|
+
*/
|
|
3213
|
+
function normalizePreparation(raw ) {
|
|
3214
|
+
if (raw !== null && typeof raw === 'object' && 'session' in (raw )) {
|
|
3215
|
+
return raw ;
|
|
3216
|
+
}
|
|
3217
|
+
return { session: raw };
|
|
3218
|
+
}
|
|
3219
|
+
|
|
3220
|
+
|
|
3221
|
+
|
|
3222
|
+
|
|
3223
|
+
|
|
3224
|
+
|
|
3225
|
+
|
|
3226
|
+
|
|
3227
|
+
|
|
3228
|
+
|
|
3229
|
+
|
|
3230
|
+
|
|
3231
|
+
|
|
3232
|
+
|
|
3233
|
+
|
|
3234
|
+
|
|
3235
|
+
|
|
3236
|
+
|
|
3237
|
+
/**
|
|
3238
|
+
* 会话持久化面(宿主 sessionPersistence 与本地 JSONL 降级实现的结构公共面)。
|
|
3239
|
+
* 形状逐字段对应 initialize 内的 duck-type 用法(create/open/append/read/header)。
|
|
3240
|
+
*/
|
|
3241
|
+
|
|
3242
|
+
|
|
3243
|
+
|
|
3244
|
+
|
|
3245
|
+
|
|
3246
|
+
|
|
3247
|
+
|
|
3248
|
+
|
|
3249
|
+
|
|
3250
|
+
|
|
3251
|
+
|
|
3252
|
+
|
|
3253
|
+
|
|
3254
|
+
|
|
3255
|
+
|
|
3256
|
+
|
|
3257
|
+
|
|
3258
|
+
|
|
3259
|
+
|
|
3260
|
+
|
|
3261
|
+
|
|
3262
|
+
|
|
3263
|
+
|
|
3264
|
+
|
|
3265
|
+
|
|
3266
|
+
|
|
3267
|
+
|
|
3268
|
+
|
|
3269
|
+
|
|
3270
|
+
|
|
3271
|
+
|
|
3272
|
+
|
|
3273
|
+
|
|
3274
|
+
|
|
3275
|
+
|
|
3276
|
+
|
|
3277
|
+
|
|
3278
|
+
|
|
3279
|
+
|
|
3280
|
+
|
|
3281
|
+
|
|
3282
|
+
|
|
3283
|
+
|
|
3284
|
+
|
|
3285
|
+
|
|
3286
|
+
|
|
3287
|
+
|
|
3288
|
+
|
|
3289
|
+
|
|
3290
|
+
|
|
3291
|
+
|
|
3292
|
+
|
|
3293
|
+
|
|
3294
|
+
|
|
3295
|
+
|
|
3296
|
+
|
|
3297
|
+
|
|
3298
|
+
|
|
3299
|
+
|
|
3300
|
+
|
|
3301
|
+
function assertSessionId(id ) {
|
|
3302
|
+
if (typeof id !== 'string' || id.trim() === '') {
|
|
3303
|
+
throw new Error(`[stream-loop] sessionId must be a non-empty string, got ${String(id)}`);
|
|
3304
|
+
}
|
|
3305
|
+
}
|
|
3306
|
+
|
|
3307
|
+
// ---------------------------------------------------------------------------
|
|
3308
|
+
// dsh-scope 作用域获取(桌面端 Agent preset 绑定的硬要求)
|
|
3309
|
+
// ---------------------------------------------------------------------------
|
|
3310
|
+
|
|
3311
|
+
|
|
3312
|
+
|
|
3313
|
+
|
|
3314
|
+
|
|
3315
|
+
|
|
3316
|
+
|
|
3317
|
+
|
|
3318
|
+
|
|
3319
|
+
async function unwrapScopeModule(mod ) {
|
|
3320
|
+
const m = mod ;
|
|
3321
|
+
if (typeof m?.createScope === 'function') return m ;
|
|
3322
|
+
if (typeof m?.default?.createScope === 'function') return m.default ;
|
|
3323
|
+
return undefined;
|
|
3324
|
+
}
|
|
3325
|
+
|
|
3326
|
+
let dshScopeCache ;
|
|
3327
|
+
const hostModuleCache = new Map ();
|
|
3328
|
+
|
|
3329
|
+
/** 获取宿主同源的模块(bundle 形态下 bare import 不可达,必须走宿主 loader 的 internal 通道):
|
|
3330
|
+
* ① entry ctx 的 loader.import(bare 名走 loader 的 internal 通道 → 宿主副本);
|
|
3331
|
+
* ② loader.internal.import 直达;
|
|
3332
|
+
* ③ 普通 dynamic import(本地 node_modules 形态可用;bundle 形态解析失败)。
|
|
3333
|
+
* 全部失败返回 undefined(调用方按需降级/fail-open)。 */
|
|
3334
|
+
async function acquireHostModule(ctx , specifier ) {
|
|
3335
|
+
const cached = hostModuleCache.get(specifier);
|
|
3336
|
+
if (cached !== undefined) return cached;
|
|
3337
|
+
const operation = (async () => {
|
|
3338
|
+
const anyCtx = ctx
|
|
3339
|
+
|
|
3340
|
+
|
|
3341
|
+
|
|
3342
|
+
|
|
3343
|
+
;
|
|
3344
|
+
// v0.2.1:loader 是可选服务——Cordis 下裸读会抛 "cannot get property ... without inject",
|
|
3345
|
+
// 必须走安全探测(cordis-compat.ts 顶部记录了完整事故链)。
|
|
3346
|
+
const loader = getService (ctx, 'loader');
|
|
3347
|
+
if (typeof loader?.import === 'function') {
|
|
3348
|
+
try {
|
|
3349
|
+
return await loader.import(specifier);
|
|
3350
|
+
} catch { /* 降级下一路径 */ }
|
|
3351
|
+
}
|
|
3352
|
+
const internal = loader?.internal;
|
|
3353
|
+
if (typeof internal?.import === 'function') {
|
|
3354
|
+
try {
|
|
3355
|
+
return await internal.import(specifier, undefined, {});
|
|
3356
|
+
} catch { /* 降级下一路径 */ }
|
|
3357
|
+
}
|
|
3358
|
+
try {
|
|
3359
|
+
return await import(specifier);
|
|
3360
|
+
} catch { /* 全路径不可达 */ }
|
|
3361
|
+
return undefined;
|
|
3362
|
+
})();
|
|
3363
|
+
hostModuleCache.set(specifier, operation);
|
|
3364
|
+
return operation;
|
|
3365
|
+
}
|
|
3366
|
+
|
|
3367
|
+
/** 获取宿主同源的 dsh-scope 模块(kScope Symbol 必须与宿主同一实例)。
|
|
3368
|
+
* 全部失败返回 undefined(调用方降级 ownerCtx——headless 不受影响,桌面端 preset 绑定会失败)。 */
|
|
3369
|
+
async function acquireDshScope(ctx ) {
|
|
3370
|
+
dshScopeCache ??= acquireHostModule(ctx, '@deepseek-ai/dsh-scope').then((mod) => unwrapScopeModule(mod));
|
|
3371
|
+
return dshScopeCache;
|
|
3372
|
+
}
|
|
3373
|
+
|
|
3374
|
+
/**
|
|
3375
|
+
* AgentFactory 实现(F1 路线:全局 setFactory 槽位;内建 loop 用 profile patch 停用)。
|
|
3376
|
+
* 创建序列镜像 dsh-agent-loop/lib/index.js:1668-1703(createAgent)与 :1710-1775(resume):
|
|
3377
|
+
* sessions.prepare → persistence.create/open → enter/announce 双公告 → setup → {agent, dispose}。
|
|
3378
|
+
* 与内建实现的差异(如实记录,详见 results 文档):
|
|
3379
|
+
* - agentCtx = ownerCtx(无 cordis 副本,agent 级 scope 不可用);
|
|
3380
|
+
* - ReactLoopAgent 换成 StreamLoopAgent(无 cordis scope,生命周期由 dispose 显式承担);
|
|
3381
|
+
* - resume 的 interruptedTurnClosers 修复未复刻(全量 seed 重放,开放 turn 由缺失的 turn/end 呈现)。
|
|
3382
|
+
*/
|
|
3383
|
+
export function createStreamAgentFactory(deps )
|
|
3384
|
+
|
|
3385
|
+
|
|
3386
|
+
{
|
|
3387
|
+
const warning = deps.onWarning ?? (() => {});
|
|
3388
|
+
|
|
3389
|
+
async function initialize(ownerCtx , args
|
|
3390
|
+
|
|
3391
|
+
|
|
3392
|
+
|
|
3393
|
+
|
|
3394
|
+
|
|
3395
|
+
|
|
3396
|
+
|
|
3397
|
+
|
|
3398
|
+
|
|
3399
|
+
|
|
3400
|
+
|
|
3401
|
+
|
|
3402
|
+
|
|
3403
|
+
|
|
3404
|
+
|
|
3405
|
+
) {
|
|
3406
|
+
const sessions = deps.ctx.sessions;
|
|
3407
|
+
if (sessions === undefined || typeof sessions.prepare !== 'function') {
|
|
3408
|
+
throw new Error('[stream-loop] ctx.sessions.prepare 不可用:无法创建 agent(需要 dsh-session 服务族在位)');
|
|
3409
|
+
}
|
|
3410
|
+
let preparation = normalizePreparation(sessions.prepare(args.sessionId, args.prepareOpts));
|
|
3411
|
+
let stored = args.stored;
|
|
3412
|
+
try {
|
|
3413
|
+
if (stored === undefined && args.persistence !== undefined) {
|
|
3414
|
+
try {
|
|
3415
|
+
stored = {
|
|
3416
|
+
handle: await args.persistence.create((preparation.session ).header, {
|
|
3417
|
+
...(args.prepareOpts.inheritedEventCount === undefined ? {} : { inheritedEventCount: args.prepareOpts.inheritedEventCount }),
|
|
3418
|
+
...(args.signal === undefined ? {} : { signal: args.signal }),
|
|
3419
|
+
}),
|
|
3420
|
+
storedCount: 0,
|
|
3421
|
+
};
|
|
3422
|
+
} catch (error) {
|
|
3423
|
+
// 桌面端 UI 对失败的草稿会话会以同一 sessionId 重试 create:冲突 → 转 resume 语义
|
|
3424
|
+
// 打开已有日志(seed 冷读),不让 "session already exists" 打死会话创建。
|
|
3425
|
+
if (!/already exists/i.test(detailString(error))) throw error;
|
|
3426
|
+
debugTrace('create.conflict.fallback-resume', { sessionId: args.sessionId });
|
|
3427
|
+
const open = (args.persistence
|
|
3428
|
+
|
|
3429
|
+
|
|
3430
|
+
|
|
3431
|
+
|
|
3432
|
+
|
|
3433
|
+
|
|
3434
|
+
).open;
|
|
3435
|
+
if (open === undefined) throw error;
|
|
3436
|
+
const handle = await open.call(args.persistence, args.sessionId, 'write', args.signal === undefined ? {} : { signal: args.signal });
|
|
3437
|
+
try {
|
|
3438
|
+
const coldRead = await handle.read(0);
|
|
3439
|
+
const events = [...coldRead.events];
|
|
3440
|
+
preparation[Symbol.dispose]?.();
|
|
3441
|
+
preparation = normalizePreparation(sessions.prepare(args.sessionId, {
|
|
3442
|
+
...args.prepareOpts,
|
|
3443
|
+
seed: events,
|
|
3444
|
+
...(handle.header === undefined ? {} : { meta: handle.header }),
|
|
3445
|
+
...(handle.inheritedEventCount === undefined ? {} : { inheritedEventCount: handle.inheritedEventCount }),
|
|
3446
|
+
...(coldRead.eventState === undefined ? {} : { eventState: coldRead.eventState }),
|
|
3447
|
+
}));
|
|
3448
|
+
stored = { handle, storedCount: events.length };
|
|
3449
|
+
} catch (openError) {
|
|
3450
|
+
await handle.close().catch(() => {});
|
|
3451
|
+
throw openError;
|
|
3452
|
+
}
|
|
3453
|
+
}
|
|
3454
|
+
}
|
|
3455
|
+
|
|
3456
|
+
debugTrace('createAgent.enter', { sessionId: args.sessionId, source: args.source });
|
|
3457
|
+
|
|
3458
|
+
// Agent 级 scoped context:在 StreamLoopAgent 构造内以 agent 实例本身为 key 铸造
|
|
3459
|
+
// (镜像内建 createScope(loopCtx, this)——宿主工具执行器 selectExecutor(input.agent) 与
|
|
3460
|
+
// 守卫 chainLayers(exec.agent) 都按 scopeChainOf(agent) 选层,key 不是 agent 实例时
|
|
3461
|
+
// preset 层工具(desktop/web 组合的 write/edit/pwsh)永远解析不到)。此处只取同源模块。
|
|
3462
|
+
const dshScope = await acquireDshScope(deps.ctx);
|
|
3463
|
+
|
|
3464
|
+
// 修复限制 3:本地 JSONL 持久化路径需要事件镜像——包装会话 append(原型链透传,
|
|
3465
|
+
// snapshotEvents/header 等行为不变);宿主持久化路径不加包装(checkpoint 机制在宿主侧)。
|
|
3466
|
+
let driverSession = preparation.session;
|
|
3467
|
+
if (args.persistenceIsFallback === true && stored !== undefined) {
|
|
3468
|
+
const storedHandle = stored.handle;
|
|
3469
|
+
driverSession = withEventCapture(preparation.session, {
|
|
3470
|
+
appendEvents: (events) => {
|
|
3471
|
+
void storedHandle.append?.(events )?.catch?.((error ) => {
|
|
3472
|
+
warning('[stream-loop] 会话事件落盘失败(fail-open:内存事实不丢)', error);
|
|
3473
|
+
});
|
|
3474
|
+
},
|
|
3475
|
+
}, warning);
|
|
3476
|
+
}
|
|
3477
|
+
|
|
3478
|
+
const { driver } = deps.createDriver({
|
|
3479
|
+
sessionId: args.sessionId,
|
|
3480
|
+
agentOptions: args.agentOptions,
|
|
3481
|
+
session: driverSession,
|
|
3482
|
+
});
|
|
3483
|
+
debugTrace('driver.created');
|
|
3484
|
+
driver.setIdentity(args.sessionId, args.sessionId);
|
|
3485
|
+
// 修复限制 4 的另一半:resume 路径回放 tf-* 台账事实(final 答案 + ok 命令幂等面)。
|
|
3486
|
+
// 来源二选一:宿主路径扫 seed 里的 plugin:tf-agent/* 事件;本地台账路径读 ledger JSONL。
|
|
3487
|
+
if (args.prepareOpts.seed !== undefined || args.fallbackLedger?.file !== undefined) {
|
|
3488
|
+
const records = collectTfAgentRecords(args.prepareOpts.seed, args.fallbackLedger?.file, warning);
|
|
3489
|
+
if (records.length > 0) {
|
|
3490
|
+
const replay = driver.rehydrateRecords(records);
|
|
3491
|
+
debugTrace('ledger.rehydrated', replay);
|
|
3492
|
+
}
|
|
3493
|
+
}
|
|
3494
|
+
// 探针 C 定案:ledger 走 plugin:tf-agent/* 私有记录(appendPluginRecord 自动 ignorable:true)。
|
|
3495
|
+
// 宿主模块不可达(bundle 形态 bare import 解析不到同一副本)→ 降级本地文件台账(可重放,
|
|
3496
|
+
// 修复限制 4);连本地台账都不可用才降级内存,告警不静默。
|
|
3497
|
+
await attachSessionLedger(driver, driverSession, warning, deps.ctx, args.fallbackLedger);
|
|
3498
|
+
debugTrace('ledger.attached');
|
|
3499
|
+
|
|
3500
|
+
const agent = new StreamLoopAgent({
|
|
3501
|
+
id: args.sessionId,
|
|
3502
|
+
session: driverSession,
|
|
3503
|
+
driver,
|
|
3504
|
+
ctx: ownerCtx,
|
|
3505
|
+
scopeModule: dshScope,
|
|
3506
|
+
storedHandle: stored?.handle,
|
|
3507
|
+
modelSelection: {
|
|
3508
|
+
provider: args.agentOptions.provider ?? '',
|
|
3509
|
+
model: args.agentOptions.model ?? '',
|
|
3510
|
+
reasoningEffort: args.agentOptions.reasoningEffort,
|
|
3511
|
+
},
|
|
3512
|
+
// v0.3.2(UI 卡住修复):宿主事件总线在位(cordis ctx.emit)才接 agent/status。
|
|
3513
|
+
// 桌面端 dsh-api-session-controller 监听它转发 api-session/status(running 布尔),
|
|
3514
|
+
// 客户端据此收起"运行中"指示——不接线 = 回合结束后 UI 永远转圈。
|
|
3515
|
+
...(typeof (deps.ctx ).emit === 'function'
|
|
3516
|
+
? {
|
|
3517
|
+
emitStatus: (payload ) => {
|
|
3518
|
+
(deps.ctx ).emit('agent/status', payload);
|
|
3519
|
+
},
|
|
3520
|
+
}
|
|
3521
|
+
: {}),
|
|
3522
|
+
onWarning: warning,
|
|
3523
|
+
});
|
|
3524
|
+
debugTrace('agent.constructed');
|
|
3525
|
+
driver.setAgent(agent);
|
|
3526
|
+
|
|
3527
|
+
// 镜像内建 appendUnstoredSuffix(initializeAgent 进入公告前调用):prepare 的 seed
|
|
3528
|
+
// 会在会话内补 session/end-seed 占位事件(seq = seed 长度)。这批内存 suffix 必须
|
|
3529
|
+
// 立刻落盘对齐 handle cursor,否则宿主 checkpoint flush(ctx.sessions.flush)从
|
|
3530
|
+
// 占位事件之后起批 → "append seq mismatch"(桌面端 resume 后首个模型请求即死)。
|
|
3531
|
+
if (stored !== undefined) {
|
|
3532
|
+
const snap = preparation.session ;
|
|
3533
|
+
const suffix = typeof snap?.snapshotEvents === 'function' ? snap.snapshotEvents(stored.storedCount) : [];
|
|
3534
|
+
if (suffix.length > 0) {
|
|
3535
|
+
await stored.handle.append(suffix );
|
|
3536
|
+
debugTrace('resume.suffix.flushed', { count: suffix.length });
|
|
3537
|
+
}
|
|
3538
|
+
stored.storedCount += suffix.length;
|
|
3539
|
+
}
|
|
3540
|
+
|
|
3541
|
+
// 会话公告(镜像内建 :1571-1572)
|
|
3542
|
+
const detachSession = sessions.enter?.(preparation.session);
|
|
3543
|
+
sessions.announce?.(preparation.session);
|
|
3544
|
+
|
|
3545
|
+
// setup(桌面端在此做 Agent preset 绑定与 model selection;镜像内建 :1574-1576 传 agent.ctx)
|
|
3546
|
+
// 工具解析说明:不重绑执行器——宿主 ToolsService.execute(input) 内部按
|
|
3547
|
+
// selectExecutor(input.agent) → scopeChainOf(agent 实例 = 作用域 key) 选 preset 层
|
|
3548
|
+
// 执行器(dsh-tools rc.3),工具批自带 agent 字段即可命中 preset 层的 write/edit/pwsh;
|
|
3549
|
+
// 直读 agentCtx.tools 会触发 cordis "cannot get property without inject"(2026-11-15
|
|
3550
|
+
// 桌面端实测教训), entry 根服务与 agent 服务是同一实例,重绑无收益。
|
|
3551
|
+
const setupCommit = await args.setup?.(agent.ctx, agent);
|
|
3552
|
+
if (setupCommit !== undefined && setupCommit !== null && typeof (setupCommit ).commit === 'function') {
|
|
3553
|
+
(setupCommit ).commit();
|
|
3554
|
+
}
|
|
3555
|
+
|
|
3556
|
+
// agent 公告(镜像内建 :1578-1579;AgentRegistry.enter/announce 无 brand 校验,duck-type 可通行)
|
|
3557
|
+
const agents = deps.ctx.agents;
|
|
3558
|
+
const detachAgent = agents?.enter?.(agent, args.parentAgent);
|
|
3559
|
+
if (agents?.announce !== undefined) {
|
|
3560
|
+
await agents.announce(agent, args.source, args.signal);
|
|
3561
|
+
}
|
|
3562
|
+
debugTrace('agent.announced');
|
|
3563
|
+
|
|
3564
|
+
const dispose = async () => {
|
|
3565
|
+
try {
|
|
3566
|
+
await agent.dispose();
|
|
3567
|
+
} finally {
|
|
3568
|
+
try {
|
|
3569
|
+
detachAgent?.();
|
|
3570
|
+
} catch (error) {
|
|
3571
|
+
warning('[stream-loop] agents.detach 失败(不阻断 dispose)', error);
|
|
3572
|
+
}
|
|
3573
|
+
try {
|
|
3574
|
+
detachSession?.();
|
|
3575
|
+
} catch (error) {
|
|
3576
|
+
warning('[stream-loop] sessions.detach 失败(不阻断 dispose)', error);
|
|
3577
|
+
}
|
|
3578
|
+
}
|
|
3579
|
+
};
|
|
3580
|
+
return { agent, dispose };
|
|
3581
|
+
} catch (error) {
|
|
3582
|
+
// 回滚(镜像内建 finally:handle close + preparation dispose)
|
|
3583
|
+
try {
|
|
3584
|
+
await stored?.handle.close();
|
|
3585
|
+
} catch (closeError) {
|
|
3586
|
+
warning('[stream-loop] 持久化句柄回滚关闭失败', closeError);
|
|
3587
|
+
}
|
|
3588
|
+
try {
|
|
3589
|
+
preparation[Symbol.dispose]?.();
|
|
3590
|
+
} catch (disposeError) {
|
|
3591
|
+
warning('[stream-loop] session preparation 回滚失败', disposeError);
|
|
3592
|
+
}
|
|
3593
|
+
throw error;
|
|
3594
|
+
}
|
|
3595
|
+
}
|
|
3596
|
+
|
|
3597
|
+
return {
|
|
3598
|
+
async createAgent(ownerCtx, options) {
|
|
3599
|
+
assertSessionId(options.sessionId);
|
|
3600
|
+
// 修复限制 3:宿主 sessionPersistence 缺位 → 本地 JSONL 持久化(会话事件落盘,
|
|
3601
|
+
// resume 真正可用);两者都缺 → create 不落盘(v0.1 行为)。
|
|
3602
|
+
let persistence = deps.ctx.get?.('sessionPersistence') ;
|
|
3603
|
+
let persistenceIsFallback = false;
|
|
3604
|
+
if ((persistence === undefined || typeof (persistence ).create !== 'function') && deps.createFallbackPersistence !== undefined) {
|
|
3605
|
+
const fallback = deps.createFallbackPersistence(options.sessionId);
|
|
3606
|
+
if (fallback !== undefined && typeof fallback.create === 'function') {
|
|
3607
|
+
persistence = fallback;
|
|
3608
|
+
persistenceIsFallback = true;
|
|
3609
|
+
debugTrace('persistence.fallback.jsonl', { sessionId: options.sessionId });
|
|
3610
|
+
}
|
|
3611
|
+
}
|
|
3612
|
+
return initialize(ownerCtx, {
|
|
3613
|
+
sessionId: options.sessionId,
|
|
3614
|
+
prepareOpts: {
|
|
3615
|
+
...(options.meta === undefined ? {} : { meta: options.meta }),
|
|
3616
|
+
...(options.seed === undefined ? {} : { seed: options.seed }),
|
|
3617
|
+
...(options.inheritedEventCount === undefined ? {} : { inheritedEventCount: options.inheritedEventCount }),
|
|
3618
|
+
},
|
|
3619
|
+
persistence,
|
|
3620
|
+
persistenceIsFallback,
|
|
3621
|
+
fallbackLedger: deps.fallbackLedger?.(options.sessionId),
|
|
3622
|
+
agentOptions: options.agentOptions ?? {},
|
|
3623
|
+
setup: options.setup,
|
|
3624
|
+
source: 'startup',
|
|
3625
|
+
parentAgent: options.parentAgent,
|
|
3626
|
+
signal: options.signal,
|
|
3627
|
+
});
|
|
3628
|
+
},
|
|
3629
|
+
|
|
3630
|
+
async resume(ownerCtx, options) {
|
|
3631
|
+
assertSessionId(options.resumeSessionId);
|
|
3632
|
+
// 修复限制 3:宿主 sessionPersistence 缺位 → 本地 JSONL 持久化 resume(不再直接报错)。
|
|
3633
|
+
let persistence = deps.ctx.get?.('sessionPersistence') ;
|
|
3634
|
+
let persistenceIsFallback = false;
|
|
3635
|
+
if ((persistence === undefined || typeof persistence.open !== 'function') && deps.createFallbackPersistence !== undefined) {
|
|
3636
|
+
const fallback = deps.createFallbackPersistence(options.resumeSessionId);
|
|
3637
|
+
if (fallback !== undefined && typeof fallback.open === 'function') {
|
|
3638
|
+
persistence = fallback;
|
|
3639
|
+
persistenceIsFallback = true;
|
|
3640
|
+
debugTrace('resume.persistence.fallback.jsonl', { sessionId: options.resumeSessionId });
|
|
3641
|
+
}
|
|
3642
|
+
}
|
|
3643
|
+
if (persistence === undefined || typeof persistence.open !== 'function') {
|
|
3644
|
+
throw new Error('[stream-loop] cannot resume: session persistence is not configured(需要 dsh-session-persistence 后端,或启用本地 JSONL 持久化降级)');
|
|
3645
|
+
}
|
|
3646
|
+
const id = options.resumeSessionId;
|
|
3647
|
+
const handle = await persistence.open(id, 'write', options.signal === undefined ? {} : { signal: options.signal });
|
|
3648
|
+
try {
|
|
3649
|
+
const coldRead = await handle.read(0);
|
|
3650
|
+
const events = [...coldRead.events];
|
|
3651
|
+
return await initialize(ownerCtx, {
|
|
3652
|
+
sessionId: id,
|
|
3653
|
+
prepareOpts: {
|
|
3654
|
+
seed: events,
|
|
3655
|
+
meta: handle.header,
|
|
3656
|
+
...(handle.inheritedEventCount === undefined ? {} : { inheritedEventCount: handle.inheritedEventCount }),
|
|
3657
|
+
...(coldRead.eventState === undefined ? {} : { eventState: coldRead.eventState }),
|
|
3658
|
+
},
|
|
3659
|
+
stored: { handle, storedCount: events.length },
|
|
3660
|
+
persistenceIsFallback,
|
|
3661
|
+
fallbackLedger: deps.fallbackLedger?.(id),
|
|
3662
|
+
agentOptions: options.agentOptions ?? {},
|
|
3663
|
+
setup: options.setup,
|
|
3664
|
+
source: 'resume',
|
|
3665
|
+
parentAgent: options.parentAgent,
|
|
3666
|
+
signal: options.signal,
|
|
3667
|
+
});
|
|
3668
|
+
} catch (error) {
|
|
3669
|
+
await handle.close().catch(() => {});
|
|
3670
|
+
throw error;
|
|
3671
|
+
}
|
|
3672
|
+
},
|
|
3673
|
+
};
|
|
3674
|
+
}
|
|
3675
|
+
|
|
3676
|
+
/** 从 seed 事件与本地台账文件收集 plugin:tf-agent/* 记录(resume 重放入口)。 */
|
|
3677
|
+
function collectTfAgentRecords(
|
|
3678
|
+
seed ,
|
|
3679
|
+
ledgerFile ,
|
|
3680
|
+
warn ,
|
|
3681
|
+
) {
|
|
3682
|
+
const records = [];
|
|
3683
|
+
if (seed !== undefined) {
|
|
3684
|
+
for (const event of seed) {
|
|
3685
|
+
if (event === null || typeof event !== 'object') continue;
|
|
3686
|
+
const e = event ;
|
|
3687
|
+
if (typeof e.type === 'string' && e.type.startsWith('plugin:tf-agent/')) {
|
|
3688
|
+
records.push({ kind: e.type, data: e.data });
|
|
3689
|
+
}
|
|
3690
|
+
}
|
|
3691
|
+
}
|
|
3692
|
+
if (ledgerFile !== undefined) {
|
|
3693
|
+
const loaded = loadLedgerRecords(ledgerFile);
|
|
3694
|
+
if (loaded.skipped > 0) warn?.(`[stream-loop] 本地台账坏行跳过 ${loaded.skipped} 条(${ledgerFile})`);
|
|
3695
|
+
for (const rec of loaded.records) records.push({ kind: rec.type, data: rec.data });
|
|
3696
|
+
}
|
|
3697
|
+
return records;
|
|
3698
|
+
}
|
|
3699
|
+
|
|
3700
|
+
/**
|
|
3701
|
+
* 探针 C 通道(修复限制 4):优先经宿主 loader 取同源 @deepseek-ai/dsh-session 副本调用
|
|
3702
|
+
* appendPluginRecord(bundle 形态 bare import 不走宿主解析,必须走 loader 的 internal 通道——
|
|
3703
|
+
* 与 dsh-scope 同款三级降级);仍不可达且提供了本地台账 → 降级 JSONL 文件台账(可重放,
|
|
3704
|
+
* 非易失内存);两者都不可用才降级内存台账。每级降级都告警,绝不静默。
|
|
3705
|
+
*/
|
|
3706
|
+
export async function attachSessionLedger(
|
|
3707
|
+
driver ,
|
|
3708
|
+
session ,
|
|
3709
|
+
warn ,
|
|
3710
|
+
ctx ,
|
|
3711
|
+
fallback ,
|
|
3712
|
+
) {
|
|
3713
|
+
try {
|
|
3714
|
+
const mod = (await acquireHostModule(ctx, '@deepseek-ai/dsh-session'))
|
|
3715
|
+
|
|
3716
|
+
;
|
|
3717
|
+
if (mod === undefined || typeof mod.appendPluginRecord !== 'function') throw new Error('appendPluginRecord 导出缺失');
|
|
3718
|
+
driver.attachLedger({
|
|
3719
|
+
record(type, data) {
|
|
3720
|
+
mod.appendPluginRecord (session, type, data);
|
|
3721
|
+
},
|
|
3722
|
+
});
|
|
3723
|
+
} catch (error) {
|
|
3724
|
+
if (fallback !== undefined) {
|
|
3725
|
+
driver.attachLedger({
|
|
3726
|
+
record(type, data) {
|
|
3727
|
+
fallback.appendRecord(type, data);
|
|
3728
|
+
},
|
|
3729
|
+
});
|
|
3730
|
+
warn?.('[stream-loop] plugin:tf-agent ledger 的 plugin record 通道不可达,降级本地文件台账(JSONL 落盘,resume 可重放)', error);
|
|
3731
|
+
return;
|
|
3732
|
+
}
|
|
3733
|
+
// 类身份/解析失败且无本地台账 → 内存台账降级(driver 内存 records 永远有全量事实),告警不静默
|
|
3734
|
+
warn?.('[stream-loop] plugin:tf-agent ledger 落 plugin record 失败,降级内存台账(resume 后 tf-* 状态不可重放)', error);
|
|
3735
|
+
}
|
|
3736
|
+
}
|
|
3737
|
+
|
|
3738
|
+
// ---------------------------------------------------------------------------
|
|
3739
|
+
// ⑤ apply —— Cordis 函数插件入口(生产 preset 挂载;F1 路线接管)
|
|
3740
|
+
// ---------------------------------------------------------------------------
|
|
3741
|
+
|
|
3742
|
+
|
|
3743
|
+
|
|
3744
|
+
|
|
3745
|
+
|
|
3746
|
+
|
|
3747
|
+
|
|
3748
|
+
|
|
3749
|
+
|
|
3750
|
+
|
|
3751
|
+
|
|
3752
|
+
|
|
3753
|
+
|
|
3754
|
+
|
|
3755
|
+
|
|
3756
|
+
|
|
3757
|
+
|
|
3758
|
+
|
|
3759
|
+
|
|
3760
|
+
|
|
3761
|
+
|
|
3762
|
+
|
|
3763
|
+
|
|
3764
|
+
|
|
3765
|
+
|
|
3766
|
+
|
|
3767
|
+
|
|
3768
|
+
|
|
3769
|
+
|
|
3770
|
+
|
|
3771
|
+
|
|
3772
|
+
|
|
3773
|
+
|
|
3774
|
+
|
|
3775
|
+
|
|
3776
|
+
|
|
3777
|
+
|
|
3778
|
+
|
|
3779
|
+
|
|
3780
|
+
|
|
3781
|
+
|
|
3782
|
+
|
|
3783
|
+
|
|
3784
|
+
|
|
3785
|
+
|
|
3786
|
+
|
|
3787
|
+
|
|
3788
|
+
|
|
3789
|
+
|
|
3790
|
+
/**
|
|
3791
|
+
* Cordis 插件名与服务依赖声明(镜像 dsh-headless/lib/index.js:100-107 的函数插件约定:
|
|
3792
|
+
* loader 等这些服务就绪后才调 apply,避免加载期 ctx.llm/ctx.tools 尚未挂载的时序问题)。
|
|
3793
|
+
*/
|
|
3794
|
+
export const name = 'stream-agent';
|
|
3795
|
+
export const inject = ['llm', 'tools', 'agents', 'sessions'];
|
|
3796
|
+
|
|
3797
|
+
/**
|
|
3798
|
+
* 函数插件入口:
|
|
3799
|
+
* ctx.agents.setFactory(factory)(F1 全局槽位;内建 agent-loop 必须已被 profile patch 停用,
|
|
3800
|
+
* 否则 setFactory 抛 "an agent factory is already registered"——fail-fast,不静默)。
|
|
3801
|
+
* 驱动器端口在 createDriver 闭包里从 ctx 现取(ctx.llm.stream / ctx.tools.execute),
|
|
3802
|
+
* 会话事件写入器按 session 构造(探针 C 定案的 surface 事件形状)。
|
|
3803
|
+
*/
|
|
3804
|
+
export default function apply(ctx
|
|
3805
|
+
|
|
3806
|
+
|
|
3807
|
+
|
|
3808
|
+
|
|
3809
|
+
|
|
3810
|
+
, config = {}) {
|
|
3811
|
+
const logger = getService (ctx, 'logger');
|
|
3812
|
+
const warning = (message , detail ) => {
|
|
3813
|
+
// 红线 5:告警走宿主 logger(可用时),否则 console.error —— 都不静默
|
|
3814
|
+
const text = `[stream-loop] ${message}${detail === undefined ? '' : ` :: ${detailString(detail)}`}`;
|
|
3815
|
+
if (logger?.warn !== undefined) logger.warn(text);
|
|
3816
|
+
else console.error(text);
|
|
3817
|
+
};
|
|
3818
|
+
|
|
3819
|
+
// v0.2.1:全部服务读取走 getService —— Cordis 对未 inject 的属性裸读会抛
|
|
3820
|
+
// "cannot get property ... without inject",v0.2.0 因此整层接管未激活(见 cordis-compat.ts)。
|
|
3821
|
+
const llm = getService (ctx, 'llm');
|
|
3822
|
+
const tools = getService (ctx, 'tools');
|
|
3823
|
+
if (llm === undefined || typeof llm.stream !== 'function') {
|
|
3824
|
+
throw new Error('[stream-loop] ctx.llm.stream 不可用:entry 挂载失败(需要 dsh-llm 服务在位)');
|
|
3825
|
+
}
|
|
3826
|
+
if (tools === undefined || typeof tools.execute !== 'function') {
|
|
3827
|
+
throw new Error('[stream-loop] ctx.tools.execute 不可用:entry 挂载失败(需要 dsh-tools 服务在位)');
|
|
3828
|
+
}
|
|
3829
|
+
|
|
3830
|
+
// 默认模型三级回退:agentOptions(宿主 agentDefaultModel 惰性 getter)→ entry config →
|
|
3831
|
+
// 宿主 agentDefaultModel → 最后兜底。桌面端部署常只挂 deepseek-account 路由,
|
|
3832
|
+
// 硬编码 deepseek-official/deepseek-chat 会请求到无凭据的路由。
|
|
3833
|
+
const agentDefaultModel = getService (ctx, 'agentDefaultModel');
|
|
3834
|
+
const defaultSelection = agentDefaultModel?.currentSelection?.() ?? {};
|
|
3835
|
+
const stateRoot = resolveStateDir(config.stateDir);
|
|
3836
|
+
// 控制栏模式(v0.2.1):显式 config.mode > STREAM_AGENT_MODE > control.json > balanced。
|
|
3837
|
+
// 模式只提供默认值,下面每个字段都用 `config.X ?? preset.X` —— 显式装配永远压过模式。
|
|
3838
|
+
const control = resolveControlState({ mode: config.mode, lang: config.lang }, config.stateDir, warning);
|
|
3839
|
+
// 每次新建 agent 时重算:桌面控制页可以在不重启的情况下切模式,
|
|
3840
|
+
// 已有的 driver 保持创建时的参数(会话内不突变),新会话拿到新参数。
|
|
3841
|
+
const resolveEffective = (
|
|
3842
|
+
|
|
3843
|
+
|
|
3844
|
+
|
|
3845
|
+
|
|
3846
|
+
|
|
3847
|
+
|
|
3848
|
+
) => {
|
|
3849
|
+
const preset = modeConfig(control.mode);
|
|
3850
|
+
return {
|
|
3851
|
+
selfReadFeedback: config.selfReadFeedback ?? preset.selfReadFeedback,
|
|
3852
|
+
// 'auto' = 交给 codeExecutor 是否存在决定(保持 v0.2.0 的"宿主有 PTC 就开"语义)
|
|
3853
|
+
enableCode: config.enableCode ?? (preset.enableCode === 'auto' ? undefined : preset.enableCode),
|
|
3854
|
+
persistFallback: config.persistFallback ?? preset.persistFallback,
|
|
3855
|
+
maxParallelToolCalls: config.maxParallelToolCalls ?? preset.maxParallelToolCalls,
|
|
3856
|
+
maxReentries: config.maxReentries ?? preset.maxReentries,
|
|
3857
|
+
budgetTokens: config.budgetTokens ?? preset.budgetTokens,
|
|
3858
|
+
};
|
|
3859
|
+
};
|
|
3860
|
+
const effective = resolveEffective();
|
|
3861
|
+
// 修复限制 3/4:本地持久化兜底(默认开启;模式或 config.persistFallback === false 关闭)
|
|
3862
|
+
const persistFallbackEnabled = effective.persistFallback !== false;
|
|
3863
|
+
// 0.2.0 PTC 桥接:ctx.ptcRuntime 在位(形状校验通过)→ tf-code 通道可用;
|
|
3864
|
+
// 形状不符或缺失 → 通道关闭(协议文本不声明 tf-code),告警不静默(红线 5)。
|
|
3865
|
+
// v0.2.1:ptcRuntime 是可选服务,只经 getService 探测(裸读即装载期抛错)。
|
|
3866
|
+
const ptcRuntime = getService (ctx, 'ptcRuntime');
|
|
3867
|
+
const codeExecutor = looksLikePtcRuntime(ptcRuntime)
|
|
3868
|
+
? createCodeExecutor(ptcRuntime, { executeTools: (input) => tools.execute(input ) })
|
|
3869
|
+
: undefined;
|
|
3870
|
+
if (ptcRuntime !== undefined && codeExecutor === undefined) {
|
|
3871
|
+
warning('ctx.ptcRuntime 形状不符(缺 resolve/run),tf-code 通道关闭(fail-open,其余行为不变)', ptcRuntime);
|
|
3872
|
+
}
|
|
3873
|
+
const factory = createStreamAgentFactory({
|
|
3874
|
+
ctx: ctx ,
|
|
3875
|
+
createFallbackPersistence: persistFallbackEnabled
|
|
3876
|
+
? (sessionId) => createJsonlPersistence(join(stateRoot, 'sessions'), sessionId, warning)
|
|
3877
|
+
: undefined,
|
|
3878
|
+
fallbackLedger: persistFallbackEnabled
|
|
3879
|
+
? (sessionId) => {
|
|
3880
|
+
const file = ledgerFileOf(stateRoot, sessionId);
|
|
3881
|
+
return { file, appendRecord: (type , data ) => appendLedgerRecord(file, type, data) };
|
|
3882
|
+
}
|
|
3883
|
+
: undefined,
|
|
3884
|
+
createDriver({ agentOptions, session, sessionId }) {
|
|
3885
|
+
const live = resolveEffective();
|
|
3886
|
+
const cfg = {
|
|
3887
|
+
provider: agentOptions.provider || config.provider || defaultSelection.provider || '',
|
|
3888
|
+
model: agentOptions.model || config.model || defaultSelection.model || '',
|
|
3889
|
+
reasoningEffort: agentOptions.reasoningEffort ?? config.reasoningEffort ?? defaultSelection.reasoningEffort,
|
|
3890
|
+
maxParallelToolCalls: live.maxParallelToolCalls,
|
|
3891
|
+
maxReentries: live.maxReentries,
|
|
3892
|
+
streamIdleTimeoutMs: config.streamIdleTimeoutMs,
|
|
3893
|
+
budgetTokens: live.budgetTokens,
|
|
3894
|
+
selfReadFeedback: live.selfReadFeedback,
|
|
3895
|
+
enableCode: live.enableCode,
|
|
3896
|
+
codeTimeoutMs: config.codeTimeoutMs,
|
|
3897
|
+
codeQuota: config.codeQuota,
|
|
3898
|
+
codeValueInjectLimit: config.codeValueInjectLimit,
|
|
3899
|
+
nativeResultLimit: config.nativeResultLimit,
|
|
3900
|
+
enablePlan: config.enablePlan,
|
|
3901
|
+
segmentMaxChars: config.segmentMaxChars,
|
|
3902
|
+
nativeToolSchemas: config.nativeToolSchemas,
|
|
3903
|
+
systemPrompt: config.systemPrompt,
|
|
3904
|
+
protocolText: config.protocolText,
|
|
3905
|
+
invariants: config.invariants,
|
|
3906
|
+
};
|
|
3907
|
+
// F6 恢复意图:意图日志端口(fsync 落盘;enableIntents: false 关闭——回退点)。
|
|
3908
|
+
// 写前意图在派发前落盘、写后回执落定即记;崩溃后"有意图无回执"= 写入可能已发生。
|
|
3909
|
+
const intentsEnabled = config.enableIntents !== false;
|
|
3910
|
+
const intentBook = new Map ();
|
|
3911
|
+
const intentFile = sessionId !== undefined && sessionId !== '' ? intentFileOf(stateRoot, sessionId) : undefined;
|
|
3912
|
+
const loadIntentState = () => {
|
|
3913
|
+
if (intentFile === undefined) return { seq: 0 };
|
|
3914
|
+
try {
|
|
3915
|
+
return { seq: loadIntentRecords(intentFile).records.length };
|
|
3916
|
+
} catch {
|
|
3917
|
+
return { seq: 0 };
|
|
3918
|
+
}
|
|
3919
|
+
};
|
|
3920
|
+
const intentSeqState = intentsEnabled ? loadIntentState() : { seq: 0 };
|
|
3921
|
+
// v0.3.2(会话日志 model source 修复):writer 在 driver 之前构造,provider/model
|
|
3922
|
+
// 却要到**写入时**才取实时值(applySelection 换模后随动)——用可变持有者回填。
|
|
3923
|
+
// 写入只发生在回合协程内(构造早已完成),时序安全。
|
|
3924
|
+
let driverRef ;
|
|
3925
|
+
const driver = new SingleStreamDriver(
|
|
3926
|
+
{
|
|
3927
|
+
stream: (options) => llm.stream(options),
|
|
3928
|
+
executeTools: (input) => tools.execute(input),
|
|
3929
|
+
...(codeExecutor === undefined ? {} : { executeCode: codeExecutor }),
|
|
3930
|
+
// v0.3.1 思考过程实时帧:宿主事件总线在位(cordis ctx.emit)才接线;
|
|
3931
|
+
// 发射契约由驱动器保证(revision/index 递增、异常熔断),宿主无监听器时是 no-op。
|
|
3932
|
+
...(typeof (ctx ).emit === 'function'
|
|
3933
|
+
? {
|
|
3934
|
+
emitHostEvent: (event , payload ) => {
|
|
3935
|
+
(ctx ).emit(event, payload);
|
|
3936
|
+
},
|
|
3937
|
+
}
|
|
3938
|
+
: {}),
|
|
3939
|
+
...(intentsEnabled && intentFile !== undefined
|
|
3940
|
+
? {
|
|
3941
|
+
onIntent: (event ) => {
|
|
3942
|
+
intentSeqState.seq += 1;
|
|
3943
|
+
intentBook.set(event.cmdId, intentSeqState.seq);
|
|
3944
|
+
appendIntentRecord(intentFile , { type: 'intent', seq: intentSeqState.seq, at: new Date().toISOString(), sessionId: sessionId ?? '', ...event });
|
|
3945
|
+
},
|
|
3946
|
+
onIntentReceipt: (event ) => {
|
|
3947
|
+
const intentSeq = intentBook.get(event.cmdId) ?? -1;
|
|
3948
|
+
intentSeqState.seq += 1;
|
|
3949
|
+
appendIntentRecord(intentFile , { type: 'receipt', seq: intentSeqState.seq, at: new Date().toISOString(), intentSeq, ok: event.ok, ...(event.detail === undefined ? {} : { detail: event.detail }) });
|
|
3950
|
+
},
|
|
3951
|
+
}
|
|
3952
|
+
: {}),
|
|
3953
|
+
events: createSessionEventWriter(session, () => driverRef?.modelSource()),
|
|
3954
|
+
onWarning: warning,
|
|
3955
|
+
},
|
|
3956
|
+
cfg,
|
|
3957
|
+
);
|
|
3958
|
+
driverRef = driver;
|
|
3959
|
+
// K2:会话工作区解析(tf-code resolve 透传用)。会话 header.cwd(会话原始目录)
|
|
3960
|
+
// 优先,缺省回退宿主 workingDirectory 服务的部署默认目录;两者都不可得则不传,
|
|
3961
|
+
// 由宿主按自己的默认语义解析。插件不复制宿主的优先级规则。
|
|
3962
|
+
const headerCwd = (session )?.header?.cwd;
|
|
3963
|
+
const workingDirectory = getService (ctx, 'workingDirectory');
|
|
3964
|
+
const resolvedCwd = typeof headerCwd === 'string' && headerCwd !== ''
|
|
3965
|
+
? headerCwd
|
|
3966
|
+
: (workingDirectory?.defaultDirectory !== undefined ? workingDirectory.defaultDirectory : undefined);
|
|
3967
|
+
driver.setSessionCwd(resolvedCwd);
|
|
3968
|
+
// F6 resume 停机核对:创建/恢复会话时检查"有意图无回执";存在即置位停机
|
|
3969
|
+
// (不发请求、零注入、不自动重放)。resumeIntentPolicy: 'ignore' 可跳过(回退点)。
|
|
3970
|
+
if (intentsEnabled && intentFile !== undefined && config.resumeIntentPolicy !== 'ignore') {
|
|
3971
|
+
try {
|
|
3972
|
+
const { records, badLines } = loadIntentRecords(intentFile);
|
|
3973
|
+
const pending = pendingIntents(records).filter((p) => p.state === 'pending');
|
|
3974
|
+
if (pending.length > 0) {
|
|
3975
|
+
const listing = pending.slice(0, 8).map((p) => `${p.intent.op} ${p.intent.path} (cmd=${p.intent.cmdId} fp=${p.intent.fingerprint})`).join('; ');
|
|
3976
|
+
driver.setResumeHalt(`${pending.length} 条写前意图无回执(${listing}${pending.length > 8 ? ' …' : ''})${badLines > 0 ? `;另有 ${badLines} 行坏记录` : ''}`);
|
|
3977
|
+
warning(`[stream-loop] F6 resume 停机核对:会话 ${sessionId} 有 ${pending.length} 条写前意图无回执(写入可能已发生)——不自动重放,请人工核对(CLI: dsh-stream-agent intents)`);
|
|
3978
|
+
}
|
|
3979
|
+
} catch (error) {
|
|
3980
|
+
warning('F6 意图日志读取失败(fail-open:不做停机核对,继续会话)', error);
|
|
3981
|
+
}
|
|
3982
|
+
}
|
|
3983
|
+
return { driver };
|
|
3984
|
+
},
|
|
3985
|
+
onWarning: warning,
|
|
3986
|
+
});
|
|
3987
|
+
|
|
3988
|
+
const agents = getService (ctx, 'agents');
|
|
3989
|
+
if (agents === undefined || typeof agents.setFactory !== 'function') {
|
|
3990
|
+
throw new Error('[stream-loop] ctx.agents.setFactory 不可用:无法接管 agent 创建(需要 dsh-agent 服务在位)');
|
|
3991
|
+
}
|
|
3992
|
+
// S3 双 loop 具名诊断(0.3.0-beta.1):setFactory 是全局唯一槽位,内建 agent-loop 未被
|
|
3993
|
+
// 停用时宿主抛裸错 "an agent factory is already registered"。转换为 E_DOUBLE_LOOP:
|
|
3994
|
+
// 带 profile 标识、冲突来源与处置建议——冲突必须具名失败,不 catch 后继续、不重试、
|
|
3995
|
+
// 不靠装载顺序"碰巧"获胜(C2 单 loop 权威)。
|
|
3996
|
+
const profileName = resolveProfileName(ctx);
|
|
3997
|
+
let detachFactory ;
|
|
3998
|
+
try {
|
|
3999
|
+
detachFactory = agents.setFactory(factory);
|
|
4000
|
+
} catch (error) {
|
|
4001
|
+
throw doubleLoopError(error, profileName);
|
|
4002
|
+
}
|
|
4003
|
+
// 接管事实登记:控制栏据此写"接管生效"或"未接管"
|
|
4004
|
+
markTakeover(control.mode);
|
|
4005
|
+
|
|
4006
|
+
// v0.2.1 桌面控制页的宿主面:只暴露"读状态 / 切模式 / 切语言"三件事。
|
|
4007
|
+
// UI 是独立子包(ui/),经同源 HTTP 路由调用本服务;服务不存在时 UI 降级为只读诊断。
|
|
4008
|
+
const controlStatus = () => {
|
|
4009
|
+
const live = resolveEffective();
|
|
4010
|
+
const persisted = readPersistedControl(config.stateDir);
|
|
4011
|
+
return {
|
|
4012
|
+
version: VERSION,
|
|
4013
|
+
takeover: true,
|
|
4014
|
+
mode: control.mode,
|
|
4015
|
+
modeSource: control.modeSource,
|
|
4016
|
+
modeLocked: control.modeSource === 'config' || control.modeSource === 'env',
|
|
4017
|
+
lang: control.lang,
|
|
4018
|
+
langSource: control.langSource,
|
|
4019
|
+
langLocked: control.langSource === 'config' || control.langSource === 'env',
|
|
4020
|
+
effective: {
|
|
4021
|
+
selfReadFeedback: live.selfReadFeedback,
|
|
4022
|
+
enableCode: live.enableCode === undefined ? false : live.enableCode,
|
|
4023
|
+
persistFallback: live.persistFallback,
|
|
4024
|
+
maxParallelToolCalls: live.maxParallelToolCalls,
|
|
4025
|
+
maxReentries: live.maxReentries,
|
|
4026
|
+
budgetTokens: live.budgetTokens ?? null,
|
|
4027
|
+
},
|
|
4028
|
+
modes: publicModeCatalog(),
|
|
4029
|
+
updatedAt: persisted.updatedAt ?? null,
|
|
4030
|
+
stateFile: control.file,
|
|
4031
|
+
};
|
|
4032
|
+
};
|
|
4033
|
+
const applyMode = (next ) => {
|
|
4034
|
+
if (!isModeId(next)) return { ok: false, code: 'invalid-mode' };
|
|
4035
|
+
if (control.modeSource === 'config' || control.modeSource === 'env') return { ok: false, code: 'locked' };
|
|
4036
|
+
control.mode = next;
|
|
4037
|
+
markTakeover(next);
|
|
4038
|
+
try {
|
|
4039
|
+
writePersistedControl({ mode: control.mode, lang: control.lang }, config.stateDir);
|
|
4040
|
+
control.modeSource = 'file';
|
|
4041
|
+
return { ok: true, persisted: true };
|
|
4042
|
+
} catch (error) {
|
|
4043
|
+
control.modeSource = 'runtime';
|
|
4044
|
+
warning(`控制栏模式已在本进程生效,但落盘失败(重启后会回到旧值):${control.file}`, error);
|
|
4045
|
+
return { ok: true, persisted: false };
|
|
4046
|
+
}
|
|
4047
|
+
};
|
|
4048
|
+
const applyLang = (next ) => {
|
|
4049
|
+
if (!isLang(next)) return { ok: false, code: 'invalid-lang' };
|
|
4050
|
+
if (control.langSource === 'config' || control.langSource === 'env') return { ok: false, code: 'locked' };
|
|
4051
|
+
control.lang = next;
|
|
4052
|
+
try {
|
|
4053
|
+
writePersistedControl({ mode: control.mode, lang: control.lang }, config.stateDir);
|
|
4054
|
+
control.langSource = 'file';
|
|
4055
|
+
return { ok: true, persisted: true };
|
|
4056
|
+
} catch (error) {
|
|
4057
|
+
control.langSource = 'runtime';
|
|
4058
|
+
warning(`控制栏语言已在本进程生效,但落盘失败(重启后会回到旧值):${control.file}`, error);
|
|
4059
|
+
return { ok: true, persisted: false };
|
|
4060
|
+
}
|
|
4061
|
+
};
|
|
4062
|
+
// 老式测试桩可能没有 provide(只挂服务不建容器);真实 Cordis 一定有。
|
|
4063
|
+
// 注册失败也不能影响 loop 本体:桌面控制页只是可选面,降级为只读即可。
|
|
4064
|
+
if (typeof ctx.provide === 'function') {
|
|
4065
|
+
try {
|
|
4066
|
+
ctx.provide('streamAgentRuntime', {
|
|
4067
|
+
status: controlStatus,
|
|
4068
|
+
setMode: applyMode,
|
|
4069
|
+
setLang: applyLang,
|
|
4070
|
+
});
|
|
4071
|
+
} catch (error) {
|
|
4072
|
+
warning('streamAgentRuntime 服务注册失败:桌面控制页降级为只读(loop 本体不受影响)', error);
|
|
4073
|
+
}
|
|
4074
|
+
}
|
|
4075
|
+
|
|
4076
|
+
if (config.announceTakeover === true) {
|
|
4077
|
+
const codeState = codeExecutor === undefined
|
|
4078
|
+
? 'code=off'
|
|
4079
|
+
: (resolveEffective().enableCode === true ? 'code=on(opt-in)' : 'code=off(default,K1)');
|
|
4080
|
+
console.error(`[stream-loop] TAKEOVER-ACTIVE: agent factory registered via setFactory (built-in agent-loop must be disabled by profile patch) · mode=${control.mode} (${control.modeSource}) · ${codeState} · profile=${profileName}`);
|
|
4081
|
+
}
|
|
4082
|
+
|
|
4083
|
+
// 会话投影注册(桌面端硬依赖,内建 agent-loop 在 Service.init 注册——dsh-agent-loop rc.3:50110):
|
|
4084
|
+
// 客户端模型选择器的 projected 数据面 = 服务端 modelSelection 投影;缺失时
|
|
4085
|
+
// dsh-client-ui-model-selection 的 syncInputs 永远停在 status:"loading"("正在加载模型…"),
|
|
4086
|
+
// 会话列表/写作工具等也读该投影族。经宿主 loader 取同源 @deepseek-ai/dsh-agent 的导出注册。
|
|
4087
|
+
// fail-open(红线 5):服务/模块/定义任一不可达 → 告警不静默,headless 行为不变。
|
|
4088
|
+
const sessionProjections = getService (ctx, 'sessionProjections');
|
|
4089
|
+
if (sessionProjections === undefined || typeof sessionProjections.register !== 'function') {
|
|
4090
|
+
warning('ctx.sessionProjections.register 不可达:跳过 modelSelection 投影注册(headless 不受影响;桌面端客户端模型选择器会停在加载态)');
|
|
4091
|
+
} else {
|
|
4092
|
+
acquireHostModule(ctx, '@deepseek-ai/dsh-agent')
|
|
4093
|
+
.then((mod) => {
|
|
4094
|
+
const definition = (mod )?.modelSelectionProjectionDefinition;
|
|
4095
|
+
if (definition === undefined) {
|
|
4096
|
+
warning('@deepseek-ai/dsh-agent.modelSelectionProjectionDefinition 不可达:跳过注册(同上,客户端模型选择器会停在加载态)');
|
|
4097
|
+
return;
|
|
4098
|
+
}
|
|
4099
|
+
return Promise.resolve(sessionProjections.register(definition)).then(() => {
|
|
4100
|
+
debugTrace('projection.modelSelection.registered');
|
|
4101
|
+
});
|
|
4102
|
+
})
|
|
4103
|
+
.catch((error) => {
|
|
4104
|
+
warning('modelSelection 投影注册失败(fail-open 继续)', error);
|
|
4105
|
+
});
|
|
4106
|
+
}
|
|
4107
|
+
|
|
4108
|
+
const dispose = () => {
|
|
4109
|
+
try {
|
|
4110
|
+
detachFactory?.();
|
|
4111
|
+
clearTakeover();
|
|
4112
|
+
} catch (error) {
|
|
4113
|
+
warning('[stream-loop] factory 卸载失败', error);
|
|
4114
|
+
}
|
|
4115
|
+
};
|
|
4116
|
+
ctx.effect?.(() => dispose, 'streamAgent.setFactory()');
|
|
4117
|
+
// Cordis 函数式插件契约:返回值必须可调用(cordis-compat.ts 缺陷 2)
|
|
4118
|
+
return asPluginEffect({ factory, dispose });
|
|
4119
|
+
}
|
|
4120
|
+
|
|
4121
|
+
function detailString(detail ) {
|
|
4122
|
+
if (detail instanceof Error) return detail.message;
|
|
4123
|
+
if (typeof detail === 'string') return detail;
|
|
4124
|
+
try {
|
|
4125
|
+
return JSON.stringify(detail);
|
|
4126
|
+
} catch {
|
|
4127
|
+
return String(detail);
|
|
4128
|
+
}
|
|
4129
|
+
}
|
|
4130
|
+
|
|
4131
|
+
/** S3:解析当前 profile 名(宿主 profileContext.dir 的 basename;测试桩/缺失时回退 env 与 unknown)。 */
|
|
4132
|
+
function resolveProfileName(ctx ) {
|
|
4133
|
+
const dir = (ctx ).get?.('profileContext') ;
|
|
4134
|
+
const raw = typeof (dir )?.dir === 'string' ? (dir ).dir : undefined;
|
|
4135
|
+
if (raw !== undefined && raw !== '') {
|
|
4136
|
+
const parts = raw.replace(/\\/g, '/').split('/').filter((p) => p !== '');
|
|
4137
|
+
const last = parts[parts.length - 1];
|
|
4138
|
+
if (last !== undefined && last !== '') return last;
|
|
4139
|
+
}
|
|
4140
|
+
const env = typeof process !== 'undefined' ? process.env['DSH_PROFILE'] : undefined;
|
|
4141
|
+
return env !== undefined && env !== '' ? env : 'unknown';
|
|
4142
|
+
}
|
|
4143
|
+
|
|
4144
|
+
/** S3:把宿主的 setFactory 冲突裸错转换为 E_DOUBLE_LOOP 具名失败(fail-fast,不重试不静默)。 */
|
|
4145
|
+
function doubleLoopError(original , profile ) {
|
|
4146
|
+
const detail = original instanceof Error ? original.message : String(original);
|
|
4147
|
+
const error = new Error(
|
|
4148
|
+
`[E_DOUBLE_LOOP] 双 loop 冲突,接管失败:profile=${profile} 已注册了另一个 agent factory`
|
|
4149
|
+
+ `(来源通常为内建 @deepseek-ai/dsh-agent-loop 或另一个 stream 实例);entry=stream-agent。`
|
|
4150
|
+
+ ` 原始错误:${detail}`
|
|
4151
|
+
+ ` 处置建议:不要把本插件装进已有内建 loop 的 profile(web/desktop 等);`
|
|
4152
|
+
+ `在专用 profile(如 profiles/stream 模板)中安装,或确认该 profile 的 bundle/patch 已停用`
|
|
4153
|
+
+ ` @deepseek-ai/dsh-agent-loop("- id: agent-loop" + "disabled: true")。`,
|
|
4154
|
+
);
|
|
4155
|
+
error.name = 'E_DOUBLE_LOOP';
|
|
4156
|
+
return error;
|
|
4157
|
+
}
|
|
4158
|
+
|
|
4159
|
+
/** 诊断追踪(STREAM_LOOP_DEBUG=1 时向 stderr 打里程碑;生产默认关闭,不产生噪音)。 */
|
|
4160
|
+
export function debugTrace(milestone , detail ) {
|
|
4161
|
+
if (process.env.STREAM_LOOP_DEBUG !== '1') return;
|
|
4162
|
+
console.error(`[stream-loop:debug] ${milestone}${detail === undefined ? '' : ` :: ${detailString(detail)}`}`);
|
|
4163
|
+
}
|