dsh-tool-manager 1.2.11 → 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.
@@ -0,0 +1,279 @@
1
+ const HISTORY_KEY = Symbol.for("dsh-tool-manager.preset-registry-history");
2
+ /** How many re-attach attempts to remember for diagnostics. */
3
+ const ATTEMPT_LIMIT = 20;
4
+ function registryHistory() {
5
+ const holder = globalThis;
6
+ holder[HISTORY_KEY] ??= {};
7
+ return holder[HISTORY_KEY];
8
+ }
9
+ /** The last registry instance this plugin saw, plus the one it replaced. */
10
+ export class PresetBindingRepair {
11
+ options;
12
+ reported = new Set();
13
+ /** Refusals in the order they happened, for diagnostics(). */
14
+ refused = [];
15
+ /** Recent re-attach attempts, newest last, for diagnostics(). */
16
+ attempts = [];
17
+ constructor(options) {
18
+ this.options = options;
19
+ }
20
+ /** Remember the instance DSH publishes, keeping the one it replaced. */
21
+ observe(live) {
22
+ if (live === undefined)
23
+ return;
24
+ const history = registryHistory();
25
+ if (history.live === live)
26
+ return;
27
+ history.retired = history.live;
28
+ history.live = live;
29
+ }
30
+ /**
31
+ * The preset an Agent was last bound to, read from the binding itself.
32
+ *
33
+ * The Session projection is the authoritative answer for what an Agent
34
+ * *should* run, but it belongs to one registry instance and is rebuilt lazily;
35
+ * the binding that is about to be repaired still names the composition the
36
+ * Agent actually lost, which is enough to restore it.
37
+ * @param agent - the Agent to inspect.
38
+ * @returns the preset id, when any instance still holds a binding for it.
39
+ */
40
+ boundPreset(agent) {
41
+ const history = registryHistory();
42
+ for (const candidate of [history.retired, history.live]) {
43
+ const bindings = candidate?.bindings;
44
+ if (bindings === undefined || typeof bindings.get !== "function")
45
+ continue;
46
+ const key = scopeKeyOf(agent.ctx, bindings);
47
+ if (key === undefined)
48
+ continue;
49
+ const presetId = bindings.get(key)?.generation?.mount?.presetId;
50
+ if (typeof presetId === "string")
51
+ return presetId;
52
+ }
53
+ return undefined;
54
+ }
55
+ /** Record one attempt so a live Host can explain what it decided. */
56
+ note(agent, presetId, outcome) {
57
+ this.attempts.push({
58
+ at: Date.now(),
59
+ ...(agent.id === undefined ? {} : { id: agent.id }),
60
+ ...(presetId === undefined ? {} : { preset: presetId }),
61
+ outcome,
62
+ });
63
+ if (this.attempts.length > ATTEMPT_LIMIT)
64
+ this.attempts.splice(0, this.attempts.length - ATTEMPT_LIMIT);
65
+ }
66
+ /**
67
+ * Move one Agent's preset ancestry onto the live instance's revision.
68
+ *
69
+ * Mirrors `mount()`: `retain()` leases the revision, the re-linked binding
70
+ * takes its own reference, and the lease is released afterwards. A revision
71
+ * the live instance does not have throws (`agent-preset/not-found`,
72
+ * `agent-preset/invalid`) and the caller decides what to report.
73
+ * @param agent - the Agent to re-attach.
74
+ * @param wanted - the preset its Session runs; read from the lost binding when
75
+ * the Session projection is not available on the replacement instance.
76
+ * @returns whether the Agent now resolves that preset on the live instance.
77
+ */
78
+ async relink(agent, wanted) {
79
+ const history = registryHistory();
80
+ const live = history.live;
81
+ const retired = history.retired;
82
+ const presetId = wanted ?? this.boundPreset(agent);
83
+ if (live === undefined) {
84
+ this.note(agent, presetId, "no-live-instance");
85
+ return false;
86
+ }
87
+ if (presetId === undefined) {
88
+ this.note(agent, presetId, "no-preset-id");
89
+ return false;
90
+ }
91
+ // Case A: the instance is the same, but the definition was re-registered
92
+ // (`dsh-agent-preset` restarts whenever `agentPresets` is replaced). The
93
+ // Agent still holds a binding here, so the registry's own bind() path can
94
+ // rebind it; no handle from a dead instance is needed.
95
+ const sameInstance = live.bindings !== undefined
96
+ && scopeKeyOf(agent.ctx, live.bindings) !== undefined;
97
+ if (sameInstance) {
98
+ this.note(agent, presetId, "same-instance");
99
+ return this.remount(live, agent, presetId);
100
+ }
101
+ // Case B: the instance was replaced. Only the retired instance still holds
102
+ // the `ScopeParentBinding` this Agent needs, so it has to be reachable.
103
+ if (retired === undefined || live === retired) {
104
+ this.note(agent, presetId, "no-retired-instance");
105
+ return false;
106
+ }
107
+ if (typeof live.retain !== "function" || typeof live.collect !== "function") {
108
+ return this.refuse("no-retain", "the registry exposes no retain()/collect()");
109
+ }
110
+ const bindings = retired.bindings;
111
+ if (bindings === undefined || typeof bindings.get !== "function") {
112
+ return this.refuse("no-bindings", "the replaced registry exposes no bindings map");
113
+ }
114
+ const key = scopeKeyOf(agent.ctx, bindings);
115
+ if (key === undefined) {
116
+ return this.refuse(`no-key:${agent.id ?? "?"}`, `Agent ${agent.id ?? "<unknown>"} has no binding on the replaced registry instance`);
117
+ }
118
+ const binding = bindings.get(key);
119
+ const parent = binding?.parent;
120
+ if (typeof parent?.rebind !== "function") {
121
+ return this.refuse(`no-rebind:${agent.id ?? "?"}`, `Agent ${agent.id ?? "<unknown>"}: the retained binding exposes no rebind()`);
122
+ }
123
+ const generation = await live.retain(presetId);
124
+ try {
125
+ // The re-linked binding holds its own reference, exactly as join() takes one.
126
+ generation.users = (generation.users ?? 0) + 1;
127
+ try {
128
+ parent.rebind(generation.key);
129
+ }
130
+ catch (error) {
131
+ generation.users -= 1;
132
+ throw error;
133
+ }
134
+ this.adopt(live, bindings, agent, key, parent, generation);
135
+ this.release(live, binding?.generation);
136
+ emitToolsChange(live);
137
+ const composed = typeof live.composedPreset === "function"
138
+ ? live.composedPreset(agent.ctx)
139
+ : generation.mount?.presetId;
140
+ this.note(agent, presetId, composed === presetId ? "re-attached" : `composed=${String(composed)}`);
141
+ return composed === presetId;
142
+ }
143
+ finally {
144
+ // Drop the lease retain() took; the binding keeps its own reference.
145
+ generation.users = (generation.users ?? 1) - 1;
146
+ await live.collect(generation);
147
+ }
148
+ }
149
+ /**
150
+ * Re-mount an Agent on the instance that already knows it.
151
+ *
152
+ * `mount()` is the registry's own entry point: it leases the current revision
153
+ * of `presetId`, and `bind()` sees the existing binding and calls `rebind()`
154
+ * instead of `bindScopeParent()`. That is precisely the path a definition
155
+ * re-registration needs, so the plugin never has to reimplement it.
156
+ * @param live - the registry instance DSH currently publishes.
157
+ * @param agent - the Agent to re-attach.
158
+ * @param presetId - the preset its Session runs.
159
+ * @returns whether the Agent now resolves that preset.
160
+ */
161
+ async remount(live, agent, presetId) {
162
+ if (typeof live.mount !== "function") {
163
+ return this.refuse("no-mount", "the registry exposes no mount() to re-attach a known Agent");
164
+ }
165
+ await live.mount(agent.ctx, presetId);
166
+ const composed = typeof live.composedPreset === "function"
167
+ ? live.composedPreset(agent.ctx)
168
+ : presetId;
169
+ return composed === presetId;
170
+ }
171
+ /** Publish the re-linked binding and release the revision when the Agent dies. */
172
+ adopt(live, bindings, agent, key, parent, generation) {
173
+ const next = { parent, generation };
174
+ // Keep both maps consistent: future bind() calls on either instance rebind
175
+ // instead of trying to join a key that already has a parent.
176
+ bindings.set?.(key, next);
177
+ live.bindings?.set?.(key, next);
178
+ const release = () => {
179
+ live.bindings?.delete?.(key);
180
+ bindings.delete?.(key);
181
+ generation.users = (generation.users ?? 1) - 1;
182
+ void live.collect?.(generation);
183
+ };
184
+ // The registry wires the same release through the Agent's own effect; do it
185
+ // here so the revision cannot outlive the Agent that joined it.
186
+ try {
187
+ agent.ctx.effect?.(() => release, "tool-manager.preset-relink");
188
+ }
189
+ catch {
190
+ // A refused effect only costs a retained revision, never correctness.
191
+ }
192
+ }
193
+ /** Drop the retired instance's reference to the revision it used to hold. */
194
+ release(live, generation) {
195
+ if (generation === undefined || typeof generation.users !== "number")
196
+ return;
197
+ generation.users -= 1;
198
+ void live.collect?.(generation);
199
+ }
200
+ /** Snapshot what the repair can see, so a live Host can be diagnosed. */
201
+ diagnostics() {
202
+ const history = registryHistory();
203
+ const live = history.live;
204
+ const retired = history.retired;
205
+ return {
206
+ live: live !== undefined,
207
+ retired: retired !== undefined && retired !== live,
208
+ liveCapable: typeof live?.retain === "function" && typeof live?.collect === "function",
209
+ retiredCapable: retired?.bindings !== undefined && typeof retired.bindings.get === "function",
210
+ refusals: [...this.refused],
211
+ attempts: [...this.attempts],
212
+ };
213
+ }
214
+ refuse(key, reason) {
215
+ if (!this.reported.has(key)) {
216
+ this.reported.add(key);
217
+ this.refused.push(`${key}: ${reason}`);
218
+ this.options.warn(`tool-manager: cannot re-attach a Session to the reloaded agent preset registry: ${reason}.`);
219
+ }
220
+ return false;
221
+ }
222
+ }
223
+ /**
224
+ * Read the scope key `createScope()` tagged onto a context.
225
+ *
226
+ * The tag is a symbol-keyed property whose value is the key itself. It is not
227
+ * necessarily an own property: `Context.extend()` returns a shadowed object when
228
+ * the context has a use-site shadow, and the tag then lives on the prototype.
229
+ * Walking the whole chain and probing each symbol value against the retired
230
+ * instance's bindings map finds it without hardcoding the symbol's identity.
231
+ */
232
+ function scopeKeyOf(ctx, bindings) {
233
+ if (ctx === null || typeof ctx !== "object")
234
+ return undefined;
235
+ for (let cursor = ctx; cursor !== null; cursor = Object.getPrototypeOf(cursor)) {
236
+ let keys;
237
+ try {
238
+ keys = Reflect.ownKeys(cursor);
239
+ }
240
+ catch {
241
+ return undefined;
242
+ }
243
+ for (const symbol of keys) {
244
+ if (typeof symbol !== "symbol")
245
+ continue;
246
+ let value;
247
+ try {
248
+ value = ctx[symbol];
249
+ }
250
+ catch {
251
+ continue;
252
+ }
253
+ if (value === null || value === undefined)
254
+ continue;
255
+ if (typeof value !== "object" && typeof value !== "function")
256
+ continue;
257
+ let bound;
258
+ try {
259
+ bound = bindings.get(value);
260
+ }
261
+ catch {
262
+ continue;
263
+ }
264
+ if (bound !== undefined)
265
+ return value;
266
+ }
267
+ }
268
+ return undefined;
269
+ }
270
+ /** Emit the invalidation the registry raises after any composition change. */
271
+ function emitToolsChange(live) {
272
+ try {
273
+ live.owner?.emit?.("tools/change");
274
+ }
275
+ catch {
276
+ // Observers are best-effort; the next step resolves tools anyway.
277
+ }
278
+ }
279
+ //# sourceMappingURL=preset-repair.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"preset-repair.js","sourceRoot":"","sources":["../src/preset-repair.ts"],"names":[],"mappings":"AAiIA,MAAM,WAAW,GAAG,MAAM,CAAC,GAAG,CAAC,0CAA0C,CAAC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IAAI,OAAO,MAAM,KAAK,QAAQ;gBAAE,SAAS;YACzC,IAAI,KAAc,CAAC;YACnB,IAAI,CAAC;gBACH,KAAK,GAAI,GAA+B,CAAC,MAAM,CAAC,CAAC;YACnD,CAAC;YAAC,MAAM,CAAC;gBACP,SAAS;YACX,CAAC;YACD,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS;gBAAE,SAAS;YACpD,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,OAAO,KAAK,KAAK,UAAU;gBAAE,SAAS;YACvE,IAAI,KAAc,CAAC;YACnB,IAAI,CAAC;gBACH,KAAK,GAAG,QAAQ,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;YAC9B,CAAC;YAAC,MAAM,CAAC;gBACP,SAAS;YACX,CAAC;YACD,IAAI,KAAK,KAAK,SAAS;gBAAE,OAAO,KAAK,CAAC;QACxC,CAAC;IACH,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,8EAA8E;AAC9E,SAAS,eAAe,CAAC,IAAkB;IACzC,IAAI,CAAC;QACH,IAAI,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC,cAAc,CAAC,CAAC;IACrC,CAAC;IAAC,MAAM,CAAC;QACP,kEAAkE;IACpE,CAAC;AACH,CAAC"}
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,aAAa,CAAS;IAC9B,OAAO,CAAC,iBAAiB,CAAC,CAAa;IACvC;;;;;;OAMG;IACH,OAAO,CAAC,oBAAoB,CAAsB;IAClD,oEAAoE;IACpE,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAqB;IACpD,OAAO,CAAC,oBAAoB,CAAS;IACrC;;;;;OAKG;IACH,OAAO,CAAC,UAAU,CAAqC;IACvD,OAAO,CAAC,iBAAiB,CAAC,CAAa;gBAGpB,GAAG,EAAE,WAAW,EAChB,OAAO,EAAE,gBAAgB,EAC1C,OAAO,EAAE,mBAAmB;IAK9B,KAAK,IAAI,IAAI;IAkBb,MAAM,CAAC,IAAI,EAAE,mBAAmB,GAAG,IAAI;IAcvC,OAAO,CAAC,OAAO;IAyBf,OAAO,CAAC,SAAS;IAcjB,OAAO,CAAC,QAAQ;IAIhB,OAAO,CAAC,MAAM;IAId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