dsh-tool-manager 1.4.1 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/runtime.d.ts CHANGED
@@ -27,6 +27,9 @@ export declare class ToolPolicyRuntime {
27
27
  private mutating;
28
28
  private refreshQueued;
29
29
  private discoveryDisposer?;
30
+ /** The MCP-style proxy pair, registered only while some preset uses mcp mode. */
31
+ private mcpDisposers;
32
+ private mcpRegistered;
30
33
  /**
31
34
  * Whether `system-prompt/assemble` still owns the tool declarations.
32
35
  * DSH < 0.2.2 hands over a PromptAssembly (declarations included);
@@ -46,6 +49,7 @@ export declare class ToolPolicyRuntime {
46
49
  */
47
50
  private stepFilter;
48
51
  private restoreStepFilter?;
52
+ private restoreSchemasBridge?;
49
53
  /** The registry instance the observed schemas belong to. */
50
54
  private presetsInstance?;
51
55
  constructor(ctx: ContextLike,
@@ -152,6 +156,23 @@ export declare class ToolPolicyRuntime {
152
156
  * same. Presets without active (non-empty) on-demand groups hide it with `restrict()`.
153
157
  */
154
158
  private registerDiscovery;
159
+ /**
160
+ * Register or drop the MCP-style proxy pair.
161
+ *
162
+ * The pair only exists while at least one preset runs mcp mode: a groups-only
163
+ * install must keep its inherited surface byte-for-byte unchanged. Returns
164
+ * whether the registration state changed, so the caller can re-snapshot every
165
+ * live baseline.
166
+ */
167
+ private syncMcpTools;
168
+ /**
169
+ * Return every member of one on-demand group.
170
+ *
171
+ * Group-only on purpose: the catalog the model already reads lists each
172
+ * group's name and description, so a second keyword path would only add a
173
+ * slower way to reach the same tools.
174
+ */
175
+ private mcpFind;
155
176
  private discoveryDefinition;
156
177
  /**
157
178
  * Hide the policy's names from every per-step tool set.
@@ -169,6 +190,24 @@ export declare class ToolPolicyRuntime {
169
190
  * "visible but still blocked by the guard", never to a broken step.
170
191
  */
171
192
  private installStepFilter;
193
+ /**
194
+ * Give a PTC program a binding for every reachable tool, not just the declared
195
+ * ones.
196
+ *
197
+ * PTC instantiates each program's `tools` namespace from
198
+ * `tools.schemas(agent, toolSet)`, while the SDK text it shows the model comes
199
+ * from `tools.definitions(agent, toolSet)`. Both walk the same step view, so a
200
+ * grouped tool has no binding and `await tools.name()` dies as a TypeError
201
+ * before the guarded pipeline ever sees it. Answering `schemas()` from the
202
+ * projected set's second face splits the two: the SDK keeps the always-on
203
+ * roster, and every grouped tool keeps a binding validated against its real
204
+ * schema and logged under its real name.
205
+ *
206
+ * Native tool calling does not read `schemas()` for dispatch — it resolves
207
+ * through `tools.executable()` and the map's `get()` — so it keeps the
208
+ * declared-only answer and the MCP token saving is unchanged.
209
+ */
210
+ private installSchemasBridge;
172
211
  /** Remove this Agent's hidden names from one resolved step set. */
173
212
  private filterStepToolSet;
174
213
  private reconcile;
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../src/runtime.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAGV,kBAAkB,EAClB,WAAW,EAEX,cAAc,EACf,MAAM,UAAU,CAAC;AASlB,OAAO,EAAuB,KAAK,sBAAsB,EAAE,KAAK,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAC9G,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AACpD,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAU1D,OAAO,EAML,KAAK,mBAAmB,EACzB,MAAM,YAAY,CAAC;AAwBpB,qBAAa,iBAAiB;IAkC1B,OAAO,CAAC,QAAQ,CAAC,GAAG;IACpB,6EAA6E;IAC7E,OAAO,CAAC,QAAQ,CAAC,OAAO;IAExB,6EAA6E;IAC7E,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAC;IAC9B,+EAA+E;IAC/E,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAC;IACjC;;;;OAIG;IACH,OAAO,CAAC,QAAQ,CAAC,QAAQ;IA9C3B,OAAO,CAAC,QAAQ,CAAsB;IACtC,OAAO,CAAC,QAAQ,C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AAE;IAM7E,gFAAgF;IAChF,OAAO,CAAC,cAAc;YAwBR,WAAW;IA6CzB;;;;;;;;OAQG;IACH,OAAO,CAAC,iBAAiB;IAoBzB;;;;;;;;;OASG;IACH,OAAO,CAAC,iBAAiB;IAezB;;;;;;;OAOG;IACH,OAAO,CAAC,YAAY;IAiCpB;;;;;;OAMG;IACH,OAAO,CAAC,OAAO;IAyBf,OAAO,CAAC,mBAAmB;IA+B3B;;;;;;;;;;;;;;OAcG;IACH,OAAO,CAAC,iBAAiB;IAmCzB;;;;;;;;;;;;;;;;OAgBG;IACH,OAAO,CAAC,oBAAoB;IAsC5B,mEAAmE;IACnE,OAAO,CAAC,iBAAiB;IAuBzB,OAAO,CAAC,SAAS;IAgCjB,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;CAgB/B"}
package/dist/runtime.js CHANGED
@@ -1,10 +1,11 @@
1
1
  import { presetForAgent, resolvePresets } from "./dsh.js";
2
2
  import { applyCatalogDecision, catalogEntriesFromGroups, catalogHistory, isEnterDecision, } from "./catalog.js";
3
3
  import { restoredExposureNames } from "./exposure-history.js";
4
+ import { applyMcpNoticeDecision, createMcpToolDefinitions, mcpNoticeHistory, groupLookup, } from "./mcp-mode.js";
4
5
  import { PresetBindingRepair } from "./preset-repair.js";
5
6
  import { PromptToolAffinity } from "./prompt-affinity.js";
6
- import { denyNames, findGroup, matchesAnyPattern, parseKnownRestrictable, policyFor, resolveActiveGroups, sameNames, } from "./policy.js";
7
- import { DISCOVERY_TOOL_NAME, PTC_TRANSPORT_NAME, TOOL_MANAGER_PROBE_SESSION_ID, } from "./types.js";
7
+ import { asRecord, denyNames, findGroup, isMcpMode, matchesAnyPattern, mcpGroupedNames, mcpGroups, parseKnownRestrictable, policyFor, resolveActiveGroups, sameNames, } from "./policy.js";
8
+ import { DISCOVERY_TOOL_NAME, MCP_FIND_TOOL_NAME, PTC_TRANSPORT_NAME, TOOL_MANAGER_PROBE_SESSION_ID, } from "./types.js";
8
9
  export class ToolPolicyRuntime {
9
10
  ctx;
10
11
  presets;
@@ -21,6 +22,9 @@ export class ToolPolicyRuntime {
21
22
  mutating = false;
22
23
  refreshQueued = false;
23
24
  discoveryDisposer;
25
+ /** The MCP-style proxy pair, registered only while some preset uses mcp mode. */
26
+ mcpDisposers = [];
27
+ mcpRegistered = false;
24
28
  /**
25
29
  * Whether `system-prompt/assemble` still owns the tool declarations.
26
30
  * DSH < 0.2.2 hands over a PromptAssembly (declarations included);
@@ -40,6 +44,7 @@ export class ToolPolicyRuntime {
40
44
  */
41
45
  stepFilter;
42
46
  restoreStepFilter;
47
+ restoreSchemasBridge;
43
48
  /** The registry instance the observed schemas belong to. */
44
49
  presetsInstance;
45
50
  constructor(ctx,
@@ -68,7 +73,9 @@ export class ToolPolicyRuntime {
68
73
  // for the preset sections already mounted before this profile plugin.
69
74
  this.affinity.install(this.ctx.get("systemPrompt"), this.ctx.get("tools"), this.ctx.registry);
70
75
  this.registerDiscovery();
76
+ this.syncMcpTools();
71
77
  this.installStepFilter();
78
+ this.installSchemasBridge();
72
79
  const agents = this.ctx.get("agents");
73
80
  for (const agent of agents?.list() ?? [])
74
81
  this.install(agent);
@@ -87,15 +94,30 @@ export class ToolPolicyRuntime {
87
94
  }
88
95
  update(next) {
89
96
  this.settings = next;
97
+ // Registering or dropping the discovery tool changes the inherited surface,
98
+ // so every live baseline has to be re-snapshotted before the next step.
99
+ const mcpChanged = this.syncMcpTools();
90
100
  for (const state of this.states.values()) {
91
- const known = new Set(resolveActiveGroups(this.policy(state.agent), state.baseline)
92
- .map((group) => group.name.toLowerCase()));
101
+ // Groups can be edited at any time, so the exposure set is re-derived on
102
+ // every update instead of being trusted from the previous policy:
103
+ // - group mode stores group names, and a renamed or deleted group must go;
104
+ // - mcp mode stores nothing today, but the set is cleared so a switch back
105
+ // to group mode never inherits stale names from an earlier policy.
106
+ const policy = this.policy(state.agent);
107
+ if (isMcpMode(policy)) {
108
+ state.exposures.clear();
109
+ continue;
110
+ }
111
+ const known = new Set(resolveActiveGroups(policy, state.baseline).map((group) => group.name.toLowerCase()));
93
112
  for (const name of [...state.exposures]) {
94
113
  if (!known.has(name.toLowerCase()))
95
114
  state.exposures.delete(name);
96
115
  }
97
- this.reconcile(state);
98
116
  }
117
+ if (mcpChanged)
118
+ this.refreshAllBaselines();
119
+ for (const state of this.states.values())
120
+ this.reconcile(state);
99
121
  }
100
122
  install(agent) {
101
123
  if (this.states.has(agent))
@@ -104,13 +126,16 @@ export class ToolPolicyRuntime {
104
126
  return;
105
127
  const baselineSchemas = this.inheritedSchemas(agent);
106
128
  const baseline = baselineSchemas.map((schema) => schema.name);
107
- const groups = resolveActiveGroups(this.policy(agent), baseline);
108
- const restored = restoredExposureNames(agent.session);
129
+ const policy = this.policy(agent);
109
130
  const exposures = new Set();
110
- for (const name of restored) {
111
- const group = findGroup(groups, name);
112
- if (group)
113
- exposures.add(group.name);
131
+ if (!isMcpMode(policy)) {
132
+ const groups = resolveActiveGroups(policy, baseline);
133
+ const restored = restoredExposureNames(agent.session);
134
+ for (const name of restored) {
135
+ const group = findGroup(groups, name);
136
+ if (group)
137
+ exposures.add(group.name);
138
+ }
114
139
  }
115
140
  const state = {
116
141
  agent,
@@ -232,6 +257,14 @@ export class ToolPolicyRuntime {
232
257
  const scopedTools = state.agent.ctx.get("tools");
233
258
  state.guard = scopedTools?.guard?.((execution) => {
234
259
  const policy = this.policy(state.agent);
260
+ if (isMcpMode(policy)) {
261
+ // Hidden tools are blocked by step admission (they are not in the step
262
+ // set), so the guard only has to enforce an explicit disable.
263
+ if (policy.disabled.includes(execution.name)) {
264
+ return `tool ${JSON.stringify(execution.name)} is disabled by the tool-manager policy for this Agent preset`;
265
+ }
266
+ return undefined;
267
+ }
235
268
  const hidden = denyNames(policy, state.baseline, state.exposures);
236
269
  if (!hidden.includes(execution.name))
237
270
  return undefined;
@@ -425,8 +458,21 @@ export class ToolPolicyRuntime {
425
458
  // snapshot would otherwise leave its on-demand group empty here, and the
426
459
  // model would never learn the group exists.
427
460
  this.syncBaseline(state);
428
- const groups = resolveActiveGroups(this.policy(agent), state.baseline);
429
- return applyCatalogDecision(decision, catalogEntriesFromGroups(groups), catalogHistory(agent));
461
+ const policy = this.policy(agent);
462
+ if (isMcpMode(policy)) {
463
+ return applyMcpNoticeDecision(decision, {
464
+ mode: "mcp",
465
+ groups: mcpGroups(policy, state.baseline).map((group) => ({
466
+ name: group.name,
467
+ ...(group.description ? { description: group.description } : {}),
468
+ })),
469
+ }, mcpNoticeHistory(agent));
470
+ }
471
+ const groups = resolveActiveGroups(policy, state.baseline);
472
+ const withCatalog = applyCatalogDecision(decision, catalogEntriesFromGroups(groups), catalogHistory(agent));
473
+ // A Session that used to run mcp mode keeps that notice in its history; the
474
+ // group catalog alone would not contradict it.
475
+ return applyMcpNoticeDecision(withCatalog, { mode: "groups" }, mcpNoticeHistory(agent));
430
476
  }
431
477
  /**
432
478
  * Re-attach this Session to a registry instance that replaced its own.
@@ -572,6 +618,81 @@ export class ToolPolicyRuntime {
572
618
  this.mutating = false;
573
619
  }
574
620
  }
621
+ /**
622
+ * Register or drop the MCP-style proxy pair.
623
+ *
624
+ * The pair only exists while at least one preset runs mcp mode: a groups-only
625
+ * install must keep its inherited surface byte-for-byte unchanged. Returns
626
+ * whether the registration state changed, so the caller can re-snapshot every
627
+ * live baseline.
628
+ */
629
+ syncMcpTools() {
630
+ const needed = Object.values(this.settings.presets).some((policy) => isMcpMode(policy));
631
+ if (needed === this.mcpRegistered)
632
+ return false;
633
+ const tools = this.hostTools();
634
+ if (!tools)
635
+ return false;
636
+ this.mutating = true;
637
+ try {
638
+ if (!needed) {
639
+ for (const dispose of this.mcpDisposers.splice(0))
640
+ dispose();
641
+ this.mcpRegistered = false;
642
+ return true;
643
+ }
644
+ const definitions = createMcpToolDefinitions({
645
+ find: (agent, args) => this.mcpFind(agent, args),
646
+ });
647
+ const disposers = [];
648
+ try {
649
+ for (const definition of definitions)
650
+ disposers.push(tools.register(definition));
651
+ }
652
+ catch (error) {
653
+ for (const dispose of disposers.splice(0))
654
+ dispose();
655
+ this.warn(`tool-manager failed to register ${MCP_FIND_TOOL_NAME}: ${errorMessage(error)}`);
656
+ return false;
657
+ }
658
+ this.mcpDisposers = disposers;
659
+ this.mcpRegistered = true;
660
+ return true;
661
+ }
662
+ finally {
663
+ this.mutating = false;
664
+ }
665
+ }
666
+ /**
667
+ * Return every member of one on-demand group.
668
+ *
669
+ * Group-only on purpose: the catalog the model already reads lists each
670
+ * group's name and description, so a second keyword path would only add a
671
+ * slower way to reach the same tools.
672
+ */
673
+ mcpFind(agent, args) {
674
+ if (!agent)
675
+ throw new Error(`${MCP_FIND_TOOL_NAME} requires a calling agent`);
676
+ const state = this.states.get(agent);
677
+ if (!state)
678
+ throw new Error("tool manager is not attached to this Agent");
679
+ // Same reason as tool_list: adopt tools that appeared after the snapshot.
680
+ this.syncBaseline(state);
681
+ const policy = this.policy(agent);
682
+ const groups = mcpGroups(policy, state.baseline);
683
+ const record = asRecord(args) ?? {};
684
+ const requested = typeof record.group === "string" ? record.group.trim() : "";
685
+ const known = groups.map((item) => item.name).join(", ") || "(none)";
686
+ if (!requested) {
687
+ throw new Error(`group is required; known groups: ${known}`);
688
+ }
689
+ const group = groups.find((item) => item.name.toLowerCase() === requested.toLowerCase());
690
+ if (!group) {
691
+ throw new Error(`unknown tool group ${JSON.stringify(requested)}; known groups: ${known}`);
692
+ }
693
+ const members = new Set(group.tools);
694
+ return groupLookup({ name: group.name, ...(group.description ? { description: group.description } : {}) }, state.baselineSchemas.filter((schema) => members.has(schema.name)));
695
+ }
575
696
  discoveryDefinition() {
576
697
  return {
577
698
  name: DISCOVERY_TOOL_NAME,
@@ -651,6 +772,64 @@ export class ToolPolicyRuntime {
651
772
  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`);
652
773
  }
653
774
  }
775
+ /**
776
+ * Give a PTC program a binding for every reachable tool, not just the declared
777
+ * ones.
778
+ *
779
+ * PTC instantiates each program's `tools` namespace from
780
+ * `tools.schemas(agent, toolSet)`, while the SDK text it shows the model comes
781
+ * from `tools.definitions(agent, toolSet)`. Both walk the same step view, so a
782
+ * grouped tool has no binding and `await tools.name()` dies as a TypeError
783
+ * before the guarded pipeline ever sees it. Answering `schemas()` from the
784
+ * projected set's second face splits the two: the SDK keeps the always-on
785
+ * roster, and every grouped tool keeps a binding validated against its real
786
+ * schema and logged under its real name.
787
+ *
788
+ * Native tool calling does not read `schemas()` for dispatch — it resolves
789
+ * through `tools.executable()` and the map's `get()` — so it keeps the
790
+ * declared-only answer and the MCP token saving is unchanged.
791
+ */
792
+ installSchemasBridge() {
793
+ const tools = this.hostTools();
794
+ if (!tools)
795
+ return;
796
+ const owner = methodOwner(tools, "schemas");
797
+ if (!owner)
798
+ return;
799
+ const current = owner.schemas;
800
+ if (typeof current !== "function")
801
+ return;
802
+ if (current[SCHEMAS_BRIDGE_MARK])
803
+ return;
804
+ const original = current;
805
+ const bridge = function (...args) {
806
+ const projected = args[1];
807
+ const reach = projected?.[MCP_REACH_MARK];
808
+ if (typeof reach !== "function" || !isPtcScope(this, args[0])) {
809
+ return original.apply(this, args);
810
+ }
811
+ try {
812
+ // Delegate the projection itself: the binding then carries the host's
813
+ // own schema (real parameters, real output), not a re-derivation of it.
814
+ const reachable = reach.call(projected, args[0]);
815
+ const everything = { dispose: () => { }, view: () => reachable };
816
+ return original.call(this, args[0], everything);
817
+ }
818
+ catch {
819
+ return original.apply(this, args);
820
+ }
821
+ };
822
+ bridge[SCHEMAS_BRIDGE_MARK] = true;
823
+ try {
824
+ owner.schemas = bridge;
825
+ this.restoreSchemasBridge = () => {
826
+ owner.schemas = current;
827
+ };
828
+ }
829
+ catch (error) {
830
+ this.warn(`tool-manager could not bridge PTC tool bindings (${errorMessage(error)}); grouped tools stay unbindable inside run_code`);
831
+ }
832
+ }
654
833
  /** Remove this Agent's hidden names from one resolved step set. */
655
834
  filterStepToolSet(context, set) {
656
835
  try {
@@ -662,7 +841,15 @@ export class ToolPolicyRuntime {
662
841
  return set;
663
842
  if (!isStepToolSet(set))
664
843
  return set;
665
- const hidden = denyNames(this.policy(agent), state.baseline, state.exposures);
844
+ const policy = this.policy(agent);
845
+ if (isMcpMode(policy)) {
846
+ const hidden = new Set(denyNames(policy, state.baseline, state.exposures));
847
+ const grouped = new Set(mcpGroupedNames(policy, state.baseline));
848
+ return hidden.size === 0 && grouped.size === 0
849
+ ? set
850
+ : projectMcpStepToolSet(set, hidden, grouped);
851
+ }
852
+ const hidden = denyNames(policy, state.baseline, state.exposures);
666
853
  if (hidden.length === 0)
667
854
  return set;
668
855
  return filterStepToolSet(set, new Set(hidden));
@@ -672,7 +859,23 @@ export class ToolPolicyRuntime {
672
859
  }
673
860
  }
674
861
  reconcile(state) {
675
- const deny = denyNames(this.policy(state.agent), state.baseline, state.exposures);
862
+ const policy = this.policy(state.agent);
863
+ if (isMcpMode(policy)) {
864
+ // Hiding stays in the per-step projection (`tools.resolve` filter): the
865
+ // mcp mode recomputes visibility whenever a tool is opened, and a scope
866
+ // local registration cannot be restricted anyway. Keeping the registry
867
+ // lookup untouched also lets `tools.executable` answer for opened tools.
868
+ this.mutating = true;
869
+ try {
870
+ state.restriction?.();
871
+ state.restriction = undefined;
872
+ }
873
+ finally {
874
+ this.mutating = false;
875
+ }
876
+ return;
877
+ }
878
+ const deny = denyNames(policy, state.baseline, state.exposures);
676
879
  this.mutating = true;
677
880
  try {
678
881
  state.restriction?.();
@@ -747,12 +950,17 @@ export class ToolPolicyRuntime {
747
950
  async dispose() {
748
951
  this.restoreStepFilter?.();
749
952
  this.restoreStepFilter = undefined;
953
+ this.restoreSchemasBridge?.();
954
+ this.restoreSchemasBridge = undefined;
750
955
  for (const agent of [...this.states.keys()])
751
956
  this.uninstall(agent);
752
957
  this.mutating = true;
753
958
  try {
754
959
  this.discoveryDisposer?.();
755
960
  this.discoveryDisposer = undefined;
961
+ for (const dispose of this.mcpDisposers.splice(0))
962
+ dispose();
963
+ this.mcpRegistered = false;
756
964
  }
757
965
  finally {
758
966
  this.mutating = false;
@@ -799,6 +1007,8 @@ const RELINK_ATTEMPTS = 3;
799
1007
  const RELINK_RETRY_MS = 60;
800
1008
  /** Cross-reload marker: two wrappers must never stack on one Host. */
801
1009
  const STEP_FILTER_MARK = Symbol.for("dsh-tool-manager.step-filter");
1010
+ /** Cross-reload marker for the PTC binding bridge over `tools.schemas()`. */
1011
+ const SCHEMAS_BRIDGE_MARK = Symbol.for("dsh-tool-manager.schemas-bridge");
802
1012
  function isStepToolSet(value) {
803
1013
  if (value === null || typeof value !== "object")
804
1014
  return false;
@@ -806,12 +1016,110 @@ function isStepToolSet(value) {
806
1016
  return typeof record.view === "function" && typeof record.dispose === "function";
807
1017
  }
808
1018
  /**
809
- * Re-project one step set without the hidden names.
1019
+ * Re-project one step set into the MCP shape.
810
1020
  *
811
- * Everything downstream — prompt declarations, PTC bindings, and the
812
- * executable lookup — reads this map, so dropping a registration here is the
813
- * 0.2.2 equivalent of removing it from the prompt assembly.
1021
+ * Hidden names are dropped, grouped names are declared nowhere but stay
1022
+ * executable through the map's `get()`, and the set carries a second face for
1023
+ * the PTC binding loop (see {@link MCP_REACH_MARK}).
814
1024
  */
1025
+ function projectMcpStepToolSet(set, hidden, grouped) {
1026
+ // The set carries a second face for the PTC binding loop: `view()` is the
1027
+ // declaration (grouped tools absent), while this marked accessor is
1028
+ // everything the step may still execute. `ToolsService.schemas()` is patched
1029
+ // to read the accessor on a PTC scope, so a program keeps a binding for every
1030
+ // grouped tool although the generated SDK never mentions it.
1031
+ const projected = {
1032
+ dispose: () => set.dispose(),
1033
+ view: (scope) => projectStepView(set.view(scope), hidden, grouped),
1034
+ [MCP_REACH_MARK]: (scope) => {
1035
+ const reachable = new Map();
1036
+ for (const [name, definition] of set.view(scope)) {
1037
+ if (!hidden.has(name))
1038
+ reachable.set(name, definition);
1039
+ }
1040
+ return reachable;
1041
+ },
1042
+ };
1043
+ return projected;
1044
+ }
1045
+ /**
1046
+ * Marker for a projected step set: `(scope) => every executable definition`.
1047
+ *
1048
+ * Registered on `Symbol.for`, like {@link STEP_FILTER_MARK}, so a reload that
1049
+ * re-installs the wrapper recognizes the shape a previous wrapper produced.
1050
+ */
1051
+ const MCP_REACH_MARK = Symbol.for("dsh-tool-manager.reach-step-set");
1052
+ /**
1053
+ * Whether this scope's selected executor renders a generated SDK instead of
1054
+ * JSON schemas. Read by shape: the PTC executor is the one with `renderSdk`,
1055
+ * exactly as the catalog prices it, so no host import is needed.
1056
+ */
1057
+ function isPtcScope(tools, scope) {
1058
+ const select = tools?.selectExecutor;
1059
+ if (typeof select !== "function")
1060
+ return false;
1061
+ try {
1062
+ const executor = select.call(tools, scope);
1063
+ return typeof executor?.renderSdk === "function";
1064
+ }
1065
+ catch {
1066
+ // No executor in this scope: not PTC, and the caller keeps the original.
1067
+ return false;
1068
+ }
1069
+ }
1070
+ /**
1071
+ * Project one step view: drop hidden names, keep grouped names reachable by key.
1072
+ *
1073
+ * DSH reads the model-facing declarations by iterating this map and resolves a
1074
+ * dispatch with `get(name)`. A grouped tool therefore disappears from the
1075
+ * declaration list while staying directly callable — the same split the group
1076
+ * mode needs, minus the on-demand switch.
1077
+ */
1078
+ function projectStepView(view, hidden, grouped) {
1079
+ const declared = new Map();
1080
+ for (const [name, definition] of view) {
1081
+ if (hidden.has(name) || grouped.has(name))
1082
+ continue;
1083
+ declared.set(name, definition);
1084
+ }
1085
+ return new ReachableView(declared, view, hidden);
1086
+ }
1087
+ /**
1088
+ * Declarations plus reachable-but-undeclared definitions.
1089
+ *
1090
+ * Iteration and `size` describe what the model may see; `get`, `has` and the
1091
+ * registry lookup also answer for a name that a group currently stands in for.
1092
+ */
1093
+ class ReachableView {
1094
+ declared;
1095
+ all;
1096
+ hidden;
1097
+ constructor(declared, all, hidden) {
1098
+ this.declared = declared;
1099
+ this.all = all;
1100
+ this.hidden = hidden;
1101
+ }
1102
+ get size() { return this.declared.size; }
1103
+ get [Symbol.toStringTag]() { return "ReachableView"; }
1104
+ get(name) {
1105
+ if (this.hidden.has(name))
1106
+ return undefined;
1107
+ return this.declared.get(name) ?? this.all.get(name);
1108
+ }
1109
+ has(name) {
1110
+ if (this.hidden.has(name))
1111
+ return false;
1112
+ return this.declared.has(name) || this.all.has(name);
1113
+ }
1114
+ keys() { return this.declared.keys(); }
1115
+ values() { return this.declared.values(); }
1116
+ entries() { return this.declared.entries(); }
1117
+ forEach(callback) {
1118
+ for (const [key, value] of this.declared)
1119
+ callback(value, key, this);
1120
+ }
1121
+ [Symbol.iterator]() { return this.declared.entries(); }
1122
+ }
815
1123
  function filterStepToolSet(set, hidden) {
816
1124
  return {
817
1125
  dispose: () => set.dispose(),