dsh-session-webhook 0.0.0-stage → 0.2.0

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.
@@ -0,0 +1,1322 @@
1
+ /**
2
+ * Offline verification for the Host half.
3
+ *
4
+ * Runs the real `apply()` against a stub Cordis context: registration, the
5
+ * token contract, all six target states, idempotency, rate limiting, caps, and
6
+ * the management RPC. No dsh process, no restart, no network.
7
+ *
8
+ * v2 追加覆盖:三层 config 视图(yaml/settings/effective)、settings.json 持久化与
9
+ * 「保存即生效」、命名入口与多 urlFile(含重启自愈)、createdBy 归属、三个 agent 工具
10
+ * (参数/输出 schema/撤销权限/会话隔离)。
11
+ *
12
+ * node scripts/verify-host.mjs
13
+ */
14
+ import assert from 'node:assert/strict';
15
+ import { mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises';
16
+ import { tmpdir } from 'node:os';
17
+ import { join } from 'node:path';
18
+ import { Readable } from 'node:stream';
19
+ import { validateJsonSchemaValue } from '@deepseek-ai/dsh-tools';
20
+ import { apply } from '../lib/index.js';
21
+ import { buildMessage } from '../lib/deliver.js';
22
+ import { fail } from '../lib/errors.js';
23
+ import { withToolErrors } from '../lib/tools.js';
24
+ import { HookStore } from '../lib/store.js';
25
+
26
+ let passed = 0;
27
+ const failures = [];
28
+
29
+ async function test(name, fn) {
30
+ try {
31
+ await fn();
32
+ passed += 1;
33
+ console.log(` ok ${name}`);
34
+ } catch (error) {
35
+ failures.push({ name, error });
36
+ console.log(`FAIL ${name}\n ${error?.stack ?? error}`);
37
+ }
38
+ }
39
+
40
+ /**
41
+ * Minimal agent whose three inbox faces record what they received.
42
+ *
43
+ * `session.requestHeader()` 是投递路径真实会读的一个面(冷恢复后
44
+ * `installSessionRoute` 用它判断模型路由是否已有人选定)。桩必须带上它,否则
45
+ * 「已存会话被冷恢复」这条用例测的就不是投递路径,而是桩的缺字段。
46
+ */
47
+ function makeAgent(id, state) {
48
+ return {
49
+ id,
50
+ session: {
51
+ // 真实的 Session 带 id;投影查询(stateOf(session, 'agentPreset'))要用它,
52
+ // 缺了会让「按会话记录的 preset 恢复」这条路径在桩里永远读到空值。
53
+ id,
54
+ // 可以给一个带 agentPreset 的 header:用于反证「不得回落到 header」。
55
+ requestHeader: () => (state.headers?.[id] ?? undefined),
56
+ },
57
+ steer(message) { state.sent.push({ id, mode: 'steer', message }); },
58
+ followup(message) { state.sent.push({ id, mode: 'queue', message }); },
59
+ inject(message) { state.sent.push({ id, mode: 'passive', message }); },
60
+ };
61
+ }
62
+
63
+ /** Stub host context covering exactly the services the plugin injects. */
64
+ function makeHarness(options = {}) {
65
+ const state = {
66
+ routes: [],
67
+ fetchRoutes: [],
68
+ interceptors: [],
69
+ effects: [],
70
+ agents: new Map(),
71
+ sent: [],
72
+ resumed: [],
73
+ stored: new Set(options.stored ?? []),
74
+ archived: new Set(options.archived ?? []),
75
+ persistence: options.persistence !== false,
76
+ logs: [],
77
+ /** 被 apply 捕获的 agent 工具定义(tools 服务桩在 register 时写入)。 */
78
+ toolDefs: [],
79
+ /** 当前是否让 getOrigin() 抛错(模拟监听未绑定等宿主状态)。 */
80
+ originFails: options.originError !== undefined,
81
+ /** 冷恢复时 setup 回调被调用的次数(宿主要在发布 agent 之前 await 它)。 */
82
+ setupCalls: 0,
83
+ /** 冷恢复时 agentPresets.mount 收到的 preset id(undefined = 用 profile 默认)。 */
84
+ mountedPresets: [],
85
+ /** 冷恢复时 setup 收到的 agentCtx 对象(断言「挂组合」发生在哪个上下文里)。 */
86
+ setupContexts: [],
87
+ };
88
+ for (const [id, agent] of Object.entries(options.live ?? {})) state.agents.set(id, agent);
89
+
90
+ const logger = {
91
+ info: (line) => state.logs.push(line),
92
+ warn: (line) => state.logs.push(line),
93
+ };
94
+
95
+ const ctx = {
96
+ agents: {
97
+ get: (id) => state.agents.get(id),
98
+ resume: async ({ resumeSessionId, setup }) => {
99
+ state.resumed.push(resumeSessionId);
100
+ if (options.resumeError !== undefined) throw options.resumeError;
101
+ const agent = makeAgent(resumeSessionId, state);
102
+ // 宿主契约:setup 在铸造 agentCtx 之后、**发布 agent 之前**被 await。
103
+ // 所以桩里 setup 必须先跑完,agent 才进 state.agents —— 顺序反了就等于
104
+ // 没测到「组合在可见之前挂好」这个关键性质。
105
+ if (setup !== undefined) {
106
+ state.setupCalls += 1;
107
+ const agentCtx = { __agentCtxFor: resumeSessionId };
108
+ state.setupContexts.push(agentCtx);
109
+ await setup(agentCtx, agent);
110
+ }
111
+ state.agents.set(resumeSessionId, agent);
112
+ return { agent, dispose: async () => {} };
113
+ },
114
+ },
115
+ webServer: {
116
+ register: (route) => { state.routes.push(route); return () => {}; },
117
+ getOrigin: () => {
118
+ if (state.originFails) {
119
+ throw options.originError ?? new Error('webserver: origin read before the listener bound a port');
120
+ }
121
+ return 'http://127.0.0.1:3080';
122
+ },
123
+ },
124
+ connection: {
125
+ fetch: {
126
+ register: (route) => {
127
+ state.fetchRoutes.push(route);
128
+ return async () => {};
129
+ },
130
+ },
131
+ },
132
+ get: (key) => {
133
+ if (key === 'webServer') return ctx.webServer;
134
+ if (key === 'connection') return ctx.connection;
135
+ if (key === 'agents') return ctx.agents;
136
+ if (key === 'sessionPersistence') {
137
+ return state.persistence
138
+ ? { stat: async (id) => (state.stored.has(id) ? { header: { id } } : undefined) }
139
+ : undefined;
140
+ }
141
+ if (key === 'workspaceRegistry') {
142
+ return { get archivedSessionIds() { return [...state.archived]; } };
143
+ }
144
+ if (key === 'agentPresets') {
145
+ if (options.presets === false) return undefined;
146
+ return {
147
+ mount: async (agentCtx, id) => {
148
+ state.mountedPresets.push({ id, agentCtx });
149
+ if (options.mountError !== undefined) throw options.mountError;
150
+ return { id: id ?? '(default)' };
151
+ },
152
+ };
153
+ }
154
+ if (key === 'sessionProjections') {
155
+ if (options.projections === false) return undefined;
156
+ return {
157
+ stateOf: (session, key) => {
158
+ if (key !== 'agentPreset') return undefined;
159
+ // 用会话 id 查预先埋好的投影值,模拟「日志里记录的 preset」。
160
+ return (state.projectionsOf ?? options.projectionsOf)?.[session?.id];
161
+ },
162
+ };
163
+ }
164
+ if (key === 'tools') {
165
+ if (options.tools === false) return undefined;
166
+ return {
167
+ register: (definition) => { state.toolDefs.push(definition); return () => {}; },
168
+ };
169
+ }
170
+ return undefined;
171
+ },
172
+ effect: (fn, label) => { state.effects.push({ label, dispose: fn() }); },
173
+ logger: () => logger,
174
+ };
175
+ return { ctx, state, logger };
176
+ }
177
+
178
+ /** Fake IncomingMessage carrying an optional JSON body. */
179
+ function makeReq({ method = 'GET', url, headers = {}, body }) {
180
+ const chunk = body === undefined ? [] : [Buffer.from(body)];
181
+ const req = Readable.from(chunk);
182
+ req.method = method;
183
+ req.url = url;
184
+ req.headers = headers;
185
+ return req;
186
+ }
187
+
188
+ /** Fake ServerResponse capturing status, headers, and body. */
189
+ function makeRes() {
190
+ return {
191
+ statusCode: 0,
192
+ headers: {},
193
+ body: '',
194
+ writableEnded: false,
195
+ destroyed: false,
196
+ writeHead(status, headers) {
197
+ this.statusCode = status;
198
+ this.headers = headers ?? {};
199
+ return this;
200
+ },
201
+ end(text = '') {
202
+ this.body = text;
203
+ this.writableEnded = true;
204
+ return this;
205
+ },
206
+ };
207
+ }
208
+
209
+ /** Drive one HTTP request through the registered prefix route. */
210
+ async function http(state, { method, path, body, headers = {} }) {
211
+ const route = state.routes.find((entry) => entry.kind === 'prefix');
212
+ assert.ok(route, 'prefix route registered');
213
+ const res = makeRes();
214
+ await route.handler(makeReq({
215
+ method,
216
+ url: path,
217
+ body,
218
+ headers: body === undefined ? headers : { 'content-type': 'application/json', ...headers },
219
+ }), res);
220
+ let json;
221
+ try {
222
+ json = JSON.parse(res.body);
223
+ } catch {
224
+ json = undefined;
225
+ }
226
+ return { status: res.statusCode, json, res };
227
+ }
228
+
229
+ /** Call one management method through the registered Fetch route. */
230
+ async function rpc(state, method, payload) {
231
+ const route = state.fetchRoutes[0];
232
+ assert.ok(route, 'management fetch route registered');
233
+ assert.equal(route.path, '/api/session-inject-rpc');
234
+ const response = await route.fetch(new Request('http://localhost/api/session-inject-rpc', {
235
+ method: 'POST',
236
+ headers: { 'content-type': 'application/json' },
237
+ body: JSON.stringify({
238
+ type: 'client-request', rpcId: 'rpc-1',
239
+ method: 'session-inject-rpc', payload: { method, payload },
240
+ }),
241
+ }));
242
+ const body = await response.json();
243
+ assert.equal(body.type, 'server-response');
244
+ assert.equal(body.rpcId, 'rpc-1');
245
+ return body.result;
246
+ }
247
+
248
+
249
+ /** 取一个被 apply 捕获的 agent 工具定义。 */
250
+ function toolDef(state, name) {
251
+ const definition = state.toolDefs.find((entry) => entry.name === name);
252
+ assert.ok(definition, `工具 ${name} 已经注册`);
253
+ return definition;
254
+ }
255
+
256
+ /**
257
+ * 以某个会话的身份调用工具(工具没有 sessionId 参数,session 只来自 exec.agent.id)。
258
+ * @param state harness 状态。
259
+ * @param name 工具名。
260
+ * @param args 工具入参。
261
+ * @param sessionId 调用方会话 id。
262
+ */
263
+ async function callTool(state, name, args, sessionId = 's1') {
264
+ return toolDef(state, name).execute(args, { agent: { id: sessionId } });
265
+ }
266
+
267
+ /**
268
+ * 断言工具返回值满足它自己声明的 output.schema(运行时会做同一校验),
269
+ * 并确认 render 产出非空文本。
270
+ * @param definition defineTool 定义。
271
+ * @param args 调用入参。
272
+ * @param value 工具返回值。
273
+ */
274
+ function assertToolOutput(definition, args, value) {
275
+ const detached = JSON.parse(JSON.stringify(value));
276
+ const violations = validateJsonSchemaValue(definition.output.schema, detached, 'value');
277
+ assert.deepEqual(violations, [], `${definition.name} 输出不符合 output.schema:${violations.join('; ')}`);
278
+ const content = definition.output.render(args, value);
279
+ assert.ok(Array.isArray(content) && content.length > 0, 'render 必须返回内容块');
280
+ assert.equal(typeof content[0].text, 'string');
281
+ assert.ok(content[0].text.length > 0, 'render 文本不能为空');
282
+ }
283
+
284
+ /** 列目录;不存在时返回空数组。 */
285
+ async function listDir(path) {
286
+ try {
287
+ return (await readdir(path)).sort();
288
+ } catch (error) {
289
+ if (error?.code === 'ENOENT') return [];
290
+ throw error;
291
+ }
292
+ }
293
+
294
+ /** 从注册表文档里读某个端点的明文 token(测试要断言「tool result 不含 token」)。 */
295
+ async function tokenOf(state, hookId) {
296
+ const document = JSON.parse(await readFile(state.storeFile, 'utf8'));
297
+ const hook = document.hooks.find((entry) => entry.id === hookId);
298
+ assert.ok(hook, `注册表里应该有端点 ${hookId}`);
299
+ return hook.token;
300
+ }
301
+
302
+ /**
303
+ * 起一个独立数据目录的 harness 并 apply(每个用例的 urlFile/settings/store 互不污染)。
304
+ * @param directory 本次运行的临时根目录。
305
+ * @param name 子目录名(也用来区分 storeFile)。
306
+ * @param options 透传给 makeHarness 的桩选项;`config` 覆盖默认配置。
307
+ */
308
+ async function startHarness(directory, name, options = {}) {
309
+ const dir = join(directory, name);
310
+ const storeFile = join(dir, 'hooks.json');
311
+ const { ctx, state } = makeHarness(options);
312
+ const defaults = {
313
+ basePath: '/api/session-inject',
314
+ maxBodyBytes: 4096,
315
+ maxTextBytes: 1024,
316
+ ratePerMinute: 3,
317
+ };
318
+ await apply(ctx, { ...defaults, ...(options.config ?? {}), storeFile });
319
+ state.dir = dir;
320
+ state.storeFile = storeFile;
321
+ return { ctx, state, dir };
322
+ }
323
+
324
+ async function main() {
325
+ const directory = await mkdtemp(join(tmpdir(), 'dsh-session-webhook-'));
326
+ const storeFile = join(directory, 'hooks.json');
327
+ const config = {
328
+ basePath: '/api/session-inject',
329
+ maxBodyBytes: 4096,
330
+ maxTextBytes: 1024,
331
+ ratePerMinute: 3,
332
+ storeFile,
333
+ };
334
+
335
+ try {
336
+ const live = { s1: makeAgent('s1', { sent: [] }) };
337
+ const { ctx, state } = makeHarness({ live, stored: ['s2', 's3'], archived: ['s3'] });
338
+ // Re-create the live agent against the harness state so deliveries record.
339
+ state.agents.set('s1', makeAgent('s1', state));
340
+
341
+ await test('apply registers the delivery route and the management channel', async () => {
342
+ await apply(ctx, config);
343
+ assert.equal(state.routes.length, 1);
344
+ assert.deepEqual({ kind: state.routes[0].kind, path: state.routes[0].path },
345
+ { kind: 'prefix', path: '/api/session-inject' });
346
+ const management = state.fetchRoutes[0];
347
+ assert.ok(management, 'management fetch route registered');
348
+ assert.equal(management.path, '/api/session-inject-rpc');
349
+ assert.deepEqual(management.methods, ['POST']);
350
+ assert.equal(management.requestBody, 'buffered');
351
+ });
352
+
353
+ await test('capability table is constant and lists no stored state', async () => {
354
+ const first = await http(state, { method: 'GET', path: '/api/session-inject' });
355
+ assert.equal(first.status, 200);
356
+ assert.equal(first.json.service, 'session-inject');
357
+ assert.deepEqual(first.json.modes, ['steer', 'queue', 'passive']);
358
+ assert.equal(first.json.addressing, 'url-token');
359
+ const second = await http(state, { method: 'GET', path: '/api/session-inject/' });
360
+ assert.equal(second.res.statusCode, 200);
361
+ assert.equal(second.res.body, first.res.body);
362
+ });
363
+
364
+ let hookId;
365
+ let hookUrl;
366
+
367
+ await test('create binds a 32-byte token to the session', async () => {
368
+ const result = await rpc(state, 'hooks/create', {
369
+ sessionId: 's1', name: 'github-notify', tags: 'github, notify',
370
+ });
371
+ assert.equal(result.ok, true, JSON.stringify(result));
372
+ hookId = result.value.hook.id;
373
+ hookUrl = result.value.url;
374
+ assert.match(hookUrl, /^http:\/\/127\.0\.0\.1:3080\/api\/session-inject\/hooks\/si_[A-Za-z0-9_-]{43}$/);
375
+ assert.equal(result.value.hook.name, 'github-notify');
376
+ assert.deepEqual(result.value.hook.tags, ['github', 'notify']);
377
+ assert.equal(result.value.hook.maskedUrl.includes('…'), true);
378
+ assert.equal(JSON.stringify(result.value.hook).includes(result.value.url.split('/').pop()), false);
379
+ });
380
+
381
+ await test('capability stays identical after a hook exists (zero enumeration)', async () => {
382
+ const after = await http(state, { method: 'GET', path: '/api/session-inject' });
383
+ const probe = await http(state, { method: 'GET', path: '/api/session-inject/hooks' });
384
+ assert.equal(after.status, 200);
385
+ assert.equal(after.res.body.includes('github-notify'), false);
386
+ assert.equal(probe.status, 404);
387
+ });
388
+
389
+ await test('unknown token answers 404 without leaking', async () => {
390
+ const result = await http(state, {
391
+ method: 'POST',
392
+ path: '/api/session-inject/hooks/si_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
393
+ body: JSON.stringify({ text: 'hi' }),
394
+ });
395
+ assert.equal(result.status, 404);
396
+ assert.equal(result.json.error.code, 'unknown-endpoint');
397
+ });
398
+
399
+ await test('live delivery steers with the endpoint label', async () => {
400
+ const path = new URL(hookUrl).pathname;
401
+ const result = await http(state, {
402
+ method: 'POST', path, body: JSON.stringify({ text: '有 3 条新通知待处理', source: 'github-notify' }),
403
+ });
404
+ assert.equal(result.status, 202, JSON.stringify(result.json));
405
+ assert.equal(result.json.ok, true);
406
+ assert.equal(typeof result.json.deliveryId, 'string');
407
+ await new Promise((resolve) => setTimeout(resolve, 10));
408
+ assert.equal(state.sent.length, 1);
409
+ assert.equal(state.sent[0].mode, 'steer');
410
+ const text = state.sent[0].message.content[0].text;
411
+ assert.equal(text, '[webhook: github-notify]\n有 3 条新通知待处理');
412
+ });
413
+
414
+ await test('the message source marks an external webhook, never the user', async () => {
415
+ const sent = state.sent[0].message;
416
+ assert.equal(sent.role, 'user');
417
+ assert.equal(sent.source.kind, 'webhook');
418
+ assert.notEqual(sent.source.kind, 'user');
419
+ assert.equal(sent.source.provider, 'session-inject');
420
+ assert.equal(sent.source.form, 'notice');
421
+ assert.equal(typeof sent.source.summary, 'string');
422
+ assert.equal(sent.source.summary, 'github-notify: 有 3 条新通知待处理');
423
+ assert.equal(sent.source.ruleId, hookId);
424
+ assert.equal(sent.source.source, hookId);
425
+ assert.match(sent.source.deliveryId, /^dl_/);
426
+ });
427
+
428
+ await test('a long first line keeps the notice summary inside the 120-char bound', async () => {
429
+ const message = buildMessage(
430
+ { id: 'wh_long', name: 'longtext' },
431
+ `第一行${'很长'.repeat(200)}\n第二行不应进摘要`,
432
+ 'local-curl',
433
+ 'dl_long',
434
+ );
435
+ assert.equal(message.source.kind, 'webhook');
436
+ assert.ok(message.source.summary.length <= 120, `summary too long: ${message.source.summary.length}`);
437
+ assert.ok(message.source.summary.endsWith('…'), message.source.summary);
438
+ assert.equal(message.source.summary.includes('第二行'), false);
439
+ assert.equal(message.content[0].text.includes('第二行'), true, 'the body keeps every line');
440
+ });
441
+
442
+ await test('GET one endpoint describes itself without the token', async () => {
443
+ const result = await http(state, { method: 'GET', path: new URL(hookUrl).pathname });
444
+ assert.equal(result.status, 200);
445
+ assert.equal(result.json.endpoint.name, 'github-notify');
446
+ assert.equal(result.json.session.archived, false);
447
+ assert.equal(JSON.stringify(result.json).includes('si_'), false);
448
+ });
449
+
450
+ await test('idempotencyKey returns the same delivery and adds no message', async () => {
451
+ const path = new URL(hookUrl).pathname;
452
+ const body = JSON.stringify({ text: 'dup', idempotencyKey: 'k-1' });
453
+ const first = await http(state, { method: 'POST', path, body });
454
+ const second = await http(state, { method: 'POST', path, body });
455
+ assert.equal(first.status, 202);
456
+ assert.equal(second.status, 202);
457
+ assert.equal(second.json.deliveryId, first.json.deliveryId);
458
+ assert.equal(second.json.duplicate, true);
459
+ await new Promise((resolve) => setTimeout(resolve, 10));
460
+ assert.equal(state.sent.filter((entry) => entry.message.content[0].text.endsWith('dup')).length, 1);
461
+ });
462
+
463
+ await test('disable answers 403 and re-enable restores delivery', async () => {
464
+ const path = new URL(hookUrl).pathname;
465
+ const off = await rpc(state, 'hooks/update', { hookId, enabled: false });
466
+ assert.equal(off.ok, true);
467
+ const denied = await http(state, { method: 'POST', path, body: JSON.stringify({ text: 'x' }) });
468
+ assert.equal(denied.status, 403);
469
+ assert.equal(denied.json.error.code, 'endpoint-disabled');
470
+ const on = await rpc(state, 'hooks/update', { hookId, enabled: true });
471
+ assert.equal(on.value.hook.enabled, true);
472
+ });
473
+
474
+ await test('a second endpoint in the same session is independent', async () => {
475
+ const second = await rpc(state, 'hooks/create', { sessionId: 's1', name: 'gitlab-ci', defaultMode: 'queue' });
476
+ assert.equal(second.ok, true);
477
+ const list = await rpc(state, 'hooks/list', { sessionId: 's1' });
478
+ assert.deepEqual(list.value.hooks.map((hook) => hook.name).sort(), ['github-notify', 'gitlab-ci']);
479
+ const path = new URL(second.value.url).pathname;
480
+ await http(state, { method: 'POST', path, body: JSON.stringify({ text: 'build failed' }) });
481
+ await new Promise((resolve) => setTimeout(resolve, 10));
482
+ const queued = state.sent.filter((entry) => entry.message.content[0].text.includes('build failed'));
483
+ assert.equal(queued.length, 1);
484
+ assert.equal(queued[0].mode, 'queue');
485
+ });
486
+
487
+ await test('duplicate names inside one session are rejected', async () => {
488
+ const result = await rpc(state, 'hooks/create', { sessionId: 's1', name: 'github-notify' });
489
+ assert.equal(result.ok, false);
490
+ assert.equal(result.error.code, 'name-taken');
491
+ assert.match(result.error.message, /当前会话已有名为「github-notify」的端点/);
492
+ });
493
+
494
+ await test('passive against a stored session is refused instead of silently parked', async () => {
495
+ const created = await rpc(state, 'hooks/create', { sessionId: 's2', name: 'ctx-only', defaultMode: 'passive' });
496
+ assert.equal(created.ok, true, JSON.stringify(created));
497
+ const path = new URL(created.value.url).pathname;
498
+ const result = await http(state, { method: 'POST', path, body: JSON.stringify({ text: 'hello' }) });
499
+ assert.equal(result.status, 400);
500
+ assert.equal(result.json.error.code, 'passive-requires-live');
501
+ assert.deepEqual(state.resumed, []);
502
+ });
503
+
504
+ await test('cold resume mounts the preset recorded in the Session projection', async () => {
505
+ // 会话日志里记着这个会话跑的是 preset-standard;冷恢复必须把它重新挂上,
506
+ // 否则目标会话会用残缺组合继续跑(工具 78→50、丢 compaction)。
507
+ const harness = makeHarness({
508
+ stored: ['s-preset'],
509
+ projectionsOf: { 's-preset': 'preset-standard' },
510
+ });
511
+ await apply(harness.ctx, { ...config, storeFile: join(directory, 'hooks-preset.json') });
512
+ const created = await rpc(harness.state, 'hooks/create', { sessionId: 's-preset', name: 'cold' });
513
+ assert.equal(created.ok, true, JSON.stringify(created));
514
+ const path = new URL(created.value.url).pathname;
515
+ const result = await http(harness.state, {
516
+ method: 'POST', path: `${path}?wait=1`, body: JSON.stringify({ text: 'wake' }),
517
+ });
518
+ assert.equal(result.status, 200, JSON.stringify(result.json));
519
+ assert.equal(result.json.resumed, true);
520
+ // 1) setup 跑了,且发生在「agent 发布之前」(桩里 setup 早于 state.agents.set)
521
+ assert.equal(harness.state.setupCalls, 1, 'setup 必须被调用一次');
522
+ // 2) 挂的是投影里记录的 preset,不是 header、也不是默认值
523
+ assert.equal(harness.state.mountedPresets.length, 1);
524
+ assert.equal(harness.state.mountedPresets[0].id, 'preset-standard');
525
+ // 3) 挂组合用的是 agentCtx(宿主铸造给这次恢复的那个),不是随便一个 ctx
526
+ assert.equal(harness.state.setupContexts[0], harness.state.mountedPresets[0].agentCtx);
527
+ });
528
+
529
+ await test('cold resume with no recorded preset falls back to the registry default', async () => {
530
+ // 投影为空(创建时没记 preset)→ 传 undefined 给 mount,由注册表用 profile 默认。
531
+ // 注意:这里**不能**回头去读 header —— 那是创建时事实,会话可能已换过 preset。
532
+ const harness = makeHarness({ stored: ['s-nopreset'] });
533
+ await apply(harness.ctx, { ...config, storeFile: join(directory, 'hooks-nopreset.json') });
534
+ const created = await rpc(harness.state, 'hooks/create', { sessionId: 's-nopreset', name: 'cold2' });
535
+ assert.equal(created.ok, true, JSON.stringify(created));
536
+ const path = new URL(created.value.url).pathname;
537
+ const result = await http(harness.state, {
538
+ method: 'POST', path: `${path}?wait=1`, body: JSON.stringify({ text: 'wake' }),
539
+ });
540
+ assert.equal(result.status, 200, JSON.stringify(result.json));
541
+ assert.equal(harness.state.mountedPresets.length, 1);
542
+ assert.equal(harness.state.mountedPresets[0].id, undefined);
543
+ });
544
+
545
+ await test('cold resume never falls back to the header when the projection is empty', async () => {
546
+ // 证据文档 3.2 ① 的反证。关键在于**投影为空、header 有值**这个组合:
547
+ // · 正确实现(只读投影)→ 传 undefined,交给注册表用 profile 默认;
548
+ // · 错误实现(`stateOf() ?? header`)→ 传 header 的旧值,静默挂错组合。
549
+ // 若把两边都设成有值,`??` 永远不触发,测试就没有牙。
550
+ const harness = makeHarness({ stored: ['s-swapped'] });
551
+ harness.state.headers = { 's-swapped': { agentPreset: 'preset-OLD' } };
552
+ harness.state.projectionsOf = {}; // 投影为空(会话没记过 preset)
553
+ await apply(harness.ctx, { ...config, storeFile: join(directory, 'hooks-swapped.json') });
554
+ const created = await rpc(harness.state, 'hooks/create', { sessionId: 's-swapped', name: 'cold5' });
555
+ assert.equal(created.ok, true, JSON.stringify(created));
556
+ const path = new URL(created.value.url).pathname;
557
+ const result = await http(harness.state, {
558
+ method: 'POST', path: `${path}?wait=1`, body: JSON.stringify({ text: 'wake' }),
559
+ });
560
+ assert.equal(result.status, 200, JSON.stringify(result.json));
561
+ assert.equal(harness.state.mountedPresets.length, 1);
562
+ assert.equal(harness.state.mountedPresets[0].id, undefined,
563
+ '投影为空时必须交给注册表默认值,绝不能回落到 header(header 是创建时事实,'
564
+ + '会话可能在 blank 期换过 preset,回落会静默挂错组合)');
565
+ });
566
+
567
+ await test('cold resume without agentPresets fails loud instead of returning a degraded agent', async () => {
568
+ // 反例(证据文档第 4 节第 4 条):profile 没组合 preset 注册表时,冷恢复必须显式失败。
569
+ // 静默返回一个无 preset 的 agent 就是事故成因:它拿到残缺工具集,且自己修不好。
570
+ const harness = makeHarness({ stored: ['s-no-registry'], presets: false });
571
+ await apply(harness.ctx, { ...config, storeFile: join(directory, 'hooks-noreg.json') });
572
+ const created = await rpc(harness.state, 'hooks/create', { sessionId: 's-no-registry', name: 'cold3' });
573
+ assert.equal(created.ok, true, JSON.stringify(created));
574
+ const path = new URL(created.value.url).pathname;
575
+ const result = await http(harness.state, {
576
+ method: 'POST', path: `${path}?wait=1`, body: JSON.stringify({ text: 'wake' }),
577
+ });
578
+ assert.equal(result.status, 409, JSON.stringify(result.json));
579
+ assert.equal(result.json.error.code, 'preset-unavailable');
580
+ // 关键:agent 没有被发布,也没有任何投递落到一个「半成品」agent 上
581
+ assert.equal(harness.state.agents.has('s-no-registry'), false);
582
+ assert.equal(harness.state.sent.length, 0);
583
+ });
584
+
585
+ await test('cold resume without sessionProjections fails loud too', async () => {
586
+ const harness = makeHarness({ stored: ['s-no-proj'], projections: false });
587
+ await apply(harness.ctx, { ...config, storeFile: join(directory, 'hooks-noproj.json') });
588
+ const created = await rpc(harness.state, 'hooks/create', { sessionId: 's-no-proj', name: 'cold4' });
589
+ assert.equal(created.ok, true, JSON.stringify(created));
590
+ const path = new URL(created.value.url).pathname;
591
+ const result = await http(harness.state, {
592
+ method: 'POST', path: `${path}?wait=1`, body: JSON.stringify({ text: 'wake' }),
593
+ });
594
+ assert.equal(result.status, 409, JSON.stringify(result.json));
595
+ assert.equal(result.json.error.code, 'preset-unavailable');
596
+ assert.equal(harness.state.sent.length, 0);
597
+ });
598
+
599
+ await test('live sessions never touch the preset registry (no cold resume)', async () => {
600
+ // 只给活会话投递的场景不该依赖 preset:这条守住「服务不进 inject」的决定。
601
+ const liveAgent = makeAgent('s-live', { sent: [] });
602
+ const harness = makeHarness({ live: { 's-live': liveAgent }, presets: false });
603
+ await apply(harness.ctx, { ...config, storeFile: join(directory, 'hooks-live.json') });
604
+ const created = await rpc(harness.state, 'hooks/create', { sessionId: 's-live', name: 'live' });
605
+ assert.equal(created.ok, true, JSON.stringify(created));
606
+ const path = new URL(created.value.url).pathname;
607
+ const result = await http(harness.state, {
608
+ method: 'POST', path, body: JSON.stringify({ text: 'ping' }),
609
+ });
610
+ assert.equal(result.status, 202, JSON.stringify(result.json));
611
+ assert.equal(harness.state.setupCalls, 0);
612
+ assert.equal(harness.state.mountedPresets.length, 0);
613
+ });
614
+
615
+ await test('stored session is cold-resumed and reports resumed:true on ?wait=1', async () => {
616
+ const created = await rpc(state, 'hooks/create', { sessionId: 's2', name: 'resume-me' });
617
+ const path = new URL(created.value.url).pathname;
618
+ const result = await http(state, {
619
+ method: 'POST', path: `${path}?wait=1`, body: JSON.stringify({ text: 'wake up' }),
620
+ });
621
+ assert.equal(result.status, 200, JSON.stringify(result.json));
622
+ assert.equal(result.json.resumed, true);
623
+ assert.deepEqual(state.resumed, ['s2']);
624
+ const delivered = state.sent.filter((entry) => entry.message.content[0].text.includes('wake up'));
625
+ assert.equal(delivered.length, 1);
626
+ });
627
+
628
+ await test('archived session answers 409 and never resumes', async () => {
629
+ const created = await rpc(state, 'hooks/create', { sessionId: 's3', name: 'archived' });
630
+ const path = new URL(created.value.url).pathname;
631
+ const before = state.resumed.length;
632
+ const result = await http(state, { method: 'POST', path, body: JSON.stringify({ text: 'x' }) });
633
+ assert.equal(result.status, 409);
634
+ assert.equal(result.json.error.code, 'session-archived');
635
+ assert.equal(state.resumed.length, before);
636
+ });
637
+
638
+ await test('a deleted session answers 404 unknown-session', async () => {
639
+ const created = await rpc(state, 'hooks/create', { sessionId: 's2', name: 'gone' });
640
+ const path = new URL(created.value.url).pathname;
641
+ state.stored.delete('s2');
642
+ state.agents.delete('s2');
643
+ const result = await http(state, { method: 'POST', path, body: JSON.stringify({ text: 'x' }) });
644
+ assert.equal(result.status, 404);
645
+ assert.equal(result.json.error.code, 'unknown-session');
646
+ state.stored.add('s2');
647
+ });
648
+
649
+ await test('a resume rejection maps to a typed 409', async () => {
650
+ const broken = makeHarness({ stored: ['s9'], resumeError: Object.assign(new Error('already owned by another process'), { name: 'SessionAlreadyOwnedError' }) });
651
+ await apply(broken.ctx, { ...config, storeFile: join(directory, 'hooks-busy.json') });
652
+ const created = await rpc(broken.state, 'hooks/create', { sessionId: 's9', name: 'busy' });
653
+ const path = new URL(created.value.url).pathname;
654
+ const result = await http(broken.state, { method: 'POST', path: `${path}?wait=1`, body: JSON.stringify({ text: 'x' }) });
655
+ assert.equal(result.status, 409);
656
+ assert.equal(result.json.error.code, 'session-busy');
657
+ });
658
+
659
+ await test('rate limit answers 429 with a retry hint', async () => {
660
+ const created = await rpc(state, 'hooks/create', { sessionId: 's1', name: 'burst' });
661
+ const path = new URL(created.value.url).pathname;
662
+ const codes = [];
663
+ for (let index = 0; index < 4; index += 1) {
664
+ const result = await http(state, { method: 'POST', path, body: JSON.stringify({ text: `n${index}` }) });
665
+ codes.push(result.status);
666
+ }
667
+ assert.deepEqual(codes.slice(0, 3), [202, 202, 202]);
668
+ assert.equal(codes[3], 429);
669
+ });
670
+
671
+ await test('oversized text and body are refused', async () => {
672
+ const created = await rpc(state, 'hooks/create', { sessionId: 's1', name: 'big' });
673
+ const path = new URL(created.value.url).pathname;
674
+ const longText = await http(state, {
675
+ method: 'POST', path, body: JSON.stringify({ text: 'x'.repeat(2048) }),
676
+ });
677
+ assert.equal(longText.status, 413);
678
+ const hugeBody = await http(state, {
679
+ method: 'POST', path, body: JSON.stringify({ text: 'ok', pad: 'x'.repeat(8192) }),
680
+ });
681
+ assert.equal(hugeBody.status, 413);
682
+ });
683
+
684
+ await test('non-object and non-JSON bodies are refused', async () => {
685
+ const created = await rpc(state, 'hooks/create', { sessionId: 's1', name: 'shape' });
686
+ const path = new URL(created.value.url).pathname;
687
+ const arrayBody = await http(state, { method: 'POST', path, body: '[]' });
688
+ assert.equal(arrayBody.status, 400);
689
+ assert.equal(arrayBody.json.error.message, '请求体必须是 JSON 对象');
690
+ const notJson = await http(state, {
691
+ method: 'POST', path, headers: { 'content-type': 'text/plain' }, body: 'x',
692
+ });
693
+ assert.equal(notJson.status, 415);
694
+ assert.match(notJson.json.error.message, /content-type 必须是 application\/json/);
695
+ });
696
+
697
+ await test('reveal returns the stored URL and revoke kills it', async () => {
698
+ const created = await rpc(state, 'hooks/create', { sessionId: 's1', name: 'temp' });
699
+ const revealed = await rpc(state, 'hooks/reveal', { hookId: created.value.hook.id });
700
+ assert.equal(revealed.value.url, created.value.url);
701
+ const revoked = await rpc(state, 'hooks/revoke', { hookId: created.value.hook.id });
702
+ assert.equal(revoked.value.revoked, true);
703
+ const after = await http(state, { method: 'GET', path: new URL(created.value.url).pathname });
704
+ assert.equal(after.status, 404);
705
+ const revealAfter = await rpc(state, 'hooks/reveal', { hookId: created.value.hook.id });
706
+ assert.equal(revealAfter.ok, false);
707
+ assert.equal(revealAfter.error.code, 'unknown-endpoint');
708
+ });
709
+
710
+ await test('unknown management method answers a typed failure', async () => {
711
+ const result = await rpc(state, 'hooks/nope', {});
712
+ assert.equal(result.ok, false);
713
+ assert.equal(result.error.code, 'unknown-method');
714
+ });
715
+
716
+ await test('the registry survives a reload and keeps mode 600', async () => {
717
+ const reloaded = new HookStore({ file: storeFile });
718
+ await reloaded.load();
719
+ const names = reloaded.list('s1').map((hook) => hook.name).sort();
720
+ assert.ok(names.includes('github-notify'));
721
+ assert.ok(names.includes('gitlab-ci'));
722
+ const info = await stat(storeFile);
723
+ assert.equal((info.mode & 0o777).toString(8), '600');
724
+ const document = JSON.parse(await readFile(storeFile, 'utf8'));
725
+ assert.equal(document.version, 1);
726
+ });
727
+
728
+ await test('malformed store fails loudly instead of starting empty', async () => {
729
+ const brokenFile = join(directory, 'broken.json');
730
+ const { writeFile } = await import('node:fs/promises');
731
+ await writeFile(brokenFile, '{"version":99}');
732
+ const store = new HookStore({ file: brokenFile });
733
+ await assert.rejects(async () => store.load(), /形状不受支持/);
734
+ });
735
+
736
+ await test('apply refuses to start without the required services', async () => {
737
+ for (const missing of ['webServer', 'connection', 'agents']) {
738
+ const { ctx: broken } = makeHarness({});
739
+ delete broken[missing];
740
+ await assert.rejects(async () => apply(broken, config), TypeError);
741
+ }
742
+ });
743
+
744
+ await test('the capability route rejects non-GET methods', async () => {
745
+ const result = await http(state, { method: 'POST', path: '/api/session-inject', body: '{}' });
746
+ assert.equal(result.status, 405);
747
+ assert.equal(result.res.headers.allow, 'GET');
748
+ assert.equal(result.json.error.message, '方法不允许');
749
+ });
750
+
751
+ // ── v2:命名入口 / settings.json 三层视图 / urlFile / createdBy / agent 工具 ──
752
+
753
+ await test('config/get 返回三层视图(yaml / settings / effective)', async () => {
754
+ const { state } = await startHarness(directory, 'cfg-get');
755
+ const result = await rpc(state, 'config/get', {});
756
+ assert.equal(result.ok, true, JSON.stringify(result));
757
+ const view = result.value;
758
+ assert.deepEqual(view.settings, {});
759
+ assert.equal('publicBaseUrls' in view.yaml, false);
760
+ assert.equal('defaultBase' in view.yaml, false);
761
+ assert.deepEqual(view.yaml.limits, { maxBodyBytes: 4096, maxTextBytes: 1024, ratePerMinute: 3 });
762
+ assert.equal(view.directOrigin, 'http://127.0.0.1:3080');
763
+ assert.equal('directError' in view, false);
764
+ assert.equal(view.basePath, '/api/session-inject');
765
+ assert.deepEqual(view.effective.publicBaseUrls, { direct: 'http://127.0.0.1:3080' });
766
+ assert.equal(view.effective.defaultBase, 'direct');
767
+ assert.deepEqual(view.effective.limits, { maxBodyBytes: 4096, maxTextBytes: 1024, ratePerMinute: 3 });
768
+ });
769
+
770
+ await test('config/set 保存 settings.json 并立即生效(入口 / 限额 / urlFile)', async () => {
771
+ const { state, dir } = await startHarness(directory, 'cfg-set');
772
+ state.agents.set('sc', makeAgent('sc', state));
773
+ const created = await rpc(state, 'hooks/create', { sessionId: 'sc', name: 'before' });
774
+ assert.equal(created.ok, true, JSON.stringify(created));
775
+ const hookId = created.value.hook.id;
776
+ const token = await tokenOf(state, hookId);
777
+ const before = await http(state, { method: 'GET', path: '/api/session-inject' });
778
+ assert.deepEqual(before.json.limits, { bodyBytes: 4096, textBytes: 1024, ratePerMinute: 3 });
779
+
780
+ const saved = await rpc(state, 'config/set', {
781
+ publicBaseUrls: { proxy: 'https://dsh.example/dsh/' },
782
+ defaultBase: 'proxy',
783
+ limits: { maxBodyBytes: 8192, maxTextBytes: 8, ratePerMinute: 100 },
784
+ });
785
+ assert.equal(saved.ok, true, JSON.stringify(saved));
786
+ assert.equal(saved.value.saved, true);
787
+ assert.deepEqual(saved.value.settings, {
788
+ publicBaseUrls: { proxy: 'https://dsh.example/dsh' },
789
+ defaultBase: 'proxy',
790
+ limits: { maxBodyBytes: 8192, maxTextBytes: 8, ratePerMinute: 100 },
791
+ });
792
+ assert.deepEqual(saved.value.yaml.limits, { maxBodyBytes: 4096, maxTextBytes: 1024, ratePerMinute: 3 });
793
+ assert.deepEqual(saved.value.effective.publicBaseUrls, {
794
+ direct: 'http://127.0.0.1:3080',
795
+ proxy: 'https://dsh.example/dsh',
796
+ });
797
+ assert.equal(saved.value.effective.defaultBase, 'proxy');
798
+
799
+ // settings.json 落盘(0600、version 1)
800
+ const settingsPath = join(dir, 'settings.json');
801
+ assert.equal(((await stat(settingsPath)).mode & 0o777).toString(8), '600');
802
+ const document = JSON.parse(await readFile(settingsPath, 'utf8'));
803
+ assert.equal(document.version, 1);
804
+ assert.equal(document.defaultBase, 'proxy');
805
+
806
+ // urlFile 立即按新入口重写:default 入口(proxy)用短名
807
+ const urlsDir = join(dir, 'urls');
808
+ assert.deepEqual(await listDir(urlsDir), [`${hookId}.direct.url`, `${hookId}.url`].sort());
809
+ assert.equal((await readFile(join(urlsDir, `${hookId}.url`), 'utf8')).trim(),
810
+ `https://dsh.example/dsh/api/session-inject/hooks/${token}`);
811
+ assert.equal((await readFile(join(urlsDir, `${hookId}.direct.url`), 'utf8')).trim(),
812
+ `http://127.0.0.1:3080/api/session-inject/hooks/${token}`);
813
+
814
+ // 新端点用新默认入口;reveal 也回新默认入口
815
+ const after = await rpc(state, 'hooks/create', { sessionId: 'sc', name: 'after' });
816
+ assert.equal(after.ok, true, JSON.stringify(after));
817
+ assert.match(after.value.url, /^https:\/\/dsh\.example\/dsh\/api\/session-inject\/hooks\/si_/);
818
+ assert.equal(after.value.defaultBase, 'proxy');
819
+ assert.deepEqual(Object.keys(after.value.urlFiles).sort(), ['direct', 'proxy']);
820
+ const revealed = await rpc(state, 'hooks/reveal', { hookId });
821
+ assert.equal(revealed.value.url, `https://dsh.example/dsh/api/session-inject/hooks/${token}`);
822
+
823
+ // 限额立即生效(投递 handler 已重建):text 上限降到 8 字节
824
+ const path = new URL(created.value.url).pathname;
825
+ const tooLong = await http(state, { method: 'POST', path, body: JSON.stringify({ text: 'x'.repeat(20) }) });
826
+ assert.equal(tooLong.status, 413);
827
+ const accepted = await http(state, { method: 'POST', path, body: JSON.stringify({ text: 'ok' }) });
828
+ assert.equal(accepted.status, 202, JSON.stringify(accepted.json));
829
+ const capability = await http(state, { method: 'GET', path: '/api/session-inject' });
830
+ assert.deepEqual(capability.json.limits, { bodyBytes: 8192, textBytes: 8, ratePerMinute: 100 });
831
+
832
+ // 再改一次限额(rate 1):新 handler 自带新限流器
833
+ const limited = await rpc(state, 'config/set', {
834
+ publicBaseUrls: { proxy: 'https://dsh.example/dsh' },
835
+ defaultBase: 'proxy',
836
+ limits: { maxBodyBytes: 8192, maxTextBytes: 8, ratePerMinute: 1 },
837
+ });
838
+ assert.equal(limited.ok, true, JSON.stringify(limited));
839
+ const first = await http(state, { method: 'POST', path, body: JSON.stringify({ text: 'ok' }) });
840
+ const second = await http(state, { method: 'POST', path, body: JSON.stringify({ text: 'ok' }) });
841
+ assert.equal(first.status, 202, JSON.stringify(first.json));
842
+ assert.equal(second.status, 429);
843
+ });
844
+
845
+ await test('config/set 拒绝非法输入并给出可映射的中文 code', async () => {
846
+ const { state, dir } = await startHarness(directory, 'cfg-invalid');
847
+ const cases = [
848
+ [{ publicBaseUrls: { PROXY: 'https://edge.example' } }, 'invalid-name'],
849
+ [{ publicBaseUrls: { proxy: 'https://edge.example?x=1' } }, 'invalid-url'],
850
+ [{ publicBaseUrls: { proxy: 'ftp://edge.example' } }, 'invalid-url'],
851
+ [{ publicBaseUrls: { proxy: 'https://edge.example' }, defaultBase: 'nope' }, 'unknown-base'],
852
+ [{ limits: { maxBodyBytes: 1, maxTextBytes: 1, ratePerMinute: 1 } }, 'invalid-limit'],
853
+ [{ limits: { maxBodyBytes: 4096, maxTextBytes: 8192, ratePerMinute: 1 } }, 'invalid-limit'],
854
+ [{ limits: { maxBodyBytes: 4096 } }, 'invalid-limit'],
855
+ ];
856
+ for (const [payload, code] of cases) {
857
+ const result = await rpc(state, 'config/set', payload);
858
+ assert.equal(result.ok, false, JSON.stringify(payload));
859
+ assert.equal(result.error.code, code, JSON.stringify({ payload, error: result.error }));
860
+ assert.equal(typeof result.error.message, 'string');
861
+ }
862
+ // 全部失败时不应该写出 settings.json(校验失败不落盘)
863
+ await assert.rejects(async () => stat(join(dir, 'settings.json')));
864
+ });
865
+
866
+ await test('direct origin 取不到:config/get 回 null+directError 不抛错,config/set 仍可保存', async () => {
867
+ const { state, dir } = await startHarness(directory, 'cfg-origin');
868
+ state.agents.set('so', makeAgent('so', state));
869
+ const created = await rpc(state, 'hooks/create', { sessionId: 'so', name: 'origin-probe' });
870
+ assert.equal(created.ok, true, JSON.stringify(created));
871
+ const hookId = created.value.hook.id;
872
+ const filesBefore = await listDir(join(dir, 'urls'));
873
+
874
+ state.originFails = true;
875
+ const view = await rpc(state, 'config/get', {});
876
+ assert.equal(view.ok, true, JSON.stringify(view));
877
+ assert.equal(view.value.directOrigin, null);
878
+ assert.match(view.value.directError, /origin/);
879
+ // 没有显式 direct 时,effective 里就无法包含 direct
880
+ assert.deepEqual(view.value.effective.publicBaseUrls, {});
881
+
882
+ const saved = await rpc(state, 'config/set', {
883
+ publicBaseUrls: {},
884
+ defaultBase: 'direct',
885
+ limits: { maxBodyBytes: 4096, maxTextBytes: 1024, ratePerMinute: 3 },
886
+ });
887
+ assert.equal(saved.ok, true, JSON.stringify(saved));
888
+ assert.equal(saved.value.saved, true);
889
+ assert.equal(saved.value.directOrigin, null);
890
+ // urlFile 保持原样(没写坏),只是没重写
891
+ assert.deepEqual(await listDir(join(dir, 'urls')), filesBefore);
892
+
893
+ // 需要 URL 的操作明确报错,绝不产出相对路径
894
+ const probe = await rpc(state, 'hooks/create', { sessionId: 'so', name: 'needs-origin' });
895
+ assert.equal(probe.ok, false);
896
+ assert.equal(probe.error.code, 'direct-origin-unavailable');
897
+ assert.equal((await rpc(state, 'hooks/reveal', { hookId })).error.code, 'direct-origin-unavailable');
898
+
899
+ // origin 恢复后同一端点照旧可用
900
+ state.originFails = false;
901
+ const back = await rpc(state, 'hooks/reveal', { hookId });
902
+ assert.equal(back.ok, true);
903
+ assert.match(back.value.url, /^http:\/\/127\.0\.0\.1:3080\/api\/session-inject\/hooks\/si_/);
904
+ });
905
+
906
+ await test('YAML 配置层非法 / origin 不可用时 apply 启动即失败(fail-loud)', async () => {
907
+ const badUrl = makeHarness({});
908
+ await assert.rejects(
909
+ apply(badUrl.ctx, {
910
+ ...config, storeFile: join(directory, 'fail-layer', 'hooks.json'),
911
+ publicBaseUrls: { edge: 'ftp://edge.example' },
912
+ }),
913
+ (error) => error?.code === 'invalid-url');
914
+ const badDefault = makeHarness({});
915
+ await assert.rejects(
916
+ apply(badDefault.ctx, {
917
+ ...config,
918
+ storeFile: join(directory, 'fail-default', 'hooks.json'),
919
+ publicBaseUrls: { edge: 'https://edge.example' },
920
+ defaultBase: 'missing',
921
+ }),
922
+ (error) => error?.code === 'unknown-base');
923
+ // 已有端点时必须重写 urlFile:origin 取不到就 fail-loud(空表时无需 origin,允许起来)
924
+ const seeded = await startHarness(directory, 'fail-origin');
925
+ seeded.state.agents.set('sf', makeAgent('sf', seeded.state));
926
+ const seededHook = await rpc(seeded.state, 'hooks/create', { sessionId: 'sf', name: 'seed' });
927
+ assert.equal(seededHook.ok, true, JSON.stringify(seededHook));
928
+ const noOrigin = makeHarness({ originError: new Error('webserver: origin read before the listener bound a port') });
929
+ await assert.rejects(
930
+ apply(noOrigin.ctx, { ...config, storeFile: join(directory, 'fail-origin', 'hooks.json') }),
931
+ (error) => error?.code === 'direct-origin-unavailable');
932
+ });
933
+
934
+ await test('urlFile:多入口文件名/内容/权限,重启按当前入口集合自愈', async () => {
935
+ const { state, dir } = await startHarness(directory, 'urlfile', {
936
+ config: { publicBaseUrls: { proxy: 'https://dsh.example/dsh' }, defaultBase: 'proxy' },
937
+ });
938
+ state.agents.set('su', makeAgent('su', state));
939
+ const created = await rpc(state, 'hooks/create', { sessionId: 'su', name: 'poller' });
940
+ assert.equal(created.ok, true, JSON.stringify(created));
941
+ const hookId = created.value.hook.id;
942
+ const token = await tokenOf(state, hookId);
943
+ const urlsDir = join(dir, 'urls');
944
+ assert.deepEqual(await listDir(urlsDir), [`${hookId}.direct.url`, `${hookId}.url`].sort());
945
+ assert.equal((await readFile(join(urlsDir, `${hookId}.url`), 'utf8')).trim(),
946
+ `https://dsh.example/dsh/api/session-inject/hooks/${token}`);
947
+ assert.equal((await readFile(join(urlsDir, `${hookId}.direct.url`), 'utf8')).trim(),
948
+ `http://127.0.0.1:3080/api/session-inject/hooks/${token}`);
949
+ assert.equal(((await stat(urlsDir)).mode & 0o777).toString(8), '700');
950
+ for (const name of await listDir(urlsDir)) {
951
+ assert.equal(((await stat(join(urlsDir, name))).mode & 0o777).toString(8), '600', `${name} 权限`);
952
+ }
953
+
954
+ // 陈旧文件:已删入口 + 已不存在端点 —— 下一次 apply 全量重写时清掉
955
+ await writeFile(join(urlsDir, `${hookId}.obsolete.url`), 'https://stale.example\n');
956
+ await writeFile(join(urlsDir, 'wh_gone.url'), 'https://stale.example\n');
957
+ const restarted = makeHarness({});
958
+ await apply(restarted.ctx, { ...config, storeFile: join(dir, 'hooks.json') });
959
+ assert.deepEqual(await listDir(urlsDir), [`${hookId}.url`]);
960
+ assert.equal((await readFile(join(urlsDir, `${hookId}.url`), 'utf8')).trim(),
961
+ `http://127.0.0.1:3080/api/session-inject/hooks/${token}`);
962
+ });
963
+
964
+ await test('UI 撤销端点会删除该端点的全部 urlFile', async () => {
965
+ const { state, dir } = await startHarness(directory, 'revoke-files', {
966
+ config: { publicBaseUrls: { proxy: 'https://dsh.example/dsh' }, defaultBase: 'proxy' },
967
+ });
968
+ state.agents.set('sr', makeAgent('sr', state));
969
+ const created = await rpc(state, 'hooks/create', { sessionId: 'sr', name: 'revoke-me' });
970
+ const hookId = created.value.hook.id;
971
+ assert.equal((await listDir(join(dir, 'urls'))).length, 2);
972
+ const revoked = await rpc(state, 'hooks/revoke', { hookId });
973
+ assert.equal(revoked.value.revoked, true);
974
+ assert.deepEqual(await listDir(join(dir, 'urls')), []);
975
+ });
976
+
977
+ await test('createdBy:UI 建 → ui、工具建 → agent、存量缺字段按 ui', async () => {
978
+ const { state } = await startHarness(directory, 'created-by');
979
+ state.agents.set('s1', makeAgent('s1', state));
980
+ const uiMade = await rpc(state, 'hooks/create', { sessionId: 's1', name: 'ui-made' });
981
+ assert.equal(uiMade.value.hook.createdBy, 'ui');
982
+ const agentMade = await callTool(state, 'session_webhook_create', { name: 'agent-made' });
983
+ assert.equal(agentMade.created, true);
984
+ const list = await rpc(state, 'hooks/list', { sessionId: 's1' });
985
+ const byName = Object.fromEntries(list.value.hooks.map((hook) => [hook.name, hook.createdBy]));
986
+ assert.deepEqual(byName, { 'ui-made': 'ui', 'agent-made': 'agent' });
987
+
988
+ // 存量记录没有 createdBy:load 时归一成 'ui',撤销权限判定不会误判成 agent
989
+ const legacyFile = join(directory, 'legacy', 'hooks.json');
990
+ await mkdir(join(directory, 'legacy'), { recursive: true });
991
+ await writeFile(legacyFile, JSON.stringify({
992
+ version: 1,
993
+ hooks: [{
994
+ id: 'wh_legacy', sessionId: 's1', name: 'old', tags: [],
995
+ token: `si_${'a'.repeat(43)}`, defaultMode: 'steer', enabled: true,
996
+ createdAt: '2026-01-01T00:00:00.000Z',
997
+ }],
998
+ }));
999
+ const reloaded = new HookStore({ file: legacyFile });
1000
+ await reloaded.load();
1001
+ assert.equal(reloaded.get('wh_legacy').createdBy, 'ui');
1002
+ });
1003
+
1004
+ await test('工具 create:只回 maskedUrl 与 urlFile 路径,完整 URL/token 不进结果', async () => {
1005
+ const { state } = await startHarness(directory, 'tool-create');
1006
+ state.agents.set('s1', makeAgent('s1', state));
1007
+ const definition = toolDef(state, 'session_webhook_create');
1008
+ const value = await callTool(state, 'session_webhook_create', {
1009
+ name: 'ci', tags: ['ci', 'build'], mode: 'queue',
1010
+ });
1011
+ assertToolOutput(definition, { name: 'ci' }, value);
1012
+ assert.equal(value.created, true);
1013
+ assert.equal(value.endpoint.sessionId, 's1');
1014
+ assert.equal(value.endpoint.name, 'ci');
1015
+ assert.equal(value.endpoint.mode, 'queue');
1016
+ assert.deepEqual(value.endpoint.tags, ['ci', 'build']);
1017
+ assert.equal(value.endpoint.enabled, true);
1018
+ assert.equal(value.defaultBase, 'direct');
1019
+ assert.ok(value.endpoint.maskedUrl.includes('…'));
1020
+ assert.deepEqual(Object.keys(value.urlFiles), ['direct']);
1021
+ const token = await tokenOf(state, value.endpoint.id);
1022
+ const serialized = JSON.stringify(value);
1023
+ assert.equal(serialized.includes(token), false, 'token 不能进 tool result');
1024
+ assert.equal(serialized.includes('http://'), false, '完整 URL 不能进 tool result');
1025
+ });
1026
+
1027
+ await test('工具 create:同名报 name-taken(带 id/maskedUrl),reuse:true 复用且不改配置', async () => {
1028
+ const { state } = await startHarness(directory, 'tool-reuse');
1029
+ state.agents.set('s1', makeAgent('s1', state));
1030
+ const first = await callTool(state, 'session_webhook_create', { name: 'dup' });
1031
+ await assert.rejects(
1032
+ callTool(state, 'session_webhook_create', { name: 'dup' }),
1033
+ (error) => {
1034
+ assert.equal(error.code, 'name-taken');
1035
+ assert.match(error.message, /^\[name-taken\] /);
1036
+ // details 不会进模型上下文,所以必须进 message 文本
1037
+ assert.ok(error.message.includes(first.endpoint.id), 'details.hookId 必须出现在 message 里');
1038
+ assert.ok(error.message.includes(first.endpoint.maskedUrl), 'details.maskedUrl 必须出现在 message 里');
1039
+ assert.match(error.message, /reuse: true/);
1040
+ return true;
1041
+ });
1042
+ const reused = await callTool(state, 'session_webhook_create', { name: 'dup', reuse: true });
1043
+ assert.equal(reused.created, false);
1044
+ assert.equal(reused.endpoint.id, first.endpoint.id);
1045
+ assert.equal(reused.endpoint.mode, 'steer');
1046
+ const list = await callTool(state, 'session_webhook_list', {});
1047
+ const listed = list.endpoints.find((endpoint) => endpoint.id === first.endpoint.id);
1048
+ assert.equal(listed.createdBy, 'agent');
1049
+ });
1050
+
1051
+ await test('工具 list:列出本会话全部端点(含 UI 建)与使用统计,不含别的会话', async () => {
1052
+ const { state } = await startHarness(directory, 'tool-list', { stored: ['s2'] });
1053
+ state.agents.set('s1', makeAgent('s1', state));
1054
+ const uiMade = await rpc(state, 'hooks/create', { sessionId: 's1', name: 'from-ui' });
1055
+ assert.equal(uiMade.ok, true, JSON.stringify(uiMade));
1056
+ const agentMade = await callTool(state, 'session_webhook_create', { name: 'from-agent' });
1057
+ const otherSession = await rpc(state, 'hooks/create', { sessionId: 's2', name: 'other-session' });
1058
+ assert.equal(otherSession.ok, true, JSON.stringify(otherSession));
1059
+
1060
+ // 给 agent 端点投递一次,让使用统计列有值
1061
+ const targetUrl = (await readFile(agentMade.urlFiles.direct, 'utf8')).trim();
1062
+ const delivered = await http(state, {
1063
+ method: 'POST', path: new URL(targetUrl).pathname, body: JSON.stringify({ text: '统计一下' }),
1064
+ });
1065
+ assert.equal(delivered.status, 202, JSON.stringify(delivered.json));
1066
+ await new Promise((resolve) => setTimeout(resolve, 20));
1067
+
1068
+ const definition = toolDef(state, 'session_webhook_list');
1069
+ const value = await callTool(state, 'session_webhook_list', {});
1070
+ assertToolOutput(definition, {}, value);
1071
+ assert.deepEqual(value.endpoints.map((endpoint) => endpoint.name).sort(), ['from-agent', 'from-ui']);
1072
+ const byName = Object.fromEntries(value.endpoints.map((endpoint) => [endpoint.name, endpoint]));
1073
+ assert.equal(byName['from-ui'].createdBy, 'ui');
1074
+ assert.equal(byName['from-agent'].createdBy, 'agent');
1075
+ assert.equal(byName['from-agent'].deliveryCount, 1);
1076
+ assert.equal(byName['from-agent'].lastStatus, 'delivered');
1077
+ assert.equal(typeof byName['from-agent'].lastUsedAt, 'string');
1078
+ assert.deepEqual(Object.keys(byName['from-agent'].urlFiles), ['direct']);
1079
+ assert.equal(value.endpoints.some((endpoint) => endpoint.name === 'other-session'), false);
1080
+ });
1081
+
1082
+ await test('工具 revoke:UI 建的报 ui-owned-endpoint;agent 建的删除后 URL 404、urlFile 消失', async () => {
1083
+ const { state, dir } = await startHarness(directory, 'tool-revoke');
1084
+ state.agents.set('s1', makeAgent('s1', state));
1085
+ const uiMade = await rpc(state, 'hooks/create', { sessionId: 's1', name: 'ui-owned' });
1086
+ assert.equal(uiMade.ok, true, JSON.stringify(uiMade));
1087
+ const agentMade = await callTool(state, 'session_webhook_create', { name: 'agent-owned' });
1088
+ const targetUrl = (await readFile(agentMade.urlFiles.direct, 'utf8')).trim();
1089
+
1090
+ await assert.rejects(
1091
+ callTool(state, 'session_webhook_revoke', { name: 'ui-owned' }),
1092
+ (error) => {
1093
+ assert.equal(error.code, 'ui-owned-endpoint');
1094
+ assert.match(error.message, /^\[ui-owned-endpoint\] /);
1095
+ assert.match(error.message, /界面/);
1096
+ return true;
1097
+ });
1098
+ const stillThere = await rpc(state, 'hooks/list', { sessionId: 's1' });
1099
+ assert.ok(stillThere.value.hooks.some((hook) => hook.id === uiMade.value.hook.id));
1100
+
1101
+ const definition = toolDef(state, 'session_webhook_revoke');
1102
+ const revoked = await callTool(state, 'session_webhook_revoke', { name: 'agent-owned' });
1103
+ assertToolOutput(definition, { name: 'agent-owned' }, revoked);
1104
+ assert.equal(revoked.revoked, true);
1105
+ assert.equal(revoked.id, agentMade.endpoint.id);
1106
+
1107
+ const after = await http(state, { method: 'GET', path: new URL(targetUrl).pathname });
1108
+ assert.equal(after.status, 404);
1109
+ assert.equal(after.json.error.code, 'unknown-endpoint');
1110
+ assert.equal((await listDir(join(dir, 'urls'))).some((name) => name.startsWith(agentMade.endpoint.id)), false);
1111
+ });
1112
+
1113
+ await test('工具 revoke:id/name 互斥校验、跨会话与无 agent 上下文明确报错', async () => {
1114
+ const { state } = await startHarness(directory, 'tool-selector', { stored: ['s2'] });
1115
+ state.agents.set('s1', makeAgent('s1', state));
1116
+ const mine = await callTool(state, 'session_webhook_create', { name: 'mine' });
1117
+ const other = await rpc(state, 'hooks/create', { sessionId: 's2', name: 'theirs' });
1118
+ assert.equal(other.ok, true, JSON.stringify(other));
1119
+ await assert.rejects(
1120
+ callTool(state, 'session_webhook_revoke', {}),
1121
+ (error) => error.code === 'bad-request' && /^\[bad-request\] /.test(error.message));
1122
+ await assert.rejects(
1123
+ callTool(state, 'session_webhook_revoke', { id: mine.endpoint.id, name: 'mine' }),
1124
+ (error) => error.code === 'bad-request' && /^\[bad-request\] /.test(error.message));
1125
+ await assert.rejects(
1126
+ callTool(state, 'session_webhook_revoke', { id: other.value.hook.id }),
1127
+ (error) => error.code === 'unknown-endpoint' && /^\[unknown-endpoint\] /.test(error.message));
1128
+ await assert.rejects(
1129
+ toolDef(state, 'session_webhook_revoke').execute({ name: 'mine' }, {}),
1130
+ (error) => error.code === 'no-session' && /^\[no-session\] /.test(error.message));
1131
+ });
1132
+
1133
+
1134
+ await test('settings.json 按键覆盖:只写 defaultBase 时入口表仍来自 YAML', async () => {
1135
+ const dir = join(directory, 'layer-merge');
1136
+ await mkdir(dir, { recursive: true });
1137
+ await writeFile(join(dir, 'settings.json'), JSON.stringify({
1138
+ version: 1,
1139
+ defaultBase: 'proxy',
1140
+ limits: { maxBodyBytes: 2048, maxTextBytes: 1024, ratePerMinute: 5 },
1141
+ }));
1142
+ const { ctx, state } = makeHarness({});
1143
+ await apply(ctx, {
1144
+ ...config,
1145
+ storeFile: join(dir, 'hooks.json'),
1146
+ publicBaseUrls: { proxy: 'https://dsh.example/dsh' },
1147
+ defaultBase: 'direct',
1148
+ });
1149
+ const view = (await rpc(state, 'config/get', {})).value;
1150
+ assert.deepEqual(view.yaml.publicBaseUrls, { proxy: 'https://dsh.example/dsh' });
1151
+ assert.equal(view.yaml.defaultBase, 'direct');
1152
+ assert.deepEqual(view.settings, {
1153
+ defaultBase: 'proxy',
1154
+ limits: { maxBodyBytes: 2048, maxTextBytes: 1024, ratePerMinute: 5 },
1155
+ });
1156
+ // 入口表来自 YAML(settings 没有这个键),defaultBase/limits 来自 settings
1157
+ assert.deepEqual(view.effective.publicBaseUrls, {
1158
+ direct: 'http://127.0.0.1:3080',
1159
+ proxy: 'https://dsh.example/dsh',
1160
+ });
1161
+ assert.equal(view.effective.defaultBase, 'proxy');
1162
+ assert.deepEqual(view.effective.limits, { maxBodyBytes: 2048, maxTextBytes: 1024, ratePerMinute: 5 });
1163
+ });
1164
+
1165
+ await test('settings.json 的 defaultBase 不在合并后入口表里时 apply 启动失败(fail-loud)', async () => {
1166
+ const dir = join(directory, 'layer-bad-default');
1167
+ await mkdir(dir, { recursive: true });
1168
+ await writeFile(join(dir, 'settings.json'), JSON.stringify({ version: 1, defaultBase: 'nope' }));
1169
+ const { ctx } = makeHarness({});
1170
+ await assert.rejects(
1171
+ apply(ctx, { ...config, storeFile: join(dir, 'hooks.json') }),
1172
+ (error) => error?.code === 'unknown-base');
1173
+ });
1174
+
1175
+
1176
+ await test('config/reset 逐键回退:入口覆盖保留、publicBaseUrls 重置后 YAML 入口重新生效', async () => {
1177
+ const { state, dir } = await startHarness(directory, 'cfg-reset', {
1178
+ config: {
1179
+ publicBaseUrls: { yamlbase: 'https://yaml.example/dsh' },
1180
+ limits: { maxBodyBytes: 4096, maxTextBytes: 1024, ratePerMinute: 3 },
1181
+ },
1182
+ });
1183
+ state.agents.set('sx', makeAgent('sx', state));
1184
+ const created = await rpc(state, 'hooks/create', { sessionId: 'sx', name: 'cfg-hook' });
1185
+ assert.equal(created.ok, true, JSON.stringify(created));
1186
+ const hookId = created.value.hook.id;
1187
+ const token = await tokenOf(state, hookId);
1188
+
1189
+ const saved = await rpc(state, 'config/set', {
1190
+ publicBaseUrls: { proxy: 'https://proxy.example' },
1191
+ defaultBase: 'proxy',
1192
+ limits: { maxBodyBytes: 8192, maxTextBytes: 8, ratePerMinute: 100 },
1193
+ });
1194
+ assert.equal(saved.ok, true, JSON.stringify(saved));
1195
+
1196
+ // 只重置 defaultBase + limits:publicBaseUrls 的覆盖仍在(仍只走 proxy)
1197
+ const partial = await rpc(state, 'config/reset', { keys: ['defaultBase', 'limits'] });
1198
+ assert.equal(partial.ok, true, JSON.stringify(partial));
1199
+ assert.deepEqual(partial.value.settings, { publicBaseUrls: { proxy: 'https://proxy.example' } });
1200
+ assert.deepEqual(partial.value.effective.publicBaseUrls, {
1201
+ direct: 'http://127.0.0.1:3080',
1202
+ proxy: 'https://proxy.example',
1203
+ });
1204
+ assert.equal(partial.value.effective.defaultBase, 'direct'); // 回落到 YAML 的 direct
1205
+ assert.deepEqual(partial.value.effective.limits, { maxBodyBytes: 4096, maxTextBytes: 1024, ratePerMinute: 3 });
1206
+ // limits 的 reset 也要重建 handler:capability 回到 YAML 值
1207
+ const capability = await http(state, { method: 'GET', path: '/api/session-inject' });
1208
+ assert.deepEqual(capability.json.limits, { bodyBytes: 4096, textBytes: 1024, ratePerMinute: 3 });
1209
+ // default 入口回到 direct:短名文件是 direct URL,proxy 变成带后缀文件
1210
+ assert.deepEqual(await listDir(join(dir, 'urls')), [`${hookId}.proxy.url`, `${hookId}.url`].sort());
1211
+ assert.equal((await readFile(join(dir, 'urls', `${hookId}.url`), 'utf8')).trim(),
1212
+ `http://127.0.0.1:3080/api/session-inject/hooks/${token}`);
1213
+ assert.equal((await readFile(join(dir, 'urls', `${hookId}.proxy.url`), 'utf8')).trim(),
1214
+ `https://proxy.example/api/session-inject/hooks/${token}`);
1215
+
1216
+ // 再重置 publicBaseUrls:覆盖层清空,YAML 入口重新生效,urlFile 按 YAML 入口重写
1217
+ const resetBases = await rpc(state, 'config/reset', { keys: ['publicBaseUrls'] });
1218
+ assert.equal(resetBases.ok, true, JSON.stringify(resetBases));
1219
+ assert.deepEqual(resetBases.value.settings, {});
1220
+ assert.deepEqual(resetBases.value.effective.publicBaseUrls, {
1221
+ direct: 'http://127.0.0.1:3080',
1222
+ yamlbase: 'https://yaml.example/dsh',
1223
+ });
1224
+ assert.equal(resetBases.value.effective.defaultBase, 'direct');
1225
+ // 覆盖层清空 → settings.json 删除
1226
+ await assert.rejects(async () => stat(join(dir, 'settings.json')));
1227
+ assert.deepEqual(await listDir(join(dir, 'urls')), [`${hookId}.url`, `${hookId}.yamlbase.url`].sort());
1228
+ assert.equal((await readFile(join(dir, 'urls', `${hookId}.yamlbase.url`), 'utf8')).trim(),
1229
+ `https://yaml.example/dsh/api/session-inject/hooks/${token}`);
1230
+
1231
+ // 幂等:没有 settings.json 时再次 reset 仍成功
1232
+ const again = await rpc(state, 'config/reset', { keys: ['publicBaseUrls'] });
1233
+ assert.equal(again.ok, true);
1234
+ assert.equal(again.value.saved, true);
1235
+ });
1236
+
1237
+ await test('config/reset:未知 key 报 bad-request、悬空 defaultBase 先校验不落盘、缺省清空全部', async () => {
1238
+ const { state, dir } = await startHarness(directory, 'cfg-reset-guard');
1239
+ state.agents.set('sy', makeAgent('sy', state));
1240
+ await rpc(state, 'hooks/create', { sessionId: 'sy', name: 'guard-hook' });
1241
+
1242
+ const unknown = await rpc(state, 'config/reset', { keys: ['nope'] });
1243
+ assert.equal(unknown.ok, false);
1244
+ assert.equal(unknown.error.code, 'bad-request');
1245
+ const notArray = await rpc(state, 'config/reset', { keys: 'defaultBase' });
1246
+ assert.equal(notArray.ok, false);
1247
+ assert.equal(notArray.error.code, 'bad-request');
1248
+
1249
+ const saved = await rpc(state, 'config/set', {
1250
+ publicBaseUrls: { proxy: 'https://proxy.example' },
1251
+ defaultBase: 'proxy',
1252
+ limits: { maxBodyBytes: 4096, maxTextBytes: 1024, ratePerMinute: 3 },
1253
+ });
1254
+ assert.equal(saved.ok, true, JSON.stringify(saved));
1255
+
1256
+ // 只删入口表会把 defaultBase 悬空:必须报错,且 settings.json / 生效值都不动
1257
+ const orphan = await rpc(state, 'config/reset', { keys: ['publicBaseUrls'] });
1258
+ assert.equal(orphan.ok, false);
1259
+ assert.equal(orphan.error.code, 'unknown-base');
1260
+ const after = (await rpc(state, 'config/get', {})).value;
1261
+ assert.deepEqual(after.settings.publicBaseUrls, { proxy: 'https://proxy.example' });
1262
+ assert.equal(after.effective.defaultBase, 'proxy');
1263
+ assert.equal(JSON.parse(await readFile(join(dir, 'settings.json'), 'utf8')).defaultBase, 'proxy');
1264
+
1265
+ // 缺省 keys = 清空全部覆盖:settings.json 消失、回到纯 YAML
1266
+ const all = await rpc(state, 'config/reset', {});
1267
+ assert.equal(all.ok, true, JSON.stringify(all));
1268
+ assert.deepEqual(all.value.settings, {});
1269
+ assert.equal(all.value.effective.defaultBase, 'direct');
1270
+ await assert.rejects(async () => stat(join(dir, 'settings.json')));
1271
+ });
1272
+
1273
+
1274
+ await test('工具错误出口:details 拼进 message,非 InjectError 标 [internal]', async () => {
1275
+ await assert.rejects(
1276
+ withToolErrors(async () => {
1277
+ throw fail(413, 'payload-too-large', '请求体太大', { limit: 42 });
1278
+ }),
1279
+ (error) => {
1280
+ assert.equal(error.code, 'payload-too-large');
1281
+ assert.equal(error.message, '[payload-too-large] 请求体太大(limit=42)');
1282
+ return true;
1283
+ });
1284
+ // message 里已经包含的 details 值不重复拼接(name-taken 的 id/maskedUrl 由上面的用例覆盖)
1285
+ await assert.rejects(
1286
+ withToolErrors(async () => {
1287
+ throw fail(409, 'name-taken', '当前会话已有名为「x」的端点(id: wh_1)', { hookId: 'wh_1' });
1288
+ }),
1289
+ (error) => {
1290
+ assert.equal(error.message, '[name-taken] 当前会话已有名为「x」的端点(id: wh_1)');
1291
+ return true;
1292
+ });
1293
+ // 真实 bug:不冒充业务错误,但带 [internal] 前缀便于模型区分
1294
+ await assert.rejects(
1295
+ withToolErrors(async () => { throw new TypeError('boom'); }),
1296
+ (error) => {
1297
+ assert.equal(error.code, 'internal');
1298
+ assert.match(error.message, /^\[internal\] boom/);
1299
+ assert.ok(error.cause instanceof TypeError);
1300
+ return true;
1301
+ });
1302
+ });
1303
+
1304
+ await test('apply 注册三个 agent 工具;没有 tools 服务的 profile 自动跳过', async () => {
1305
+ assert.deepEqual(state.toolDefs.map((definition) => definition.name),
1306
+ ['session_webhook_create', 'session_webhook_list', 'session_webhook_revoke']);
1307
+ const { ctx: bare, state: bareState } = makeHarness({ tools: false });
1308
+ await apply(bare, { ...config, storeFile: join(directory, 'no-tools', 'hooks.json') });
1309
+ assert.equal(bareState.toolDefs.length, 0);
1310
+ assert.equal(bareState.fetchRoutes.length, 1);
1311
+ assert.equal(bareState.routes.length, 1);
1312
+ });
1313
+
1314
+ } finally {
1315
+ await rm(directory, { recursive: true, force: true });
1316
+ }
1317
+
1318
+ console.log(`\n${passed} passed, ${failures.length} failed`);
1319
+ if (failures.length > 0) process.exitCode = 1;
1320
+ }
1321
+
1322
+ await main();