@hugesb/dsh-stream-agent 0.0.0-stage → 0.3.1

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.
Files changed (158) hide show
  1. package/CHANGELOG.md +497 -0
  2. package/CONTRIBUTING.md +72 -0
  3. package/LICENSE +202 -0
  4. package/README.en.md +349 -0
  5. package/README.md +300 -3
  6. package/cordis.patch.yml +77 -0
  7. package/dist/entry/action-gate.js +206 -0
  8. package/dist/entry/adapter-kit.js +192 -0
  9. package/dist/entry/context-render.js +119 -0
  10. package/dist/entry/control-bar-cli.js +289 -0
  11. package/dist/entry/control-bar.js +123 -0
  12. package/dist/entry/control-session.js +115 -0
  13. package/dist/entry/control-state.js +125 -0
  14. package/dist/entry/cordis-compat.js +95 -0
  15. package/dist/entry/eval-probe.js +112 -0
  16. package/dist/entry/intent-log.js +121 -0
  17. package/dist/entry/json-persistence.js +306 -0
  18. package/dist/entry/loop.js +3852 -0
  19. package/dist/entry/mock-provider.js +536 -0
  20. package/dist/entry/obs-broker.js +178 -0
  21. package/dist/entry/ptc-bridge.js +405 -0
  22. package/dist/entry/state-handle.js +217 -0
  23. package/dist/entry/takeover-registry.js +60 -0
  24. package/dist/kernel/control-bar.js +559 -0
  25. package/dist/kernel/final.js +62 -0
  26. package/dist/kernel/gate.js +464 -0
  27. package/dist/kernel/modes.js +253 -0
  28. package/dist/kernel/obs.js +517 -0
  29. package/dist/kernel/parser.js +632 -0
  30. package/dist/kernel/render.js +444 -0
  31. package/dist/kernel/state.js +416 -0
  32. package/dist/version.js +9 -0
  33. package/docs/TEST-PROPOSITIONS.md +139 -0
  34. package/docs/adr-001-segment-boundary.md +61 -0
  35. package/docs/architecture.md +104 -0
  36. package/docs/desktop-ui-feasibility.md +277 -0
  37. package/docs/disabled-lines-audit.md +53 -0
  38. package/docs/limitations.md +181 -0
  39. package/docs/protocol.md +99 -0
  40. package/docs/v0.4.0-plan.md +50 -0
  41. package/eval/METRICS.md +128 -0
  42. package/eval/RESULTS.md +246 -0
  43. package/eval/tasks/fixtures/big-report.md +298 -0
  44. package/eval/tasks/fixtures/build-manifest.txt +5 -0
  45. package/eval/tasks/fixtures/deploy.yaml +4 -0
  46. package/eval/tasks/fixtures/error.log +200 -0
  47. package/eval/tasks/fixtures/features.yaml +4 -0
  48. package/eval/tasks/fixtures/pipeline.yaml +4 -0
  49. package/eval/tasks/fixtures/sales-q1.csv +61 -0
  50. package/eval/tasks/fixtures/settings.yaml +4 -0
  51. package/eval/tasks/fixtures/users-roster.json +304 -0
  52. package/eval/tasks/fixtures/users-scores.json +20 -0
  53. package/eval/tasks/gen-fixtures.cjs +80 -0
  54. package/eval/tasks/tasks.json +150 -0
  55. package/eval/tools/f6-kill-drill.cjs +176 -0
  56. package/eval/tools/f6-kill-drill.worker.cjs +131 -0
  57. package/eval/tools/gen-results.cjs +191 -0
  58. package/eval/tools/machine-test.cjs +200 -0
  59. package/eval/tools/manual-code-scenarios.md +59 -0
  60. package/eval/tools/replay-check.cjs +311 -0
  61. package/eval/tools/runner.cjs +219 -0
  62. package/eval/tools/session-log.cjs +106 -0
  63. package/eval/tools/summarize.cjs +185 -0
  64. package/eval/tools/t3-cells.cjs +173 -0
  65. package/package.json +73 -6
  66. package/patches/adapters-smoke.yml +41 -0
  67. package/patches/eval-account.yml +36 -0
  68. package/patches/eval-baseline.yml +33 -0
  69. package/patches/eval-stream-code-off.yml +46 -0
  70. package/patches/eval-stream-code-on.yml +47 -0
  71. package/patches/eval-stream.yml +54 -0
  72. package/patches/takeover.yml +42 -0
  73. package/patches/test-preset.yml +23 -0
  74. package/preset/stream/cordis.patch.yml +39 -0
  75. package/preset/stream/package.json +13 -0
  76. package/preset.yml +56 -0
  77. package/profiles/stream/README.md +66 -0
  78. package/profiles/stream/cordis.patch.yml +12 -0
  79. package/profiles/stream/package.json +17 -0
  80. package/profiles/stream-headless/package.json +16 -0
  81. package/scripts/build.mjs +103 -0
  82. package/scripts/check-consistency.mjs +146 -0
  83. package/scripts/gate.mjs +138 -0
  84. package/scripts/install-check.mjs +116 -0
  85. package/scripts/install-cycle.mjs +88 -0
  86. package/scripts/release.mjs +415 -0
  87. package/scripts/repair-session-logs.mjs +403 -0
  88. package/src/entry/action-gate.ts +206 -0
  89. package/src/entry/adapter-kit.ts +192 -0
  90. package/src/entry/context-render.ts +119 -0
  91. package/src/entry/control-bar-cli.ts +289 -0
  92. package/src/entry/control-bar.ts +123 -0
  93. package/src/entry/control-session.ts +115 -0
  94. package/src/entry/control-state.ts +125 -0
  95. package/src/entry/cordis-compat.ts +95 -0
  96. package/src/entry/eval-probe.ts +112 -0
  97. package/src/entry/intent-log.ts +121 -0
  98. package/src/entry/json-persistence.ts +306 -0
  99. package/src/entry/loop.ts +3852 -0
  100. package/src/entry/mock-provider.ts +536 -0
  101. package/src/entry/obs-broker.ts +178 -0
  102. package/src/entry/ptc-bridge.ts +405 -0
  103. package/src/entry/state-handle.ts +217 -0
  104. package/src/entry/takeover-registry.ts +60 -0
  105. package/src/kernel/control-bar.ts +559 -0
  106. package/src/kernel/final.ts +62 -0
  107. package/src/kernel/gate.ts +464 -0
  108. package/src/kernel/modes.ts +253 -0
  109. package/src/kernel/obs.ts +517 -0
  110. package/src/kernel/parser.ts +632 -0
  111. package/src/kernel/render.ts +444 -0
  112. package/src/kernel/state.ts +416 -0
  113. package/src/version.ts +9 -0
  114. package/test/activation.test.ts +187 -0
  115. package/test/adapters.test.ts +676 -0
  116. package/test/control-bar.test.ts +486 -0
  117. package/test/desktop-ui.test.ts +359 -0
  118. package/test/eval-probe.test.ts +139 -0
  119. package/test/f5-plan.test.ts +221 -0
  120. package/test/f6-intent.test.ts +168 -0
  121. package/test/f7-segment.test.ts +190 -0
  122. package/test/fix-limits.test.ts +599 -0
  123. package/test/gate.test.ts +380 -0
  124. package/test/helpers/stub-loop.ts +240 -0
  125. package/test/kernel/obs.test.ts +329 -0
  126. package/test/kernel/parser.test.ts +450 -0
  127. package/test/loop.test.ts +1393 -0
  128. package/test/mock-provider.test.ts +386 -0
  129. package/test/ptc-bridge.test.ts +356 -0
  130. package/test/render.test.ts +418 -0
  131. package/test/s2-install-check.test.ts +46 -0
  132. package/test/scenarios/3-file-basic.json +13 -0
  133. package/test/scenarios/5-file-basic.json +22 -0
  134. package/test/scenarios/burn-more.json +9 -0
  135. package/test/scenarios/degraded-final.json +10 -0
  136. package/test/scenarios/fault-abort-xml.json +11 -0
  137. package/test/scenarios/fault-malformed-command.json +12 -0
  138. package/test/scenarios/fault-midstream-abort.json +11 -0
  139. package/test/scenarios/fault-saturating-output.json +9 -0
  140. package/test/scenarios/fault-timeout.json +9 -0
  141. package/test/scenarios/peek-first.json +11 -0
  142. package/test/scenarios/peek-second.json +11 -0
  143. package/test/scenarios/peek-third.json +10 -0
  144. package/test/scenarios/recover-final.json +10 -0
  145. package/test/scenarios/reroute-first.json +17 -0
  146. package/test/scenarios/reroute-second.json +16 -0
  147. package/test/scenarios/starvation-final.json +10 -0
  148. package/test/scenarios/starvation-promote.json +11 -0
  149. package/test/scenarios/wait-tools-continue.json +10 -0
  150. package/test/scenarios/wait-tools-xml.json +22 -0
  151. package/test/scenarios/wait-tools.json +15 -0
  152. package/test/session-format.test.ts +234 -0
  153. package/test/state.test.ts +335 -0
  154. package/test/stream-v02.test.ts +264 -0
  155. package/test/v031-display.test.ts +333 -0
  156. package/ui/client.js +576 -0
  157. package/ui/index.js +282 -0
  158. package/ui/package.json +26 -0
@@ -0,0 +1,356 @@
1
+ // test/ptc-bridge.test.ts —— tf-code 程序化通道(PTC 桥接,0.2.0)
2
+ //
3
+ // 覆盖:
4
+ // - parser:tf-code 命令(body = 程序体、timeout/description 属性)解析
5
+ // - obs:tf-code → code 族(高增益:首个/变化结果注骨架;失败一律 high)
6
+ // - ptc-bridge 适配器:resolve/run duck-type 装配、bindings 透传 executeTools、
7
+ // 错误 kind 映射、logs 展平、run() reject → 结构化失败
8
+ // - 驱动器 E2E:tf-code 成功 → 句柄化 + 骨架注入;失败 → 结构化错误改道;
9
+ // 无 executeCode 端口 → no-code-channel 命令级失败;协议文本按通道可用性声明
10
+
11
+ import { describe, it, beforeEach } from 'node:test';
12
+ import assert from 'node:assert/strict';
13
+ import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
14
+ import { tmpdir } from 'node:os';
15
+ import { join } from 'node:path';
16
+
17
+ import { SingleStreamDriver, normalizeStreamShim } from '../src/entry/loop.ts';
18
+ import type { DriverPorts, StreamRequestOptions, ToolBatchInputLike, ToolBatchResultLike, StreamDriverConfig } from '../src/entry/loop.ts';
19
+ import { createMockModel } from '../src/entry/mock-provider.ts';
20
+ import type { MockModel, Scenario } from '../src/entry/mock-provider.ts';
21
+ import { TfStreamParser } from '../src/kernel/parser.ts';
22
+ import { classifyTool, ObservationLedger } from '../src/kernel/obs.ts';
23
+ import { createCodeExecutor, looksLikePtcRuntime } from '../src/entry/ptc-bridge.ts';
24
+ import type { PtcRuntimeLike } from '../src/entry/ptc-bridge.ts';
25
+
26
+ // ---------------------------------------------------------------------------
27
+ // 测试设施
28
+ // ---------------------------------------------------------------------------
29
+
30
+ function createSandboxExecutor(sandboxDir: string) {
31
+ return async (input: ToolBatchInputLike): Promise<ToolBatchResultLike> => {
32
+ const results: ToolBatchResultLike['results'] = [];
33
+ for (const call of input.calls) {
34
+ const args = JSON.parse(call.arguments) as Record<string, unknown>;
35
+ results.push({ callId: call.id, result: { content: [{ type: 'text', text: `${call.name}:${JSON.stringify(args)}` }], isError: false } });
36
+ }
37
+ return { results, additionalContexts: [], concluded: false };
38
+ };
39
+ }
40
+
41
+ interface Harness {
42
+ driver: SingleStreamDriver;
43
+ model: MockModel;
44
+ wireRequests: Array<StreamRequestOptions & { contentTexts: string[] }>;
45
+ cleanup: () => void;
46
+ }
47
+
48
+ function makeHarness(opts: {
49
+ task: string;
50
+ scenarios: Scenario[];
51
+ executeCode?: DriverPorts['executeCode'];
52
+ config?: Partial<StreamDriverConfig>;
53
+ }): Harness {
54
+ const sandboxDir = mkdtempSync(join(tmpdir(), 'tf-ptc-'));
55
+ const model = createMockModel({ scenarios: opts.scenarios, provider: 'mock' });
56
+ const wireRequests: Array<StreamRequestOptions & { contentTexts: string[] }> = [];
57
+ const ports: DriverPorts = {
58
+ stream: (options) => {
59
+ wireRequests.push({ ...options, contentTexts: options.messages.map((m) => m.content.map((b) => b.text ?? '').join('\n')) });
60
+ return normalizeStreamShim(model.adapter.stream({ provider: options.provider, model: options.model, messages: options.messages, signal: options.signal }));
61
+ },
62
+ executeTools: createSandboxExecutor(sandboxDir),
63
+ ...(opts.executeCode === undefined ? {} : { executeCode: opts.executeCode }),
64
+ onToolSettled: () => model.notifyToolResult(),
65
+ };
66
+ const config: StreamDriverConfig = { provider: 'mock', model: 'mock-scenario', streamIdleTimeoutMs: 30_000, ...opts.config };
67
+ const driver = new SingleStreamDriver(ports, config);
68
+ driver.pushUserTask(opts.task);
69
+ return { driver, model, wireRequests, cleanup: () => rmSync(sandboxDir, { recursive: true, force: true }) };
70
+ }
71
+
72
+ function lastReasonOf(driver: SingleStreamDriver): string {
73
+ const ends = driver.snapshot().records.filter((r) => r.kind === 'turn-end');
74
+ const last = ends[ends.length - 1];
75
+ assert.ok(last !== undefined && last.kind === 'turn-end', '必须有 turn-end 记录');
76
+ return last.reason.kind;
77
+ }
78
+
79
+ // ---------------------------------------------------------------------------
80
+
81
+ describe('tf-code:parser 与 obs 内核层', () => {
82
+ it('P1. parser:tf-code 带 body 与 timeout/description 属性,闭合即派发事件', () => {
83
+ const parser = new TfStreamParser();
84
+ const events = parser.feed('<tf-code id="c1" timeout="60000" description="统计">return { n: 1 }</tf-code>');
85
+ const cmdEvent = events.find((e) => e.type === 'command');
86
+ assert.ok(cmdEvent !== undefined && cmdEvent.type === 'command', 'tf-code 应正常闭合');
87
+ const cmd = cmdEvent.command;
88
+ assert.equal(cmd.name, 'tf-code');
89
+ assert.equal(cmd.id, 'c1');
90
+ assert.equal(cmd.body, 'return { n: 1 }');
91
+ assert.equal(cmd.attrs['timeout'], '60000');
92
+ assert.equal(cmd.attrs['description'], '统计');
93
+ });
94
+
95
+ it('P2. obs:tf-code → code 族,首个观测 high(注骨架),重复内容 none,失败一律 high', () => {
96
+ assert.equal(classifyTool('tf-code'), 'code');
97
+ const obs = new ObservationLedger();
98
+ const first = obs.observe({ tool: 'tf-code', ok: true, key: 'code:统计', content: '{"n":1}', callId: 'c1' });
99
+ assert.equal(first.info_gain, 'high', '首个 code 观测应 high');
100
+ assert.ok(first.handle.startsWith('obs:code:c1@v'), `句柄族应为 code:${first.handle}`);
101
+ const dup = obs.observe({ tool: 'tf-code', ok: true, key: 'code:统计', content: '{"n":1}', callId: 'c2' });
102
+ assert.equal(dup.info_gain, 'none', '重复内容应 none');
103
+ const fail = obs.observe({ tool: 'tf-code', ok: false, key: 'code:统计', content: 'exception: boom', callId: 'c3' });
104
+ assert.equal(fail.info_gain, 'high', '失败一律 high');
105
+ });
106
+ });
107
+
108
+ describe('tf-code:ptc-bridge 适配器', () => {
109
+ const baseDeps = () => ({
110
+ executeTools: async (input: { calls: readonly { type: 'tool-call'; id: string; name: string; arguments: string }[] }) => ({
111
+ results: input.calls.map((c) => ({ callId: c.id, result: { content: [{ type: 'text', text: `${c.name}:ok(${c.arguments})` }], isError: false } })),
112
+ }),
113
+ });
114
+
115
+ it('B1. 形状校验:resolve+run 在位才算 PtcRuntime', () => {
116
+ assert.equal(looksLikePtcRuntime({ resolve: () => ({}), run: async () => ({}) }), true);
117
+ assert.equal(looksLikePtcRuntime({ run: async () => ({}) }), false);
118
+ assert.equal(looksLikePtcRuntime(undefined), false);
119
+ assert.equal(looksLikePtcRuntime('ptc'), false);
120
+ });
121
+
122
+ it('B2. 成功路径:程序进 resolve.request.program;bindings 三件套;value 无损 JSON 出', async () => {
123
+ const captured: Array<{ program: string; bindings: Array<{ global: string; functions: Record<string, (args: unknown) => Promise<unknown>> }> }> = [];
124
+ const runtime: PtcRuntimeLike = {
125
+ language: 'typescript',
126
+ resolve(request: { program: string; bindings?: unknown[] }) {
127
+ captured.push(request as never);
128
+ return { spec: true };
129
+ },
130
+ async run() {
131
+ return { value: { total: 10, hits: ['a'] }, logs: ['line1', 'line2'] };
132
+ },
133
+ };
134
+ const executeCode = createCodeExecutor(runtime, baseDeps());
135
+ const outcome = await executeCode({ callId: 'c1', code: 'return 1', signal: new AbortController().signal });
136
+ assert.ok(outcome.ok);
137
+ assert.equal(outcome.valueJson, '{"total":10,"hits":["a"]}');
138
+ assert.equal(outcome.logs, 'line1\nline2');
139
+ assert.equal(captured.length, 1);
140
+ assert.equal(captured[0]!.program, 'return 1');
141
+ const ns = captured[0]!.bindings[0]!;
142
+ assert.equal(ns.global, 'tools');
143
+ assert.deepEqual(Object.keys(ns.functions).sort(), ['pwsh', 'read', 'write']);
144
+ });
145
+
146
+ it('B3. bindings 走 executeTools;isError → 抛(对齐 ToolCallError 语义)', async () => {
147
+ let lastInput: { calls: readonly { name: string; arguments: string }[] } | undefined;
148
+ const runtime: PtcRuntimeLike = {
149
+ resolve(request: { program: string; bindings?: Array<{ global: string; functions: Record<string, (args: unknown) => Promise<unknown>> }> }) {
150
+ void runtime;
151
+ return { request };
152
+ },
153
+ async run(spec) {
154
+ const request = (spec as { request: { bindings: Array<{ global: string; functions: Record<string, (args: unknown) => Promise<unknown>> }> } }).request;
155
+ lastInput = undefined;
156
+ const written = await request.bindings[0]!.functions.write({ file_path: 'a.txt', content: 'hi' });
157
+ assert.equal(written, 'write:ok({"file_path":"a.txt","content":"hi"})');
158
+ try {
159
+ await request.bindings[0]!.functions.pwsh({ command: 'boom' });
160
+ assert.fail('isError 绑定必须抛');
161
+ } catch (error) {
162
+ assert.ok(error instanceof Error && error.message.includes('pwsh:failed'), `应抛宿主错误文本:${String(error)}`);
163
+ }
164
+ return { value: 'done' };
165
+ },
166
+ };
167
+ const executeCode = createCodeExecutor(runtime, {
168
+ executeTools: async (input) => {
169
+ lastInput = input as never;
170
+ const args = JSON.parse(input.calls[0]!.arguments) as Record<string, unknown>;
171
+ const isFailure = input.calls[0]!.name === 'pwsh';
172
+ return {
173
+ results: input.calls.map((c) => ({ callId: c.id, result: { content: [{ type: 'text', text: isFailure ? `${c.name}:failed:denied` : `${c.name}:ok(${input.calls[0]!.arguments})` }], isError: isFailure } })),
174
+ };
175
+ },
176
+ });
177
+ const outcome = await executeCode({ callId: 'c9', code: 'x', signal: new AbortController().signal, agent: { id: 'agent-1' } });
178
+ assert.ok(outcome.ok);
179
+ assert.equal(outcome.valueJson, '"done"');
180
+ assert.ok(lastInput !== undefined);
181
+ });
182
+
183
+ it('B4. 失败路径:result.error.kind 进 error 诊断;run() reject → ptc-runtime-misuse;logs 缺省 undefined', async () => {
184
+ const failing: PtcRuntimeLike = {
185
+ resolve: () => ({}),
186
+ async run() {
187
+ return { error: { kind: 'timeout', message: 'exceeded 120000ms' }, logs: { stdout: ['x'], stderr: [] } };
188
+ },
189
+ };
190
+ const executeCode = createCodeExecutor(failing, baseDeps());
191
+ const outcome = await executeCode({ callId: 'c1', code: 'x', signal: new AbortController().signal });
192
+ assert.ok(!outcome.ok);
193
+ assert.equal(outcome.error, 'timeout: exceeded 120000ms');
194
+ assert.equal(outcome.logs, '{"stdout":["x"],"stderr":[]}');
195
+
196
+ const misusing: PtcRuntimeLike = {
197
+ resolve: () => ({}),
198
+ async run() {
199
+ throw new Error('disposed');
200
+ },
201
+ };
202
+ const outcome2 = await createCodeExecutor(misusing, baseDeps())({ callId: 'c2', code: 'x', signal: new AbortController().signal });
203
+ assert.ok(!outcome2.ok);
204
+ assert.ok(outcome2.error.startsWith('ptc-runtime-misuse: disposed'));
205
+ assert.equal(outcome2.logs, undefined);
206
+ });
207
+ });
208
+
209
+ describe('tf-code:驱动器 E2E', () => {
210
+ let harness: Harness | undefined;
211
+ beforeEach(() => {
212
+ harness?.cleanup();
213
+ harness = undefined;
214
+ });
215
+
216
+ const codeScenario: Scenario = {
217
+ name: 'code-basic',
218
+ match: { promptIncludes: 'code 演练' },
219
+ chunking: { charsPerChunk: 0, delayMs: 0 },
220
+ steps: [
221
+ { type: 'text', text: '用程序统计。\n' },
222
+ { type: 'commands', commands: ['<tf-code id="c1" description="统计 ERROR">return { errorCount: 42 }</tf-code>', '<tf-final id="f1" summary="done"/>'] },
223
+ { type: 'waitTools', count: 1, timeoutMs: 5000 },
224
+ { type: 'finish', reason: 'stop' },
225
+ ],
226
+ };
227
+
228
+ it('E1. 成功:命令 ok + code 族句柄 + 值注入下一请求;协议文本声明 tf-code(显式开启,K1)', async () => {
229
+ harness = makeHarness({
230
+ task: 'code 演练:统计日志错误。',
231
+ scenarios: [codeScenario],
232
+ executeCode: async () => ({ ok: true, valueJson: '{"errorCount":42}' }),
233
+ // K1:通道默认关闭,opt-in 显式开启;F3:值 17 字符 ≤ 4000 上限 → 完整注入
234
+ config: { enableCode: true },
235
+ });
236
+ try {
237
+ const reason = await harness.driver.runTurn();
238
+ assert.equal(reason.kind, 'completed');
239
+ const snap = harness.driver.snapshot();
240
+ const c1 = snap.records.find((r) => r.kind === 'command' && r.id === 'c1' && r.status === 'ok');
241
+ assert.ok(c1 !== undefined, 'tf-code 应 ok');
242
+ const observation = snap.records.find((r) => r.kind === 'observation' && r.handle !== null && r.handle.startsWith('obs:code:c1@v'));
243
+ assert.ok(observation !== undefined, '应有 obs:code 句柄');
244
+ // 通道启用 → 协议文本声明 tf-code(进请求 1 的 system 消息)
245
+ assert.ok(harness.wireRequests[0]!.contentTexts[0]!.includes('tf-code 程序化工具调用'), '协议应声明 tf-code');
246
+ // 高增益骨架注入下一请求
247
+ const req2 = harness.wireRequests[1]!;
248
+ assert.ok(
249
+ req2.contentTexts.some((t) => t.includes('[tf-stream:observation handle=obs:code:c1@v')),
250
+ '请求 2 应注入 code 观测骨架',
251
+ );
252
+ } finally {
253
+ harness.cleanup();
254
+ }
255
+ });
256
+
257
+ it('E2. 程序失败:结构化错误注入(kind + retry 结论 + 建议改道),模型重发后收敛', async () => {
258
+ let calls = 0;
259
+ harness = makeHarness({
260
+ task: 'code 演练:统计日志错误。',
261
+ scenarios: [
262
+ {
263
+ name: 'code-retry',
264
+ match: { promptIncludes: 'tf-stream:error id=c1' },
265
+ chunking: { charsPerChunk: 0, delayMs: 0 },
266
+ steps: [
267
+ { type: 'text', text: '修复后重发。\n' },
268
+ { type: 'commands', commands: ['<tf-code id="c2" description="统计 ERROR 修复版">return { errorCount: 42 }</tf-code>', '<tf-final id="f2" summary="done"/>'] },
269
+ { type: 'waitTools', count: 1, timeoutMs: 5000 },
270
+ { type: 'finish', reason: 'stop' },
271
+ ],
272
+ },
273
+ codeScenario,
274
+ ],
275
+ executeCode: async (input) => {
276
+ calls += 1;
277
+ if (input.callId === 'c1') return { ok: false, kind: 'exception', retryable: true, advice: '修复后换新 id 重发。', error: 'exception: TypeError: x is not a function' };
278
+ return { ok: true, valueJson: '{"errorCount":42}' };
279
+ },
280
+ config: { enableCode: true },
281
+ });
282
+ try {
283
+ const reason = await harness.driver.runTurn();
284
+ assert.equal(reason.kind, 'completed');
285
+ assert.equal(calls, 2, '失败一次 + 修复重发一次');
286
+ const req2 = harness.wireRequests[1]!;
287
+ const errBlock = req2.contentTexts.find((t) => t.includes('[tf-stream:error id=c1 cmd=tf-code]'));
288
+ assert.ok(errBlock !== undefined, `应注入结构化错误:\n${req2.contentTexts.join('\n---\n').slice(0, 1500)}`);
289
+ assert.ok(errBlock.includes('exception: TypeError'), '错误块应含 kind 与诊断');
290
+ assert.ok(errBlock.includes('建议:'), '错误块应含改道建议');
291
+ } finally {
292
+ harness.cleanup();
293
+ }
294
+ });
295
+
296
+ it('E3. 默认关闭(K1):无端口/未显式开启 → no-code-channel 命令级失败;协议文本不声明 tf-code', async () => {
297
+ harness = makeHarness({
298
+ task: 'code 演练:统计日志错误。',
299
+ scenarios: [
300
+ {
301
+ name: 'code-fallback',
302
+ match: { promptIncludes: 'tf-stream:error id=c1' },
303
+ chunking: { charsPerChunk: 0, delayMs: 0 },
304
+ steps: [
305
+ { type: 'text', text: '通道缺失,改道收尾。\n' },
306
+ { type: 'commands', commands: ['<tf-final id="f2" summary="改道完成"/>'] },
307
+ { type: 'finish', reason: 'stop' },
308
+ ],
309
+ },
310
+ codeScenario,
311
+ ],
312
+ // 不提供 executeCode
313
+ });
314
+ try {
315
+ const reason = await harness.driver.runTurn();
316
+ assert.equal(reason.kind, 'completed');
317
+ assert.ok(!harness.wireRequests[0]!.contentTexts[0]!.includes('tf-code 程序化工具调用'), '通道关闭时协议不得声明 tf-code');
318
+ const req2 = harness.wireRequests[1]!;
319
+ const errBlock = req2.contentTexts.find((t) => t.includes('[tf-stream:error id=c1 cmd=tf-code]'));
320
+ assert.ok(errBlock !== undefined && errBlock.includes('no-code-channel'), '应注入通道缺失错误');
321
+ assert.ok(errBlock.includes('ptcRuntime'), '错误应指明缺失的服务缝');
322
+ } finally {
323
+ harness.cleanup();
324
+ }
325
+ });
326
+
327
+ it('E4. enableCode=false → 强制关闭(端口在位也不声明、命令级失败)', async () => {
328
+ harness = makeHarness({
329
+ task: 'code 演练:统计日志错误。',
330
+ scenarios: [
331
+ {
332
+ name: 'code-off',
333
+ match: { promptIncludes: 'tf-stream:error id=c1' },
334
+ chunking: { charsPerChunk: 0, delayMs: 0 },
335
+ steps: [
336
+ { type: 'text', text: '通道被配置关闭。\n' },
337
+ { type: 'commands', commands: ['<tf-final id="f2" summary="off"/>'] },
338
+ { type: 'finish', reason: 'stop' },
339
+ ],
340
+ },
341
+ codeScenario,
342
+ ],
343
+ executeCode: async () => ({ ok: true, valueJson: '{}' }),
344
+ config: { enableCode: false },
345
+ });
346
+ try {
347
+ const reason = await harness.driver.runTurn();
348
+ assert.equal(reason.kind, 'completed');
349
+ assert.ok(!harness.wireRequests[0]!.contentTexts[0]!.includes('tf-code 程序化工具调用'), '配置关闭时协议不得声明 tf-code');
350
+ const errBlock = harness.wireRequests[1]!.contentTexts.find((t) => t.includes('no-code-channel'));
351
+ assert.ok(errBlock !== undefined, '配置关闭应命令级失败');
352
+ } finally {
353
+ harness.cleanup();
354
+ }
355
+ });
356
+ });