dsh-tool-manager 1.2.10 → 1.2.12

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.js CHANGED
@@ -1,23 +1,62 @@
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;
14
- constructor(ctx, presets, initial) {
22
+ /**
23
+ * Whether `system-prompt/assemble` still owns the tool declarations.
24
+ * DSH < 0.2.2 hands over a PromptAssembly (declarations included);
25
+ * DSH >= 0.2.2 hands over a PromptPresentation and re-attaches the
26
+ * provider's declarations after the waterfall. Undefined until the first
27
+ * assembly with something to hide is observed.
28
+ */
29
+ declarationFiltering;
30
+ /** Names `restrict()` refused because they are not global tools. */
31
+ unrestrictable = new Set();
32
+ warnedUnrestrictable = false;
33
+ /**
34
+ * Whether this Host filters the per-step admitted set.
35
+ * DSH >= 0.2.2 derives declarations, PTC bindings, and execution lookup from
36
+ * `tools.resolve()`, which is the only seam that can hide a registration made
37
+ * in the Agent's own scope. `undefined` on older Hosts (no `resolve`).
38
+ */
39
+ stepFilter;
40
+ restoreStepFilter;
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) {
15
50
  this.ctx = ctx;
16
51
  this.presets = presets;
52
+ this.onUserNotice = onUserNotice;
53
+ this.onBindingHealed = onBindingHealed;
17
54
  this.settings = initial;
55
+ this.repairs = new PresetBindingRepair({ warn: (message) => this.warn(message) });
18
56
  }
19
57
  start() {
20
58
  this.registerDiscovery();
59
+ this.installStepFilter();
21
60
  const agents = this.ctx.get("agents");
22
61
  for (const agent of agents?.list() ?? [])
23
62
  this.install(agent);
@@ -88,7 +127,64 @@ export class ToolPolicyRuntime {
88
127
  }
89
128
  }
90
129
  presetId(agent) {
91
- 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();
92
188
  }
93
189
  policy(agent) {
94
190
  return policyFor(this.settings, this.presetId(agent));
@@ -142,19 +238,32 @@ export class ToolPolicyRuntime {
142
238
  if (typeof next !== "function")
143
239
  return args[0];
144
240
  const assembly = await next();
145
- if (!isPromptAssembly(assembly))
241
+ if (!isPromptPresentation(assembly))
146
242
  return assembly;
147
- const hidden = new Set(denyNames(this.policy(state.agent), state.baseline, state.exposures));
148
- 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)
149
247
  return assembly;
150
- return {
151
- ...assembly,
152
- tools: assembly.tools.filter((schema) => !hidden.has(schema.name)),
153
- sections: assembly.sections.filter((section) => {
154
- const toolName = section.name.startsWith("tool:") ? section.name.slice("tool:".length) : undefined;
155
- return toolName === undefined || !hidden.has(toolName);
156
- }),
157
- };
248
+ // DSH < 0.2.2: the waterfall receives a PromptAssembly and the returned
249
+ // tool list is authoritative, so hiding declarations here works.
250
+ // DSH >= 0.2.2: it receives a PromptPresentation (sections/contexts/
251
+ // variables) and the provider's declarations are re-attached AFTER the
252
+ // waterfall, so only section text can still be filtered. The guard keeps
253
+ // blocking the call itself either way.
254
+ if (Array.isArray(assembly.tools)) {
255
+ this.declarationFiltering = true;
256
+ }
257
+ else {
258
+ this.declarationFiltering = false;
259
+ this.warnUnrestrictable();
260
+ }
261
+ const sections = assembly.sections.filter((section) => (!sectionHidden(section.name, state.baseline, policy, folded, hidden)));
262
+ const filtered = { ...assembly, sections };
263
+ if (Array.isArray(assembly.tools)) {
264
+ filtered.tools = assembly.tools.filter((schema) => !hidden.has(schema.name));
265
+ }
266
+ return filtered;
158
267
  });
159
268
  }
160
269
  queueBaselineRefresh() {
@@ -190,10 +299,80 @@ export class ToolPolicyRuntime {
190
299
  for (const state of this.states.values())
191
300
  this.reconcile(state);
192
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
+ }
193
369
  openGroup(agent, requestedGroup) {
194
370
  const state = this.states.get(agent);
195
371
  if (!state)
196
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);
197
376
  const groups = resolveActiveGroups(this.policy(agent), state.baseline);
198
377
  const known = groups.map((item) => item.name).join(", ") || "(none)";
199
378
  if (requestedGroup === undefined || requestedGroup.trim() === "") {
@@ -225,9 +404,135 @@ export class ToolPolicyRuntime {
225
404
  const state = this.states.get(agent);
226
405
  if (!state)
227
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);
228
416
  const groups = resolveActiveGroups(this.policy(agent), state.baseline);
229
417
  return applyCatalogDecision(decision, catalogEntriesFromGroups(groups), catalogHistory(agent));
230
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
+ }
231
536
  /**
232
537
  * Register `tool_list` on the host/global tools layer, not per agent.
233
538
  *
@@ -283,6 +588,77 @@ export class ToolPolicyRuntime {
283
588
  },
284
589
  };
285
590
  }
591
+ /**
592
+ * Hide the policy's names from every per-step tool set.
593
+ *
594
+ * DSH 0.2.2 builds each step's admitted set from `tools.resolve()`, then
595
+ * derives the model-facing declarations, the PTC bindings, and execution
596
+ * lookup from it. Unlike `restrict()`, that set is NOT exempting the Agent's
597
+ * own registrations, so this is the only seam able to hide a tool another
598
+ * plugin registered into `agent.ctx` — the exact behaviour the prompt
599
+ * waterfall provided before 0.2.2.
600
+ *
601
+ * The seam is a method on the shared `ToolsService` prototype, so one patch
602
+ * covers the host service and every Agent-scoped derivation of it. Every
603
+ * failure path returns the untouched set: a wrong guess here must degrade to
604
+ * "visible but still blocked by the guard", never to a broken step.
605
+ */
606
+ installStepFilter() {
607
+ const tools = this.hostTools();
608
+ if (!tools)
609
+ return;
610
+ const owner = methodOwner(tools, "resolve");
611
+ if (!owner)
612
+ return;
613
+ const current = owner.resolve;
614
+ if (typeof current !== "function")
615
+ return;
616
+ if (current[STEP_FILTER_MARK]) {
617
+ this.stepFilter = "installed";
618
+ return;
619
+ }
620
+ const runtime = this;
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]);
626
+ const set = await current.apply(this, args);
627
+ return runtime.filterStepToolSet(args[0], set);
628
+ });
629
+ patched[STEP_FILTER_MARK] = true;
630
+ try {
631
+ owner.resolve = patched;
632
+ this.restoreStepFilter = () => {
633
+ owner.resolve = current;
634
+ };
635
+ this.stepFilter = "installed";
636
+ }
637
+ catch (error) {
638
+ this.stepFilter = "failed";
639
+ this.warn(`tool-manager could not filter the per-step tool set (${errorMessage(error)}); tools registered in the Agent's own scope stay visible to the model`);
640
+ }
641
+ }
642
+ /** Remove this Agent's hidden names from one resolved step set. */
643
+ filterStepToolSet(context, set) {
644
+ try {
645
+ const agent = asCreated(context)?.agent;
646
+ if (!agent)
647
+ return set;
648
+ const state = this.states.get(agent);
649
+ if (!state)
650
+ return set;
651
+ if (!isStepToolSet(set))
652
+ return set;
653
+ const hidden = denyNames(this.policy(agent), state.baseline, state.exposures);
654
+ if (hidden.length === 0)
655
+ return set;
656
+ return filterStepToolSet(set, new Set(hidden));
657
+ }
658
+ catch {
659
+ return set;
660
+ }
661
+ }
286
662
  reconcile(state) {
287
663
  const deny = denyNames(this.policy(state.agent), state.baseline, state.exposures);
288
664
  this.mutating = true;
@@ -311,6 +687,9 @@ export class ToolPolicyRuntime {
311
687
  return undefined;
312
688
  }
313
689
  const next = deny.filter((name) => known.has(name));
690
+ const unrestrictable = deny.filter((name) => !known.has(name));
691
+ if (unrestrictable.length > 0)
692
+ this.noteUnrestrictable(unrestrictable);
314
693
  if (next.length === 0)
315
694
  return undefined;
316
695
  try {
@@ -322,11 +701,40 @@ export class ToolPolicyRuntime {
322
701
  }
323
702
  }
324
703
  }
704
+ /**
705
+ * Remember names `restrict()` refused because they are not global tools.
706
+ *
707
+ * These are registrations owned by the Agent's own scope (delegation and
708
+ * scheduled-task tools are the common ones). DSH < 0.2.2 still hid them by
709
+ * filtering the prompt assembly; DSH >= 0.2.2 cannot, so the call guard is
710
+ * the only remaining enforcement and the model keeps seeing the name.
711
+ */
712
+ noteUnrestrictable(names) {
713
+ for (const name of names)
714
+ this.unrestrictable.add(name);
715
+ this.warnUnrestrictable();
716
+ }
717
+ /** Explain the remaining limitation once, and only when it actually bites. */
718
+ warnUnrestrictable() {
719
+ if (this.declarationFiltering !== false || this.warnedUnrestrictable)
720
+ return;
721
+ // The per-step filter already removes these names from everything the
722
+ // model sees, so there is nothing to report.
723
+ if (this.stepFilter === "installed")
724
+ return;
725
+ if (this.unrestrictable.size === 0)
726
+ return;
727
+ this.warnedUnrestrictable = true;
728
+ const names = [...this.unrestrictable].sort();
729
+ this.warn(`tool-manager: this DSH builds the system prompt without tool declarations, so ${names.length} Agent-scoped tool(s) — ${names.join(", ")} — stay visible to the model even when disabled or assigned to an on-demand group. Calls are still blocked by the tool-manager guard; only tools registered outside the Agent's own scope can be hidden from the prompt.`);
730
+ }
325
731
  warn(message) {
326
732
  const logger = this.ctx.get("logger");
327
733
  logger?.warn?.(message);
328
734
  }
329
735
  async dispose() {
736
+ this.restoreStepFilter?.();
737
+ this.restoreStepFilter = undefined;
330
738
  for (const agent of [...this.states.keys()])
331
739
  this.uninstall(agent);
332
740
  this.mutating = true;
@@ -339,6 +747,30 @@ export class ToolPolicyRuntime {
339
747
  }
340
748
  }
341
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
+ }
342
774
  function asCreated(value) {
343
775
  if (value === null || typeof value !== "object")
344
776
  return undefined;
@@ -347,17 +779,180 @@ function asCreated(value) {
347
779
  return undefined;
348
780
  return { agent };
349
781
  }
350
- function isEnterDecision(value) {
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;
788
+ /** Cross-reload marker: two wrappers must never stack on one Host. */
789
+ const STEP_FILTER_MARK = Symbol.for("dsh-tool-manager.step-filter");
790
+ function isStepToolSet(value) {
351
791
  if (value === null || typeof value !== "object")
352
792
  return false;
353
793
  const record = value;
354
- return record.kind === "enter" && Array.isArray(record.messages);
794
+ return typeof record.view === "function" && typeof record.dispose === "function";
795
+ }
796
+ /**
797
+ * Re-project one step set without the hidden names.
798
+ *
799
+ * Everything downstream — prompt declarations, PTC bindings, and the
800
+ * executable lookup — reads this map, so dropping a registration here is the
801
+ * 0.2.2 equivalent of removing it from the prompt assembly.
802
+ */
803
+ function filterStepToolSet(set, hidden) {
804
+ return {
805
+ dispose: () => set.dispose(),
806
+ view(scope) {
807
+ const view = set.view(scope);
808
+ const kept = new Map();
809
+ for (const [name, definition] of view) {
810
+ if (!hidden.has(name))
811
+ kept.set(name, definition);
812
+ }
813
+ return kept;
814
+ },
815
+ };
816
+ }
817
+ /**
818
+ * The object in `value`'s prototype chain that owns `name`.
819
+ *
820
+ * Services in Cordis derive per-context instances with `Object.create(service)`,
821
+ * so the owning prototype is the single place a patch reaches every Agent.
822
+ */
823
+ function methodOwner(value, name) {
824
+ let owner = value;
825
+ while (owner !== null && owner !== Object.prototype) {
826
+ if (Object.prototype.hasOwnProperty.call(owner, name))
827
+ return owner;
828
+ owner = Object.getPrototypeOf(owner);
829
+ }
830
+ return undefined;
355
831
  }
356
- function isPromptAssembly(value) {
832
+ function isPromptPresentation(value) {
357
833
  if (value === null || typeof value !== "object")
358
834
  return false;
359
835
  const record = value;
360
- return Array.isArray(record.tools) && Array.isArray(record.sections);
836
+ return Array.isArray(record.sections);
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));
361
956
  }
362
957
  function errorMessage(error) {
363
958
  return error instanceof Error ? error.message : String(error);