dsh-tool-manager 1.2.11 → 1.2.13

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/dist/runtime.d.ts CHANGED
@@ -1,11 +1,22 @@
1
- import type { AgentPresetsLike, ContextLike, ToolSchemaLike } from "./dsh.js";
1
+ import type { AgentPresetsSource, ContextLike, ToolSchemaLike } from "./dsh.js";
2
+ import { type RepairAgentDiagnostics, type RepairDiagnostics } from "./preset-repair.js";
3
+ import type { UserNoticeInput } from "./notices.js";
2
4
  import { type ToolManagerSettings } from "./types.js";
3
5
  export declare class ToolPolicyRuntime {
4
6
  private readonly ctx;
7
+ /** The live registry, or a resolver: DSH replaces the instance on reload. */
5
8
  private readonly presets;
9
+ /** The reader's inbox: what the model cannot fix and the person must see. */
10
+ private readonly onUserNotice?;
11
+ /** Called when a repair succeeds, so its transient notice can be withdrawn. */
12
+ private readonly onBindingHealed?;
6
13
  private settings;
7
14
  private readonly states;
8
15
  private readonly observedSchemas;
16
+ /** Re-attaches Sessions to a registry instance that replaced their own. */
17
+ private readonly repairs;
18
+ /** Sessions whose re-attach already failed once, so the log stays readable. */
19
+ private readonly healFailures;
9
20
  private mutating;
10
21
  private refreshQueued;
11
22
  private discoveryDisposer?;
@@ -28,12 +39,32 @@ export declare class ToolPolicyRuntime {
28
39
  */
29
40
  private stepFilter;
30
41
  private restoreStepFilter?;
31
- constructor(ctx: ContextLike, presets: AgentPresetsLike, initial: ToolManagerSettings);
42
+ /** The registry instance the observed schemas belong to. */
43
+ private presetsInstance?;
44
+ constructor(ctx: ContextLike,
45
+ /** The live registry, or a resolver: DSH replaces the instance on reload. */
46
+ presets: AgentPresetsSource, initial: ToolManagerSettings,
47
+ /** The reader's inbox: what the model cannot fix and the person must see. */
48
+ onUserNotice?: ((notice: UserNoticeInput) => void) | undefined,
49
+ /** Called when a repair succeeds, so its transient notice can be withdrawn. */
50
+ onBindingHealed?: ((sessionId: string | undefined, presetId: string | undefined) => void) | undefined);
32
51
  start(): void;
33
52
  update(next: ToolManagerSettings): void;
34
53
  private install;
35
54
  private uninstall;
36
55
  private presetId;
56
+ /** The preset a Session runs, per the Session log, when the live registry has no binding. */
57
+ private declaredPreset;
58
+ /** Whether the live registry lost this Agent's preset binding to a reload. */
59
+ private lostBinding;
60
+ /**
61
+ * Drop observations taken through a registry instance DSH has replaced.
62
+ *
63
+ * A preset id identifies a composition of ONE registry instance. After a
64
+ * reload the same id is a different composition, so schemas observed under
65
+ * the retired instance would describe tools no live preset owns.
66
+ */
67
+ private retain;
37
68
  private policy;
38
69
  private hostTools;
39
70
  private inheritedSchemas;
@@ -43,8 +74,60 @@ export declare class ToolPolicyRuntime {
43
74
  private installLocalPolicy;
44
75
  private queueBaselineRefresh;
45
76
  private refreshAllBaselines;
77
+ /**
78
+ * Adopt names the live inherited surface gained since the snapshot.
79
+ *
80
+ * The baseline is a snapshot, and a snapshot can miss a registration that
81
+ * lands outside a `tools/change` edge: a plugin installed while the runtime
82
+ * was still starting, a standing Preset re-mounting, or a composition reload
83
+ * that re-registers tools without emitting a change. A stale baseline makes a
84
+ * saved on-demand group resolve to zero tools, so the group silently drops
85
+ * out of the catalog and its tools stay visible — the "the group only works
86
+ * after restarting DSH" report. One live `schemas(agent)` read per step is a
87
+ * map walk and keeps the policy, the catalog and the step on one tool set.
88
+ *
89
+ * The visible surface is read first: this Agent's own restriction only ever
90
+ * removes names, so a name it shows that the snapshot lacks is proof of a new
91
+ * registration. Only then is the restriction lifted for a full read — adopting
92
+ * the restricted view would drop every grouped tool from the snapshot and
93
+ * `reconcile()` would then un-hide them. A surface that merely shrank can be
94
+ * the transient gap of a composition swap, which the debounced `tools/change`
95
+ * refresh in `refreshAllBaselines()` settles.
96
+ * @param state - the Agent whose baseline may have drifted.
97
+ * @returns whether the baseline changed.
98
+ */
99
+ private syncBaseline;
100
+ /** Refresh the baseline of the Agent a `tools.resolve()` call belongs to. */
101
+ private syncStepBaseline;
46
102
  private openGroup;
47
103
  private onPreStep;
104
+ /**
105
+ * Re-attach this Session to a registry instance that replaced its own.
106
+ *
107
+ * A registry reload disposes the standing composition the Agent's scope
108
+ * points at, so the Session silently drops to root-bundle tools. Re-linking
109
+ * the Agent's ancestry to the live instance's revision restores them before
110
+ * this step resolves its tool set, which is the only point where it can
111
+ * happen without rebuilding the Agent (and therefore without a restart).
112
+ * @param state - the Agent whose preset binding may have been retired.
113
+ */
114
+ /** What the registry re-attach can see, for the diagnostic endpoint. */
115
+ repairDiagnostics(): RepairDiagnostics & {
116
+ agents: RepairAgentDiagnostics[];
117
+ };
118
+ /** One row per live Agent: what it resolves now, and what it should resolve. */
119
+ private diagnoseAgents;
120
+ private healBinding;
121
+ /**
122
+ * Tell the person that a Session lost its tools and cannot get them back.
123
+ *
124
+ * `healBinding` runs first and is the preferred outcome; this is the residual
125
+ * case (the handles died with the replaced instance, or the preset no longer
126
+ * exists). Then only a rebuilt Agent helps, and the reader is the one who has
127
+ * to act, so the notice goes to the banner — never into the transcript: a
128
+ * model-side reminder cannot restore a tool set and is easy to miss.
129
+ */
130
+ private reportLostBinding;
48
131
  /**
49
132
  * Register `tool_list` on the host/global tools layer, not per agent.
50
133
  *
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../src/runtime.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,gBAAgB,EAChB,WAAW,EAEX,cAAc,EACf,MAAM,UAAU,CAAC;AAelB,OAAO,EAKL,KAAK,mBAAmB,EACzB,MAAM,YAAY,CAAC;AAYpB,qBAAa,iBAAiB;IA4B1B,OAAO,CAAC,QAAQ,CAAC,GAAG;IACpB,OAAO,CAAC,QAAQ,CAAC,OAAO;IA5B1B,OAAO,CAAC,QAAQ,CAAsB;IACtC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAoC;IAC3D,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAkD;IAClF,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,a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wBR,WAAW;IA6CzB;;;;;;;;OAQG;IACH,OAAO,CAAC,iBAAiB;IAoBzB;;;;;;;;;OASG;IACH,OAAO,CAAC,iBAAiB;IAezB,OAAO,CAAC,mBAAmB;IA+B3B;;;;;;;;;;;;;;OAcG;IACH,OAAO,CAAC,iBAAiB;IAmCzB,mEAAmE;IACnE,OAAO,CAAC,iBAAiB;IAezB,OAAO,CAAC,SAAS;IAiBjB,OAAO,CAAC,SAAS;IAwBjB;;;;;;;OAOG;IACH,OAAO,CAAC,kBAAkB;IAK1B,8EAA8E;IAC9E,OAAO,CAAC,kBAAkB;IAa1B,OAAO,CAAC,IAAI;IAKN,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;CAY/B"}
package/dist/runtime.js CHANGED
@@ -1,13 +1,21 @@
1
- import { applyCatalogDecision, catalogEntriesFromGroups, catalogHistory, } from "./catalog.js";
1
+ import { presetForAgent, resolvePresets } from "./dsh.js";
2
+ import { applyCatalogDecision, catalogEntriesFromGroups, catalogHistory, isEnterDecision, } from "./catalog.js";
2
3
  import { restoredExposureNames } from "./exposure-history.js";
3
- import { denyNames, findGroup, parseKnownRestrictable, policyFor, resolveActiveGroups, sameNames, } from "./policy.js";
4
- import { DISCOVERY_TOOL_NAME, TOOL_MANAGER_PROBE_SESSION_ID, } from "./types.js";
4
+ import { PresetBindingRepair } from "./preset-repair.js";
5
+ import { denyNames, findGroup, matchesAnyPattern, parseKnownRestrictable, policyFor, resolveActiveGroups, sameNames, } from "./policy.js";
6
+ import { DISCOVERY_TOOL_NAME, PTC_TRANSPORT_NAME, TOOL_MANAGER_PROBE_SESSION_ID, } from "./types.js";
5
7
  export class ToolPolicyRuntime {
6
8
  ctx;
7
9
  presets;
10
+ onUserNotice;
11
+ onBindingHealed;
8
12
  settings;
9
13
  states = new Map();
10
14
  observedSchemas = new Map();
15
+ /** Re-attaches Sessions to a registry instance that replaced their own. */
16
+ repairs;
17
+ /** Sessions whose re-attach already failed once, so the log stays readable. */
18
+ healFailures = new Set();
11
19
  mutating = false;
12
20
  refreshQueued = false;
13
21
  discoveryDisposer;
@@ -30,10 +38,21 @@ export class ToolPolicyRuntime {
30
38
  */
31
39
  stepFilter;
32
40
  restoreStepFilter;
33
- constructor(ctx, presets, initial) {
41
+ /** The registry instance the observed schemas belong to. */
42
+ presetsInstance;
43
+ constructor(ctx,
44
+ /** The live registry, or a resolver: DSH replaces the instance on reload. */
45
+ presets, initial,
46
+ /** The reader's inbox: what the model cannot fix and the person must see. */
47
+ onUserNotice,
48
+ /** Called when a repair succeeds, so its transient notice can be withdrawn. */
49
+ onBindingHealed) {
34
50
  this.ctx = ctx;
35
51
  this.presets = presets;
52
+ this.onUserNotice = onUserNotice;
53
+ this.onBindingHealed = onBindingHealed;
36
54
  this.settings = initial;
55
+ this.repairs = new PresetBindingRepair({ warn: (message) => this.warn(message) });
37
56
  }
38
57
  start() {
39
58
  this.registerDiscovery();
@@ -108,7 +127,64 @@ export class ToolPolicyRuntime {
108
127
  }
109
128
  }
110
129
  presetId(agent) {
111
- return this.presets.composedPreset(agent.ctx);
130
+ const presets = resolvePresets(this.presets);
131
+ if (presets !== undefined) {
132
+ this.retain(presets);
133
+ this.repairs.observe(presets);
134
+ const live = presets.composedPreset(agent.ctx);
135
+ if (live !== undefined) {
136
+ const state = this.states.get(agent);
137
+ if (state)
138
+ state.preset = live;
139
+ return live;
140
+ }
141
+ // DSH binds a Session's preset composition when its Agent is created, and
142
+ // `dsh-scope` refuses to re-link a key that already has a parent. A
143
+ // reloaded registry therefore cannot answer for Agents composed by the
144
+ // instance it replaced; the Session log still names the preset those
145
+ // Sessions run, and their policy has to keep applying to it.
146
+ const declared = this.declaredPreset(presets, agent);
147
+ if (declared !== undefined) {
148
+ const state = this.states.get(agent);
149
+ if (state)
150
+ state.preset = declared;
151
+ return declared;
152
+ }
153
+ }
154
+ // No live instance at all: keep the preset this Agent was last seen on
155
+ // rather than dropping its policy.
156
+ return this.states.get(agent)?.preset;
157
+ }
158
+ /** The preset a Session runs, per the Session log, when the live registry has no binding. */
159
+ declaredPreset(presets, agent) {
160
+ return presetForAgent(presets, agent);
161
+ }
162
+ /** Whether the live registry lost this Agent's preset binding to a reload. */
163
+ lostBinding(state) {
164
+ const presets = resolvePresets(this.presets);
165
+ if (presets === undefined)
166
+ return false;
167
+ if (presets.composedPreset(state.agent.ctx) !== undefined)
168
+ return false;
169
+ // The Session projection belongs to the instance that was replaced and is
170
+ // rebuilt lazily, so on the first step after a reload it can still be empty.
171
+ // The binding the Agent lost names the preset either way.
172
+ return this.declaredPreset(presets, state.agent) !== undefined
173
+ || state.preset !== undefined
174
+ || this.repairs.boundPreset(state.agent) !== undefined;
175
+ }
176
+ /**
177
+ * Drop observations taken through a registry instance DSH has replaced.
178
+ *
179
+ * A preset id identifies a composition of ONE registry instance. After a
180
+ * reload the same id is a different composition, so schemas observed under
181
+ * the retired instance would describe tools no live preset owns.
182
+ */
183
+ retain(presets) {
184
+ if (this.presetsInstance === presets)
185
+ return;
186
+ this.presetsInstance = presets;
187
+ this.observedSchemas.clear();
112
188
  }
113
189
  policy(agent) {
114
190
  return policyFor(this.settings, this.presetId(agent));
@@ -164,8 +240,10 @@ export class ToolPolicyRuntime {
164
240
  const assembly = await next();
165
241
  if (!isPromptPresentation(assembly))
166
242
  return assembly;
167
- const hidden = new Set(denyNames(this.policy(state.agent), state.baseline, state.exposures));
168
- if (hidden.size === 0)
243
+ const policy = this.policy(state.agent);
244
+ const hidden = new Set(denyNames(policy, state.baseline, state.exposures));
245
+ const folded = foldedGroups(policy, state.exposures);
246
+ if (hidden.size === 0 && folded.length === 0 && policy.disabled.length === 0)
169
247
  return assembly;
170
248
  // DSH < 0.2.2: the waterfall receives a PromptAssembly and the returned
171
249
  // tool list is authoritative, so hiding declarations here works.
@@ -180,10 +258,7 @@ export class ToolPolicyRuntime {
180
258
  this.declarationFiltering = false;
181
259
  this.warnUnrestrictable();
182
260
  }
183
- const sections = assembly.sections.filter((section) => {
184
- const toolName = section.name.startsWith("tool:") ? section.name.slice("tool:".length) : undefined;
185
- return toolName === undefined || !hidden.has(toolName);
186
- });
261
+ const sections = assembly.sections.filter((section) => (!sectionHidden(section.name, state.baseline, policy, folded, hidden)));
187
262
  const filtered = { ...assembly, sections };
188
263
  if (Array.isArray(assembly.tools)) {
189
264
  filtered.tools = assembly.tools.filter((schema) => !hidden.has(schema.name));
@@ -224,10 +299,80 @@ export class ToolPolicyRuntime {
224
299
  for (const state of this.states.values())
225
300
  this.reconcile(state);
226
301
  }
302
+ /**
303
+ * Adopt names the live inherited surface gained since the snapshot.
304
+ *
305
+ * The baseline is a snapshot, and a snapshot can miss a registration that
306
+ * lands outside a `tools/change` edge: a plugin installed while the runtime
307
+ * was still starting, a standing Preset re-mounting, or a composition reload
308
+ * that re-registers tools without emitting a change. A stale baseline makes a
309
+ * saved on-demand group resolve to zero tools, so the group silently drops
310
+ * out of the catalog and its tools stay visible — the "the group only works
311
+ * after restarting DSH" report. One live `schemas(agent)` read per step is a
312
+ * map walk and keeps the policy, the catalog and the step on one tool set.
313
+ *
314
+ * The visible surface is read first: this Agent's own restriction only ever
315
+ * removes names, so a name it shows that the snapshot lacks is proof of a new
316
+ * registration. Only then is the restriction lifted for a full read — adopting
317
+ * the restricted view would drop every grouped tool from the snapshot and
318
+ * `reconcile()` would then un-hide them. A surface that merely shrank can be
319
+ * the transient gap of a composition swap, which the debounced `tools/change`
320
+ * refresh in `refreshAllBaselines()` settles.
321
+ * @param state - the Agent whose baseline may have drifted.
322
+ * @returns whether the baseline changed.
323
+ */
324
+ syncBaseline(state) {
325
+ const scopedTools = state.agent.ctx.get("tools");
326
+ // A missing service is a reload window, not an empty tool set.
327
+ if (!scopedTools)
328
+ return false;
329
+ let nextSchemas;
330
+ try {
331
+ const known = new Set(state.baseline);
332
+ if (scopedTools.schemas(state.agent).every((schema) => known.has(schema.name)))
333
+ return false;
334
+ this.mutating = true;
335
+ try {
336
+ state.restriction?.();
337
+ state.restriction = undefined;
338
+ nextSchemas = scopedTools.schemas(state.agent);
339
+ }
340
+ finally {
341
+ this.mutating = false;
342
+ }
343
+ }
344
+ catch {
345
+ // A refresh must never break the step; the guard still enforces the policy.
346
+ return false;
347
+ }
348
+ state.baseline = nextSchemas.map((schema) => schema.name);
349
+ state.baselineSchemas = nextSchemas;
350
+ this.observe(state);
351
+ this.reconcile(state);
352
+ return true;
353
+ }
354
+ /** Refresh the baseline of the Agent a `tools.resolve()` call belongs to. */
355
+ syncStepBaseline(context) {
356
+ try {
357
+ const agent = asCreated(context)?.agent;
358
+ if (!agent)
359
+ return;
360
+ const state = this.states.get(agent);
361
+ if (!state)
362
+ return;
363
+ this.syncBaseline(state);
364
+ }
365
+ catch {
366
+ // A refresh must never break the step; the guard still enforces the policy.
367
+ }
368
+ }
227
369
  openGroup(agent, requestedGroup) {
228
370
  const state = this.states.get(agent);
229
371
  if (!state)
230
372
  throw new Error("tool manager is not attached to this Agent");
373
+ // `tool_list` is the last chance to see a group whose tools appeared after
374
+ // this Agent's snapshot; resolve it against the live surface, not the old one.
375
+ this.syncBaseline(state);
231
376
  const groups = resolveActiveGroups(this.policy(agent), state.baseline);
232
377
  const known = groups.map((item) => item.name).join(", ") || "(none)";
233
378
  if (requestedGroup === undefined || requestedGroup.trim() === "") {
@@ -259,9 +404,135 @@ export class ToolPolicyRuntime {
259
404
  const state = this.states.get(agent);
260
405
  if (!state)
261
406
  return decision;
407
+ await this.healBinding(state);
408
+ // Nothing is appended to the step: a lost tool set is the reader's problem
409
+ // to act on, and the reader is reached through the notice banner instead of
410
+ // through the transcript.
411
+ this.reportLostBinding(state);
412
+ // Refresh before the catalog decision: a tool registered after this Agent's
413
+ // snapshot would otherwise leave its on-demand group empty here, and the
414
+ // model would never learn the group exists.
415
+ this.syncBaseline(state);
262
416
  const groups = resolveActiveGroups(this.policy(agent), state.baseline);
263
417
  return applyCatalogDecision(decision, catalogEntriesFromGroups(groups), catalogHistory(agent));
264
418
  }
419
+ /**
420
+ * Re-attach this Session to a registry instance that replaced its own.
421
+ *
422
+ * A registry reload disposes the standing composition the Agent's scope
423
+ * points at, so the Session silently drops to root-bundle tools. Re-linking
424
+ * the Agent's ancestry to the live instance's revision restores them before
425
+ * this step resolves its tool set, which is the only point where it can
426
+ * happen without rebuilding the Agent (and therefore without a restart).
427
+ * @param state - the Agent whose preset binding may have been retired.
428
+ */
429
+ /** What the registry re-attach can see, for the diagnostic endpoint. */
430
+ repairDiagnostics() {
431
+ const presets = resolvePresets(this.presets);
432
+ if (presets !== undefined)
433
+ this.repairs.observe(presets);
434
+ return { ...this.repairs.diagnostics(), agents: this.diagnoseAgents(presets) };
435
+ }
436
+ /** One row per live Agent: what it resolves now, and what it should resolve. */
437
+ diagnoseAgents(presets) {
438
+ const agents = this.ctx.get("agents");
439
+ const rows = [];
440
+ for (const agent of agents?.list() ?? []) {
441
+ const state = this.states.get(agent);
442
+ let composed;
443
+ let declared;
444
+ try {
445
+ composed = presets?.composedPreset(agent.ctx);
446
+ }
447
+ catch {
448
+ composed = undefined;
449
+ }
450
+ if (presets !== undefined)
451
+ declared = this.declaredPreset(presets, agent);
452
+ rows.push({
453
+ ...(agent.id === undefined ? {} : { id: agent.id }),
454
+ ...(composed === undefined ? {} : { composed }),
455
+ ...(declared === undefined ? {} : { declared }),
456
+ ...(state?.preset === undefined ? {} : { preset: state.preset }),
457
+ ...(state === undefined ? {} : { baseline: state.baseline.length }),
458
+ });
459
+ }
460
+ return rows;
461
+ }
462
+ async healBinding(state) {
463
+ const presets = resolvePresets(this.presets);
464
+ if (presets === undefined)
465
+ return;
466
+ this.repairs.observe(presets);
467
+ if (presets.composedPreset(state.agent.ctx) !== undefined)
468
+ return;
469
+ const presetId = this.declaredPreset(presets, state.agent) ?? state.preset ?? this.repairs.boundPreset(state.agent);
470
+ let repaired = false;
471
+ for (let attempt = 0; attempt < RELINK_ATTEMPTS && !repaired; attempt += 1) {
472
+ try {
473
+ repaired = await withTimeout(this.repairs.relink(state.agent, presetId), RELINK_TIMEOUT_MS);
474
+ }
475
+ catch (error) {
476
+ // A replacement instance registers its definitions asynchronously, so the
477
+ // first attempt after a reload can miss the preset. Give it a moment and
478
+ // try again in this same step, so the tool set never has to disappear.
479
+ const transient = /not-found|not ready|not registered/i.test(errorMessage(error));
480
+ if (transient && attempt + 1 < RELINK_ATTEMPTS) {
481
+ await sleep(RELINK_RETRY_MS);
482
+ continue;
483
+ }
484
+ // Retry on later steps too, but say so once: a warning per step would
485
+ // bury the log.
486
+ const key = `${state.agent.id ?? "?"}|${presetId}`;
487
+ if (!this.healFailures.has(key)) {
488
+ this.healFailures.add(key);
489
+ this.warn(`tool-manager: could not re-attach Session ${state.agent.id ?? "<unknown>"} to preset ${JSON.stringify(presetId)}: ${errorMessage(error)}`);
490
+ }
491
+ return;
492
+ }
493
+ }
494
+ if (!repaired)
495
+ return;
496
+ const restored = presetId ?? this.repairs.boundPreset(state.agent);
497
+ if (restored !== undefined)
498
+ state.preset = restored;
499
+ state.bindingNotice = undefined;
500
+ this.healFailures.delete(`${state.agent.id ?? "?"}|${presetId}`);
501
+ this.onBindingHealed?.(state.agent.id, restored);
502
+ this.warn(`tool-manager: re-attached Session ${state.agent.id ?? "<unknown>"} to preset ${JSON.stringify(presetId)} after the agent preset registry was reloaded`);
503
+ // The Session's tool set just grew back: re-snapshot it so policy, groups
504
+ // and the on-demand catalog describe the restored composition.
505
+ this.refreshAllBaselines();
506
+ }
507
+ /**
508
+ * Tell the person that a Session lost its tools and cannot get them back.
509
+ *
510
+ * `healBinding` runs first and is the preferred outcome; this is the residual
511
+ * case (the handles died with the replaced instance, or the preset no longer
512
+ * exists). Then only a rebuilt Agent helps, and the reader is the one who has
513
+ * to act, so the notice goes to the banner — never into the transcript: a
514
+ * model-side reminder cannot restore a tool set and is easy to miss.
515
+ */
516
+ reportLostBinding(state) {
517
+ if (state.bindingNotice === true)
518
+ return;
519
+ if (!this.lostBinding(state))
520
+ return;
521
+ const presets = resolvePresets(this.presets);
522
+ const presetId = (presets === undefined ? undefined : this.declaredPreset(presets, state.agent))
523
+ ?? state.preset
524
+ ?? this.repairs.boundPreset(state.agent);
525
+ state.bindingNotice = true;
526
+ const sessionId = state.agent.id;
527
+ this.onUserNotice?.({
528
+ kind: "failed",
529
+ ...(sessionId === undefined ? {} : { sessionId }),
530
+ ...(presetId === undefined ? {} : { presetId }),
531
+ message: `会话「${sessionId ?? "未知"}」在 agent preset 注册表重载后丢失了 preset ${presetId ?? "(未知)"} 提供的工具,` +
532
+ "插件没能自动重新挂载(旧注册表的绑定句柄已随实例销毁,或该 preset 已不存在)。" +
533
+ "需要重启 DSH(托盘图标 →「退出 DeepSeek Harness」→ 重新打开)才能恢复这些工具;切换会话无效。",
534
+ });
535
+ }
265
536
  /**
266
537
  * Register `tool_list` on the host/global tools layer, not per agent.
267
538
  *
@@ -348,6 +619,10 @@ export class ToolPolicyRuntime {
348
619
  }
349
620
  const runtime = this;
350
621
  const patched = (async function (...args) {
622
+ // Before the host resolves the set: a tool registered after this Agent's
623
+ // snapshot must join its on-demand group now, or the group stays empty and
624
+ // the tool stays admitted for this step.
625
+ runtime.syncStepBaseline(args[0]);
351
626
  const set = await current.apply(this, args);
352
627
  return runtime.filterStepToolSet(args[0], set);
353
628
  });
@@ -472,6 +747,30 @@ export class ToolPolicyRuntime {
472
747
  }
473
748
  }
474
749
  }
750
+ /** Wait `ms` without holding the event loop open. */
751
+ function sleep(ms) {
752
+ return new Promise((resolve) => {
753
+ const timer = setTimeout(resolve, ms);
754
+ timer.unref?.();
755
+ });
756
+ }
757
+ /** Settle `work` within `ms`, rejecting rather than stalling a model step. */
758
+ async function withTimeout(work, ms) {
759
+ let timer;
760
+ try {
761
+ return await Promise.race([
762
+ work,
763
+ new Promise((_, reject) => {
764
+ timer = setTimeout(() => reject(new Error(`timed out after ${ms}ms`)), ms);
765
+ timer.unref?.();
766
+ }),
767
+ ]);
768
+ }
769
+ finally {
770
+ if (timer !== undefined)
771
+ clearTimeout(timer);
772
+ }
773
+ }
475
774
  function asCreated(value) {
476
775
  if (value === null || typeof value !== "object")
477
776
  return undefined;
@@ -480,6 +779,12 @@ function asCreated(value) {
480
779
  return undefined;
481
780
  return { agent };
482
781
  }
782
+ /** How long a pre-step waits for a registry re-link before giving up. */
783
+ const RELINK_TIMEOUT_MS = 3000;
784
+ /** How many times one step tries to re-attach before it defers to the next. */
785
+ const RELINK_ATTEMPTS = 3;
786
+ /** Pause between attempts: enough for a replacement to finish registering. */
787
+ const RELINK_RETRY_MS = 60;
483
788
  /** Cross-reload marker: two wrappers must never stack on one Host. */
484
789
  const STEP_FILTER_MARK = Symbol.for("dsh-tool-manager.step-filter");
485
790
  function isStepToolSet(value) {
@@ -524,18 +829,131 @@ function methodOwner(value, name) {
524
829
  }
525
830
  return undefined;
526
831
  }
527
- function isEnterDecision(value) {
528
- if (value === null || typeof value !== "object")
529
- return false;
530
- const record = value;
531
- return record.kind === "enter" && Array.isArray(record.messages);
532
- }
533
832
  function isPromptPresentation(value) {
534
833
  if (value === null || typeof value !== "object")
535
834
  return false;
536
835
  const record = value;
537
836
  return Array.isArray(record.sections);
538
837
  }
838
+ /**
839
+ * Shared MCP resource tools published by `@deepseek-ai/dsh-mcp-resources`.
840
+ *
841
+ * The package advertises all three in one `mcp-resource-servers` section, so
842
+ * the section is stale only once the whole family is hidden.
843
+ */
844
+ const MCP_RESOURCE_TOOLS = [
845
+ "list_mcp_resources",
846
+ "list_mcp_resource_templates",
847
+ "read_mcp_resource",
848
+ ];
849
+ /**
850
+ * Whether a prompt section exists only to advertise tools that are all hidden.
851
+ *
852
+ * A section that only advertises tools is dead weight once every one of them is
853
+ * hidden: the model reads an instruction it cannot follow, because the
854
+ * declaration and the call are both gone. DSH links `tool:<name>` sections to
855
+ * exactly one tool; other producers encode the family in the section name, and
856
+ * this resolver extends the same rule by convention instead of hard-coding one
857
+ * group or one server:
858
+ * - `tool:<name>` — DSH's per-tool description section;
859
+ * - `mcp:<server>` — `@deepseek-ai/dsh-mcp-client` instructions for one server,
860
+ * covering every `mcp__<server>__*` tool it registered;
861
+ * - `mcp-resource-servers` — `@deepseek-ai/dsh-mcp-resources` hint for the
862
+ * shared resource tools above.
863
+ *
864
+ * Membership is read from the baseline *and* from the preset policy. A child
865
+ * Agent can start with a tool surface already narrowed by an upstream
866
+ * `tools.restrict()`, so its baseline may not name a single member of a folded
867
+ * group even though the section is still emitted globally (issue #3).
868
+ *
869
+ * @param name - prompt section name.
870
+ * @param baseline - every tool name this Agent inherited.
871
+ * @param policy - the preset policy for this Agent.
872
+ * @param folded - the policy's groups that are not open in this session.
873
+ * @param hidden - names already denied by `denyNames()` for this Agent.
874
+ * @returns whether the section must be dropped from the prompt.
875
+ */
876
+ function sectionHidden(name, baseline, policy, folded, hidden) {
877
+ const owners = sectionToolOwners(name, baseline, policy);
878
+ // Not a tool section: persona, plan policy, delegation rules, and every other
879
+ // prose contribution is never filtered by this plugin.
880
+ if (owners === undefined)
881
+ return false;
882
+ if (owners.length === 0) {
883
+ // A namespace section whose tools this Agent never inherited. Only a folded
884
+ // pattern that spells out this very namespace proves it stale.
885
+ const prefix = mcpServerPrefix(name);
886
+ return prefix !== undefined && folded.some((group) => (group.patterns.some((pattern) => pattern.startsWith(prefix) && pattern.length > prefix.length)));
887
+ }
888
+ return owners.every((tool) => hidden.has(tool) || policyHides(policy, folded, tool));
889
+ }
890
+ /**
891
+ * The tools a prompt section exists to introduce.
892
+ *
893
+ * @param name - prompt section name.
894
+ * @param registeredNames - every tool name in the Agent's baseline.
895
+ * @param policy - the preset policy, whose literal names count as members.
896
+ * @returns the owned tool names (possibly empty when the family is known only
897
+ * by a wildcard pattern), or `undefined` when the section is not owned by a
898
+ * tool family and must always be kept.
899
+ */
900
+ function sectionToolOwners(name, registeredNames, policy) {
901
+ if (name.startsWith("tool:"))
902
+ return [name.slice("tool:".length)];
903
+ if (name === "mcp-resource-servers")
904
+ return MCP_RESOURCE_TOOLS;
905
+ const prefix = mcpServerPrefix(name);
906
+ if (prefix === undefined)
907
+ return undefined;
908
+ const members = new Set(registeredNames.filter((tool) => tool.startsWith(prefix)));
909
+ for (const declared of declaredToolNames(policy)) {
910
+ if (declared.startsWith(prefix))
911
+ members.add(declared);
912
+ }
913
+ return [...members];
914
+ }
915
+ /** The `mcp__<server>__` tool-name prefix an `mcp:<server>` section covers. */
916
+ function mcpServerPrefix(sectionName) {
917
+ if (!sectionName.startsWith("mcp:"))
918
+ return undefined;
919
+ const server = sectionName.slice("mcp:".length);
920
+ return server ? `mcp__${server}__` : undefined;
921
+ }
922
+ /** Every tool name the policy spells out, including exact group patterns. */
923
+ function declaredToolNames(policy) {
924
+ const names = [...policy.disabled];
925
+ for (const group of policy.groups) {
926
+ for (const pattern of group.patterns) {
927
+ if (!pattern.includes("*"))
928
+ names.push(pattern);
929
+ }
930
+ }
931
+ return names;
932
+ }
933
+ /** Groups that are not open in this Agent, so their members stay folded. */
934
+ function foldedGroups(policy, exposures) {
935
+ const open = new Set([...exposures].map((name) => name.toLowerCase()));
936
+ return policy.groups.filter((group) => !open.has(group.name.toLowerCase()));
937
+ }
938
+ /**
939
+ * Whether the preset policy alone hides a tool, independent of the tool
940
+ * surface this Agent inherited.
941
+ *
942
+ * `denyNames()` can only deny names that are present, because `restrict()`
943
+ * rejects unknown ones. A section must not depend on that: the child Agent of
944
+ * a delegation inherits a narrowed tool set before this plugin installs, so
945
+ * the folded group resolves to zero tools there while the section — registered
946
+ * globally by the tool's own plugin — is still emitted for everyone.
947
+ */
948
+ function policyHides(policy, folded, toolName) {
949
+ // Mirrors `denyNames()`: the PTC transport and the discovery tool are never
950
+ // folded, so neither may lose its section to a stray group pattern.
951
+ if (toolName === PTC_TRANSPORT_NAME || toolName === DISCOVERY_TOOL_NAME)
952
+ return false;
953
+ if (policy.disabled.includes(toolName))
954
+ return true;
955
+ return folded.some((group) => matchesAnyPattern(toolName, group.patterns));
956
+ }
539
957
  function errorMessage(error) {
540
958
  return error instanceof Error ? error.message : String(error);
541
959
  }