@hugesb/dsh-stream-agent 0.3.1 → 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 +125 -0
- package/README.en.md +3 -3
- package/README.md +3 -3
- package/dist/entry/loop.js +332 -21
- package/dist/entry/mock-provider.js +20 -7
- package/dist/kernel/parser.js +488 -39
- package/dist/kernel/render.js +25 -3
- package/dist/version.js +1 -1
- package/package.json +2 -2
- package/scripts/release.mjs +20 -7
- package/scripts/repair-session-logs.mjs +105 -10
- package/src/entry/loop.ts +332 -21
- package/src/entry/mock-provider.ts +20 -7
- package/src/kernel/parser.ts +488 -39
- package/src/kernel/render.ts +25 -3
- package/src/version.ts +1 -1
- package/test/host-conformance.test.ts +418 -0
- package/test/kernel/parser.test.ts +3 -2
- package/test/v032-conflict.test.ts +191 -0
- package/test/v032-truncation.test.ts +291 -0
package/src/kernel/render.ts
CHANGED
|
@@ -26,9 +26,23 @@ import { createHash } from 'node:crypto';
|
|
|
26
26
|
|
|
27
27
|
export type MessageRole = 'system' | 'user' | 'assistant' | 'tool';
|
|
28
28
|
|
|
29
|
+
/** v0.3.2:assistant 消息的宿主来源元数据。宿主 LlmRuntime.forAdapter(dsh-llm
|
|
30
|
+
* lib/index.js:2277;GitHub master packages/llm/llm/src/index.ts 同源无防护)对请求里的
|
|
31
|
+
* 每条 assistant 消息读 `message.source.replayState`——source 缺失 = TypeError
|
|
32
|
+
* "Cannot read properties of undefined (reading 'replayState')",流以 error finish 收场,
|
|
33
|
+
* 回合中断(真机 session-8f22c7a0 seq 121 实证:正文首次落追加区后的下一请求必崩)。
|
|
34
|
+
* replayState 本身可选(dsh-llm types.d.ts:15),缺失时宿主按"无原生回放"处理。 */
|
|
35
|
+
export interface RenderMessageSource {
|
|
36
|
+
kind: 'model';
|
|
37
|
+
provider: string;
|
|
38
|
+
model: string;
|
|
39
|
+
}
|
|
40
|
+
|
|
29
41
|
export interface RenderMessage {
|
|
30
42
|
role: MessageRole;
|
|
31
43
|
content: string;
|
|
44
|
+
/** 仅 assistant 消息需要;user/system 消息宿主不读 source。 */
|
|
45
|
+
source?: RenderMessageSource;
|
|
32
46
|
}
|
|
33
47
|
|
|
34
48
|
/** 与 03 号分派 obs.ts 的 directoryDelta(sinceSeq) 返回结构兼容(结构化类型,不 import)。 */
|
|
@@ -161,6 +175,8 @@ interface AppendBlock {
|
|
|
161
175
|
kind: AppendBlockKind;
|
|
162
176
|
role: MessageRole;
|
|
163
177
|
content: string;
|
|
178
|
+
/** v0.3.2:assistant 追加块携带宿主来源(stableMessages 装配时透传进请求)。 */
|
|
179
|
+
source?: RenderMessageSource;
|
|
164
180
|
}
|
|
165
181
|
|
|
166
182
|
interface TailBlock {
|
|
@@ -241,7 +257,8 @@ export class ContextRenderer {
|
|
|
241
257
|
if (msg.role === 'system') {
|
|
242
258
|
throw new Error('appendHistory 不接受 system 消息:system 属于稳定前缀');
|
|
243
259
|
}
|
|
244
|
-
|
|
260
|
+
// v0.3.2:source 必须保留(assistant 块不带 source = 请求在宿主 forAdapter 崩溃)。
|
|
261
|
+
this.#appendBlocks.push({ kind: 'history', role: msg.role, content: msg.content, ...(msg.source === undefined ? {} : { source: msg.source }) });
|
|
245
262
|
}
|
|
246
263
|
|
|
247
264
|
/**
|
|
@@ -317,11 +334,16 @@ export class ContextRenderer {
|
|
|
317
334
|
|
|
318
335
|
// ------------------------------------------------------------------- 装配
|
|
319
336
|
|
|
320
|
-
/** 稳定段 = 稳定前缀 ++ 追加区(不含易变尾)。
|
|
337
|
+
/** 稳定段 = 稳定前缀 ++ 追加区(不含易变尾)。v0.3.2:assistant 块的 source 随装配
|
|
338
|
+
* 透传(宿主 forAdapter 读 assistant 消息的 source.replayState,缺失即崩)。 */
|
|
321
339
|
stableMessages(): RenderMessage[] {
|
|
322
340
|
return [
|
|
323
341
|
...this.#prefix,
|
|
324
|
-
...this.#appendBlocks.map((b) => (
|
|
342
|
+
...this.#appendBlocks.map((b) => (
|
|
343
|
+
b.source === undefined
|
|
344
|
+
? { role: b.role, content: b.content }
|
|
345
|
+
: { role: b.role, content: b.content, source: b.source }
|
|
346
|
+
)),
|
|
325
347
|
];
|
|
326
348
|
}
|
|
327
349
|
|
package/src/version.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// 为什么单独一个文件:控制栏在 stderr 与 --json 里都要报版本,而 kernel 不读 package.json
|
|
4
4
|
// (内核零 IO 纪律),entry 也不该各自硬编码字符串。
|
|
5
5
|
|
|
6
|
-
export const VERSION = '0.3.
|
|
6
|
+
export const VERSION = '0.3.2';
|
|
7
7
|
|
|
8
8
|
/** 版本来源:npm 源未上线时引导用户用本地路径安装的提示会用到。 */
|
|
9
9
|
export const PACKAGE_NAME = '@hugesb/dsh-stream-agent';
|
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
// test/host-conformance.test.ts —— v0.3.2:宿主一致性回归(历史加载失败 + UI 卡住两案)
|
|
2
|
+
//
|
|
3
|
+
// 两起真机事故同源:插件的 duck-type 面缺了宿主侧的形状/事件契约——
|
|
4
|
+
// ① 会话日志:assistant/message 的 source 只写 `{kind:'model'}`,缺非空 provider/model。
|
|
5
|
+
// 宿主校验器(dsh-session assertMessageEventShape → hasProviderModel)读取时抛
|
|
6
|
+
// `message must have model source`,整条会话判 corrupt → 桌面端"历史加载失败"。
|
|
7
|
+
// ② 事件面:StreamLoopAgent 从不发 `agent/status`(内建 loop 的 setPhase 语义)。
|
|
8
|
+
// 桌面端 dsh-api-session-controller 靠它转发 api-session/status 收起"运行中"指示——
|
|
9
|
+
// 不发 = 回合结束后 UI 永远转圈。缺 `agent.inject` 则让改审批策略的命令报
|
|
10
|
+
// "agent.inject is not a function"。
|
|
11
|
+
//
|
|
12
|
+
// 本文件按宿主同款规则本地复核(仓库零宿主依赖红线);宿主真实校验器的对照验证走
|
|
13
|
+
// scripts/repair-session-logs.mjs 的 DSH_HOST_MODULES 通道。
|
|
14
|
+
|
|
15
|
+
import { describe, it } from 'node:test';
|
|
16
|
+
import assert from 'node:assert/strict';
|
|
17
|
+
import { readFileSync } from 'node:fs';
|
|
18
|
+
import { join } from 'node:path';
|
|
19
|
+
|
|
20
|
+
import { SingleStreamDriver, normalizeStreamShim, createSessionEventWriter, StreamLoopAgent } from '../src/entry/loop.ts';
|
|
21
|
+
import type { ToolBatchInputLike, ToolBatchResultLike, ModelSourceInfo } from '../src/entry/loop.ts';
|
|
22
|
+
import { createMockModel } from '../src/entry/mock-provider.ts';
|
|
23
|
+
import type { MockModel, Scenario } from '../src/entry/mock-provider.ts';
|
|
24
|
+
|
|
25
|
+
interface FakeEvent {
|
|
26
|
+
type: string;
|
|
27
|
+
seq: number;
|
|
28
|
+
time: number;
|
|
29
|
+
data: Record<string, unknown>;
|
|
30
|
+
surfaceOp?: string;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
interface FakeSession {
|
|
34
|
+
id: string;
|
|
35
|
+
readonly seq: number;
|
|
36
|
+
events: FakeEvent[];
|
|
37
|
+
append(type: string, data: unknown, opts?: { surfaceOp?: string }): FakeEvent;
|
|
38
|
+
snapshotEvents(from?: number): FakeEvent[];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function createFakeSession(): FakeSession {
|
|
42
|
+
const events: FakeEvent[] = [];
|
|
43
|
+
let seq = 0;
|
|
44
|
+
return {
|
|
45
|
+
id: 'host-conformance-fixture',
|
|
46
|
+
get seq() {
|
|
47
|
+
return seq;
|
|
48
|
+
},
|
|
49
|
+
events,
|
|
50
|
+
append(type, data, opts) {
|
|
51
|
+
const event: FakeEvent = { type, seq: seq++, time: Date.now(), data: data as Record<string, unknown> };
|
|
52
|
+
if (opts?.surfaceOp !== undefined) event.surfaceOp = opts.surfaceOp;
|
|
53
|
+
events.push(event);
|
|
54
|
+
return event;
|
|
55
|
+
},
|
|
56
|
+
snapshotEvents(from = 0) {
|
|
57
|
+
return events.slice(from);
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function loadScenario(name: string): Scenario {
|
|
63
|
+
return JSON.parse(readFileSync(join(import.meta.dirname, 'scenarios', name), 'utf8')) as Scenario;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** 宿主同款工具管线:任意调用都落 tool/call + tool/result(与 session-format.test.ts 同形)。 */
|
|
67
|
+
function createHostLikeTools(session: FakeSession) {
|
|
68
|
+
return async (input: ToolBatchInputLike): Promise<ToolBatchResultLike> => {
|
|
69
|
+
const results = [];
|
|
70
|
+
for (const call of input.calls) {
|
|
71
|
+
const content = [{ type: 'text' as const, text: `ok:${call.name}` }];
|
|
72
|
+
const callSeq = session.append('tool/call', {
|
|
73
|
+
turn: input.log?.turn,
|
|
74
|
+
step: input.log?.step,
|
|
75
|
+
callId: call.id,
|
|
76
|
+
name: call.name,
|
|
77
|
+
arguments: call.arguments,
|
|
78
|
+
}).seq;
|
|
79
|
+
session.append('tool/result', {
|
|
80
|
+
turn: input.log?.turn,
|
|
81
|
+
step: input.log?.step,
|
|
82
|
+
message: {
|
|
83
|
+
id: `tool-result-${call.id}`,
|
|
84
|
+
role: 'tool',
|
|
85
|
+
source: { kind: 'tool', callId: call.id },
|
|
86
|
+
toolCallId: call.id,
|
|
87
|
+
content,
|
|
88
|
+
},
|
|
89
|
+
}, { surfaceOp: 'append' });
|
|
90
|
+
results.push({ callId: call.id, result: { content, isError: false } });
|
|
91
|
+
}
|
|
92
|
+
return { results };
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* 宿主同款消息形状校验(dsh-session/lib/index.js assertMessageEventShape + hasProviderModel
|
|
98
|
+
* 的本地镜像):五类 message 事件逐条过规则,违规即整条日志 corrupt。
|
|
99
|
+
*/
|
|
100
|
+
function assertMessageEventShapes(events: readonly FakeEvent[]): void {
|
|
101
|
+
const expectedRole: Record<string, string> = {
|
|
102
|
+
'system/message': 'system',
|
|
103
|
+
'developer/message': 'developer',
|
|
104
|
+
'user/message': 'user',
|
|
105
|
+
'assistant/message': 'assistant',
|
|
106
|
+
'tool/result': 'tool',
|
|
107
|
+
};
|
|
108
|
+
for (const event of events) {
|
|
109
|
+
const type = event.type;
|
|
110
|
+
if (!(type in expectedRole)) continue;
|
|
111
|
+
const data = event.data as { message?: { id?: unknown; role?: unknown; source?: { kind?: unknown; provider?: unknown; model?: unknown; callId?: unknown }; content?: unknown; toolCallId?: unknown } };
|
|
112
|
+
const message = type === 'user/message' ? (event.data as Record<string, unknown>) : data.message;
|
|
113
|
+
assert.ok(message !== null && typeof message === 'object', `${type}#${event.seq} 缺 message`);
|
|
114
|
+
assert.equal(typeof message.id, 'string', `${type}#${event.seq} 缺非空 id`);
|
|
115
|
+
assert.notEqual((message.id as string).length, 0, `${type}#${event.seq} id 不得为空`);
|
|
116
|
+
assert.equal(message.role, expectedRole[type], `${type}#${event.seq} role 必须是 "${expectedRole[type]}"`);
|
|
117
|
+
assert.ok(message.source !== null && typeof message.source === 'object', `${type}#${event.seq} 缺 source`);
|
|
118
|
+
assert.equal(typeof message.source!.kind, 'string', `${type}#${event.seq} source.kind 缺失`);
|
|
119
|
+
assert.notEqual(message.source!.kind, '', `${type}#${event.seq} source.kind 不得为空`);
|
|
120
|
+
assert.ok(Array.isArray(message.content), `${type}#${event.seq} content 必须是数组`);
|
|
121
|
+
if (type === 'assistant/message') {
|
|
122
|
+
assert.equal(message.source!.kind, 'model', `assistant/message#${event.seq} source 必须是 model`);
|
|
123
|
+
assert.equal(typeof message.source!.provider, 'string', `assistant/message#${event.seq} 缺 provider(历史加载失败根因)`);
|
|
124
|
+
assert.notEqual(message.source!.provider, '', `assistant/message#${event.seq} provider 不得为空`);
|
|
125
|
+
assert.equal(typeof message.source!.model, 'string', `assistant/message#${event.seq} 缺 model(历史加载失败根因)`);
|
|
126
|
+
assert.notEqual(message.source!.model, '', `assistant/message#${event.seq} model 不得为空`);
|
|
127
|
+
}
|
|
128
|
+
if (type === 'tool/result') {
|
|
129
|
+
assert.equal(message.source!.kind, 'tool', `tool/result#${event.seq} source 必须是 tool`);
|
|
130
|
+
assert.equal(typeof message.source!.callId, 'string', `tool/result#${event.seq} 缺 source.callId`);
|
|
131
|
+
assert.equal(message.toolCallId, message.source!.callId, `tool/result#${event.seq} toolCallId 与 source.callId 不一致`);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function createDriver(session: FakeSession, model: MockModel, modelInfo: () => ModelSourceInfo) {
|
|
137
|
+
return new SingleStreamDriver({
|
|
138
|
+
stream: (options) => normalizeStreamShim(model.adapter.stream({
|
|
139
|
+
provider: options.provider,
|
|
140
|
+
model: options.model,
|
|
141
|
+
messages: options.messages,
|
|
142
|
+
signal: options.signal,
|
|
143
|
+
})),
|
|
144
|
+
executeTools: createHostLikeTools(session),
|
|
145
|
+
events: createSessionEventWriter(session, modelInfo),
|
|
146
|
+
onToolSettled: () => model.notifyToolResult(),
|
|
147
|
+
}, { provider: 'mock-provider', model: 'mock-model', streamIdleTimeoutMs: 30_000 });
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// ---------------------------------------------------------------------------
|
|
151
|
+
// C1:会话日志 model source(历史加载失败根因)
|
|
152
|
+
// ---------------------------------------------------------------------------
|
|
153
|
+
|
|
154
|
+
describe('HC. 宿主一致性(v0.3.2 回归)', () => {
|
|
155
|
+
it('HC1. assistant/message 的 source 必须带非空 provider/model(含广告消息),且整条日志过宿主形状校验', async () => {
|
|
156
|
+
const session = createFakeSession();
|
|
157
|
+
const model = createMockModel({ scenarios: [loadScenario('5-file-basic.json')], provider: 'mock-provider' });
|
|
158
|
+
let driverRef: SingleStreamDriver | undefined;
|
|
159
|
+
const driver = createDriver(session, model, () => driverRef!.modelSource());
|
|
160
|
+
driverRef = driver;
|
|
161
|
+
driver.pushUserTask('请写五个文件:f1 到 f5。');
|
|
162
|
+
const reason = await driver.runTurn();
|
|
163
|
+
assert.equal(reason.kind, 'completed');
|
|
164
|
+
// 整条日志按宿主同款规则过一遍——任何一条不合规 = 桌面端"历史加载失败"。
|
|
165
|
+
assertMessageEventShapes(session.events);
|
|
166
|
+
const messages = session.events.filter((e) => e.type === 'assistant/message');
|
|
167
|
+
assert.ok(messages.length >= 2, `至少有广告消息与正文消息,实际 ${messages.length}`);
|
|
168
|
+
for (const message of messages) {
|
|
169
|
+
const source = (message.data as { message?: { source?: { kind?: string; provider?: string; model?: string } } }).message?.source;
|
|
170
|
+
assert.equal(source?.kind, 'model');
|
|
171
|
+
assert.equal(source?.provider, 'mock-provider', 'provider 必须来自驱动器实时配置');
|
|
172
|
+
assert.equal(source?.model, 'mock-model', 'model 必须来自驱动器实时配置');
|
|
173
|
+
}
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
it('HC2. applySelection 运行时换模后,新写入的消息取实时 provider/model(写入时取,不缓存)', async () => {
|
|
177
|
+
const session = createFakeSession();
|
|
178
|
+
const scenario: Scenario = {
|
|
179
|
+
name: 'hc2-switch',
|
|
180
|
+
match: { promptIncludes: '换模演练' },
|
|
181
|
+
chunking: { charsPerChunk: 0, delayMs: 0 },
|
|
182
|
+
steps: [
|
|
183
|
+
{ type: 'text', text: '换模后收尾。\n' },
|
|
184
|
+
{ type: 'commands', commands: ['<tf-final id="f1" summary="switched-done"/>'] },
|
|
185
|
+
{ type: 'finish', reason: 'stop' },
|
|
186
|
+
],
|
|
187
|
+
};
|
|
188
|
+
const model = createMockModel({ scenarios: [scenario], provider: 'mock-provider' });
|
|
189
|
+
let driverRef: SingleStreamDriver | undefined;
|
|
190
|
+
const driver = createDriver(session, model, () => driverRef!.modelSource());
|
|
191
|
+
driverRef = driver;
|
|
192
|
+
driver.pushUserTask('换模演练:直接收尾。');
|
|
193
|
+
await driver.runTurn();
|
|
194
|
+
driver.applySelection({ provider: 'provider-b', model: 'model-b' });
|
|
195
|
+
driver.pushUserTask('换模演练:第二回合直接收尾。');
|
|
196
|
+
await driver.runTurn();
|
|
197
|
+
assertMessageEventShapes(session.events);
|
|
198
|
+
const messages = session.events.filter((e) => e.type === 'assistant/message');
|
|
199
|
+
const lastSource = (messages.at(-1)!.data as { message?: { source?: { provider?: string; model?: string } } }).message?.source;
|
|
200
|
+
assert.equal(lastSource?.provider, 'provider-b', '换模后的消息必须取实时 provider');
|
|
201
|
+
assert.equal(lastSource?.model, 'model-b', '换模后的消息必须取实时 model');
|
|
202
|
+
const firstSource = (messages[0].data as { message?: { source?: { provider?: string; model?: string } } }).message?.source;
|
|
203
|
+
assert.equal(firstSource?.provider, 'mock-provider', '换模前的消息保留首请求路由');
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
it('HC3. 无模型路由信息(离线/缺省)时 source 落 unknown 兜底——日志形状仍过宿主校验', () => {
|
|
207
|
+
const session = createFakeSession();
|
|
208
|
+
const writer = createSessionEventWriter(session);
|
|
209
|
+
assert.notEqual(writer, undefined);
|
|
210
|
+
writer!.assistantMessage(1, 1, '离线正文', {
|
|
211
|
+
finish: { kind: 'stop' },
|
|
212
|
+
});
|
|
213
|
+
assertMessageEventShapes(session.events);
|
|
214
|
+
const source = (session.events[0].data as { message?: { source?: { provider?: string; model?: string } } }).message?.source;
|
|
215
|
+
assert.equal(source?.provider, 'unknown');
|
|
216
|
+
assert.equal(source?.model, 'unknown');
|
|
217
|
+
});
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
// ---------------------------------------------------------------------------
|
|
221
|
+
// C2:agent/status 事件面(UI 卡住根因)
|
|
222
|
+
// ---------------------------------------------------------------------------
|
|
223
|
+
|
|
224
|
+
describe('HC4. agent/status 转换事件(镜像内建 setPhase:只在变化时发)', () => {
|
|
225
|
+
it('HC4a. followup → running,回合收敛 → idle,且序列精确(不重复、不遗漏)', async () => {
|
|
226
|
+
const session = createFakeSession();
|
|
227
|
+
const scenario: Scenario = {
|
|
228
|
+
name: 'hc4-status',
|
|
229
|
+
match: { promptIncludes: '状态演练' },
|
|
230
|
+
chunking: { charsPerChunk: 0, delayMs: 0 },
|
|
231
|
+
steps: [
|
|
232
|
+
{ type: 'text', text: '状态演练收尾。\n' },
|
|
233
|
+
{ type: 'commands', commands: ['<tf-final id="f1" summary="status-done"/>'] },
|
|
234
|
+
{ type: 'finish', reason: 'stop' },
|
|
235
|
+
],
|
|
236
|
+
};
|
|
237
|
+
const model = createMockModel({ scenarios: [scenario], provider: 'mock-provider' });
|
|
238
|
+
const driver = new SingleStreamDriver({
|
|
239
|
+
stream: (options) => normalizeStreamShim(model.adapter.stream({ provider: options.provider, model: options.model, messages: options.messages, signal: options.signal })),
|
|
240
|
+
executeTools: createHostLikeTools(session),
|
|
241
|
+
onToolSettled: () => model.notifyToolResult(),
|
|
242
|
+
}, { provider: 'mock-provider', model: 'mock-model', streamIdleTimeoutMs: 30_000 });
|
|
243
|
+
const transitions: Array<{ status: string }> = [];
|
|
244
|
+
const agent = new StreamLoopAgent({
|
|
245
|
+
id: 'hc4-agent',
|
|
246
|
+
session,
|
|
247
|
+
driver,
|
|
248
|
+
modelSelection: { provider: 'mock-provider', model: 'mock-model' },
|
|
249
|
+
emitStatus: (payload) => transitions.push({ status: payload.status as string }),
|
|
250
|
+
});
|
|
251
|
+
assert.equal(agent.status, 'idle');
|
|
252
|
+
agent.followup({ role: 'user', content: [{ type: 'text', text: '状态演练:直接收尾。' }] });
|
|
253
|
+
assert.equal(agent.status, 'running');
|
|
254
|
+
assert.deepEqual(transitions, [{ status: 'running' }], '开始回合必须恰好发一次 running');
|
|
255
|
+
await agent.whenIdle();
|
|
256
|
+
assert.equal(agent.status, 'idle');
|
|
257
|
+
assert.deepEqual(transitions, [{ status: 'running' }, { status: 'idle' }], '回合结束必须恰好发一次 idle');
|
|
258
|
+
// 第二回合:再来一对 running/idle(转换才发,不做重复广播)
|
|
259
|
+
agent.followup({ role: 'user', content: [{ type: 'text', text: '状态演练:第二回合直接收尾。' }] });
|
|
260
|
+
await agent.whenIdle();
|
|
261
|
+
assert.deepEqual(transitions, [
|
|
262
|
+
{ status: 'running' }, { status: 'idle' },
|
|
263
|
+
{ status: 'running' }, { status: 'idle' },
|
|
264
|
+
]);
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
it('HC4b. emitStatus 抛错不阻断回合(fail-open),回合照常收敛', async () => {
|
|
268
|
+
const session = createFakeSession();
|
|
269
|
+
const scenario: Scenario = {
|
|
270
|
+
name: 'hc4b-boom',
|
|
271
|
+
match: { promptIncludes: '熔断演练' },
|
|
272
|
+
chunking: { charsPerChunk: 0, delayMs: 0 },
|
|
273
|
+
steps: [
|
|
274
|
+
{ type: 'text', text: '熔断演练收尾。\n' },
|
|
275
|
+
{ type: 'commands', commands: ['<tf-final id="f1" summary="boom-done"/>'] },
|
|
276
|
+
{ type: 'finish', reason: 'stop' },
|
|
277
|
+
],
|
|
278
|
+
};
|
|
279
|
+
const model = createMockModel({ scenarios: [scenario], provider: 'mock-provider' });
|
|
280
|
+
const driver = new SingleStreamDriver({
|
|
281
|
+
stream: (options) => normalizeStreamShim(model.adapter.stream({ provider: options.provider, model: options.model, messages: options.messages, signal: options.signal })),
|
|
282
|
+
executeTools: createHostLikeTools(session),
|
|
283
|
+
onToolSettled: () => model.notifyToolResult(),
|
|
284
|
+
}, { provider: 'mock-provider', model: 'mock-model', streamIdleTimeoutMs: 30_000 });
|
|
285
|
+
const warnings: string[] = [];
|
|
286
|
+
const agent = new StreamLoopAgent({
|
|
287
|
+
id: 'hc4b-agent',
|
|
288
|
+
session,
|
|
289
|
+
driver,
|
|
290
|
+
modelSelection: { provider: 'mock-provider', model: 'mock-model' },
|
|
291
|
+
emitStatus: () => {
|
|
292
|
+
throw new Error('bus exploded');
|
|
293
|
+
},
|
|
294
|
+
onWarning: (message) => warnings.push(message),
|
|
295
|
+
});
|
|
296
|
+
agent.followup({ role: 'user', content: [{ type: 'text', text: '熔断演练:直接收尾。' }] });
|
|
297
|
+
await agent.whenIdle();
|
|
298
|
+
assert.equal(agent.status, 'idle', '发射异常不得阻断回合收束');
|
|
299
|
+
assert.ok(warnings.some((w) => w.includes('agent/status')), '发射异常必须走告警出口(不静默)');
|
|
300
|
+
const finals = driver.snapshot().records.filter((r) => r.kind === 'final');
|
|
301
|
+
assert.equal((finals.at(-1) as { summary?: string }).summary, 'boom-done');
|
|
302
|
+
});
|
|
303
|
+
});
|
|
304
|
+
|
|
305
|
+
// ---------------------------------------------------------------------------
|
|
306
|
+
// C3:inject 事件面(改审批策略命令的报错根因)
|
|
307
|
+
// ---------------------------------------------------------------------------
|
|
308
|
+
|
|
309
|
+
describe('HC5. agent.inject(dsh-user-approval setPolicy 的依赖面)', () => {
|
|
310
|
+
it('HC5a. 空闲 inject:落盘 user/message + 并入下一请求装配,但不唤醒回合', async () => {
|
|
311
|
+
const session = createFakeSession();
|
|
312
|
+
const scenario: Scenario = {
|
|
313
|
+
name: 'hc5a-inject',
|
|
314
|
+
match: { promptIncludes: '注入演练' },
|
|
315
|
+
chunking: { charsPerChunk: 0, delayMs: 0 },
|
|
316
|
+
steps: [
|
|
317
|
+
{ type: 'text', text: '注入演练收尾。\n' },
|
|
318
|
+
{ type: 'commands', commands: ['<tf-final id="f1" summary="inject-done"/>'] },
|
|
319
|
+
{ type: 'finish', reason: 'stop' },
|
|
320
|
+
],
|
|
321
|
+
};
|
|
322
|
+
const model = createMockModel({ scenarios: [scenario], provider: 'mock-provider' });
|
|
323
|
+
const driver = new SingleStreamDriver({
|
|
324
|
+
stream: (options) => normalizeStreamShim(model.adapter.stream({ provider: options.provider, model: options.model, messages: options.messages, signal: options.signal })),
|
|
325
|
+
executeTools: createHostLikeTools(session),
|
|
326
|
+
onToolSettled: () => model.notifyToolResult(),
|
|
327
|
+
}, { provider: 'mock-provider', model: 'mock-model', streamIdleTimeoutMs: 30_000 });
|
|
328
|
+
const agent = new StreamLoopAgent({
|
|
329
|
+
id: 'hc5a-agent',
|
|
330
|
+
session,
|
|
331
|
+
driver,
|
|
332
|
+
modelSelection: { provider: 'mock-provider', model: 'mock-model' },
|
|
333
|
+
});
|
|
334
|
+
agent.inject({
|
|
335
|
+
id: 'notice-1',
|
|
336
|
+
role: 'user',
|
|
337
|
+
content: [{ type: 'text', text: 'The user changed the approval policy from "ask" to "never".' }],
|
|
338
|
+
source: { kind: 'user-approval' },
|
|
339
|
+
});
|
|
340
|
+
assert.equal(agent.status, 'idle', '通知型注入不得自己开回合(镜像内建 send(...,false))');
|
|
341
|
+
assert.equal(session.events.filter((e) => e.type === 'user/message').length, 1, '注入必须落盘 user/message');
|
|
342
|
+
assert.equal((driver.pendingSteerMessages as unknown[]).length, 1, '注入并入下一请求装配(next-step)');
|
|
343
|
+
assert.equal(agent.inbox.nextStep.length, 1, 'inbox 面如实暴露待消费注入');
|
|
344
|
+
// 下一回合首请求消费注入(runTurn 每次请求前 splice pendingSteers)
|
|
345
|
+
agent.followup({ role: 'user', content: [{ type: 'text', text: '注入演练:直接收尾。' }] });
|
|
346
|
+
await agent.whenIdle();
|
|
347
|
+
assert.equal((driver.pendingSteerMessages as unknown[]).length, 0, '下一回合首请求消费注入');
|
|
348
|
+
});
|
|
349
|
+
|
|
350
|
+
it('HC5b. 运行中 inject:并入下一请求(不掐当前流),消费后清空', async () => {
|
|
351
|
+
const session = createFakeSession();
|
|
352
|
+
const scenario: Scenario = {
|
|
353
|
+
name: 'hc5b-running',
|
|
354
|
+
match: { promptIncludes: '运行中注入演练' },
|
|
355
|
+
chunking: { charsPerChunk: 0, delayMs: 0 },
|
|
356
|
+
steps: [
|
|
357
|
+
{ type: 'text', text: '先读 missing.txt。\n' },
|
|
358
|
+
{ type: 'commands', commands: ['<tf-read path="missing.txt" id="r1"/>'] },
|
|
359
|
+
{ type: 'waitTools', count: 1, timeoutMs: 5000 },
|
|
360
|
+
{ type: 'text', text: '读完了。\n' },
|
|
361
|
+
{ type: 'commands', commands: ['<tf-final id="f1" summary="running-inject-done"/>'] },
|
|
362
|
+
{ type: 'finish', reason: 'stop' },
|
|
363
|
+
],
|
|
364
|
+
};
|
|
365
|
+
const model = createMockModel({ scenarios: [scenario], provider: 'mock-provider' });
|
|
366
|
+
let settled = false;
|
|
367
|
+
let agentRef: StreamLoopAgent | undefined;
|
|
368
|
+
const driver = new SingleStreamDriver({
|
|
369
|
+
stream: (options) => normalizeStreamShim(model.adapter.stream({ provider: options.provider, model: options.model, messages: options.messages, signal: options.signal })),
|
|
370
|
+
// 独立批不带 agent 的执行器(tf-read 对不存在文件返回错误结果,不碰 fs 会话解析)
|
|
371
|
+
executeTools: async (input: ToolBatchInputLike): Promise<ToolBatchResultLike> => {
|
|
372
|
+
const results = [];
|
|
373
|
+
for (const call of input.calls) {
|
|
374
|
+
const content = [{ type: 'text' as const, text: 'Error: file not found (fixture)' }];
|
|
375
|
+
results.push({ callId: call.id, result: { content, isError: true } });
|
|
376
|
+
}
|
|
377
|
+
return { results };
|
|
378
|
+
},
|
|
379
|
+
onToolSettled: () => {
|
|
380
|
+
model.notifyToolResult();
|
|
381
|
+
if (!settled && agentRef !== undefined) {
|
|
382
|
+
settled = true;
|
|
383
|
+
agentRef.inject({ role: 'user', content: [{ type: 'text', text: '审批策略已改为 never。' }], source: { kind: 'user-approval' } });
|
|
384
|
+
}
|
|
385
|
+
},
|
|
386
|
+
}, { provider: 'mock-provider', model: 'mock-model', streamIdleTimeoutMs: 30_000 });
|
|
387
|
+
const fakeSession = { id: 'hc5b-agent', header: { id: 'hc5b-agent' }, events: [] as Array<{ type: string; data: unknown }>, append(type: string, data: unknown) { fakeSession.events.push({ type, data }); } };
|
|
388
|
+
const agent = new StreamLoopAgent({ id: 'hc5b-agent', session: fakeSession, driver, modelSelection: { provider: 'mock-provider', model: 'mock-model' } });
|
|
389
|
+
agentRef = agent;
|
|
390
|
+
agent.followup({ role: 'user', content: [{ type: 'text', text: '运行中注入演练:读 missing.txt 后收尾。' }] });
|
|
391
|
+
assert.equal(agent.status, 'running');
|
|
392
|
+
await agent.whenIdle();
|
|
393
|
+
assert.equal(agent.status, 'idle');
|
|
394
|
+
assert.equal((driver.pendingSteerMessages as unknown[]).length, 0, '运行中注入在下一请求被消费');
|
|
395
|
+
const finals = driver.snapshot().records.filter((r) => r.kind === 'final');
|
|
396
|
+
assert.equal((finals.at(-1) as { summary?: string }).summary, 'running-inject-done', '注入不打断回合收敛');
|
|
397
|
+
});
|
|
398
|
+
|
|
399
|
+
it('HC5c. dispose 后 inject 拒绝(镜像 followup/steer 的 dispose 语义)', async () => {
|
|
400
|
+
const session = createFakeSession();
|
|
401
|
+
const model = createMockModel({
|
|
402
|
+
scenarios: [{
|
|
403
|
+
name: 'hc5c-unused',
|
|
404
|
+
match: { promptIncludes: '永不匹配' },
|
|
405
|
+
chunking: { charsPerChunk: 0, delayMs: 0 },
|
|
406
|
+
steps: [{ type: 'finish', reason: 'stop' }],
|
|
407
|
+
}],
|
|
408
|
+
provider: 'mock-provider',
|
|
409
|
+
});
|
|
410
|
+
const driver = new SingleStreamDriver({
|
|
411
|
+
stream: (options) => normalizeStreamShim(model.adapter.stream({ provider: options.provider, model: options.model, messages: options.messages, signal: options.signal })),
|
|
412
|
+
executeTools: createHostLikeTools(session),
|
|
413
|
+
}, { provider: 'mock-provider', model: 'mock-model', streamIdleTimeoutMs: 30_000 });
|
|
414
|
+
const agent = new StreamLoopAgent({ id: 'hc5c-agent', session, driver, modelSelection: { provider: 'mock-provider', model: 'mock-model' } });
|
|
415
|
+
await agent.dispose();
|
|
416
|
+
assert.throws(() => agent.inject({ role: 'user', content: [{ type: 'text', text: 'late' }] }), /inject after dispose/);
|
|
417
|
+
});
|
|
418
|
+
});
|
|
@@ -348,12 +348,13 @@ test('DSML 包装行:malformed 上报并丢弃,不进 prose(真机形态
|
|
|
348
348
|
assert.equal(text, '\n\n\n', 'DSML 标签本身不得作为 prose 透传(标签间空白换行保留)');
|
|
349
349
|
const malformed = events.filter((e) => e.type === 'malformed').map((e) => e as { reason: string });
|
|
350
350
|
assert.ok(malformed.some((m) => m.reason === 'dsml-wrapper'), '包装行应按 dsml-wrapper 上报');
|
|
351
|
-
// invoke + 配对闭合 →
|
|
351
|
+
// invoke + 配对闭合 → 命令不丢。v0.3.2 起全部 invoke 统一走块缓冲(含内联属性形态),
|
|
352
|
+
// 正文约定与 parameter 语义一致:剥首尾各一个换行(内容本身不变)。
|
|
352
353
|
const cmds = commandsOf(events);
|
|
353
354
|
assert.equal(cmds.length, 1);
|
|
354
355
|
assert.equal(cmds[0].name, 'tf-plan');
|
|
355
356
|
assert.equal(cmds[0].id, 'p1');
|
|
356
|
-
assert.equal(cmds[0].body, '
|
|
357
|
+
assert.equal(cmds[0].body, '- [a1] 验收项');
|
|
357
358
|
});
|
|
358
359
|
|
|
359
360
|
test('DSML invoke 自闭合:改写回 tf-* 命令(属性透传)', () => {
|