@fractalsynapse/dsh-chapters 0.2.30 → 0.2.32

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/lib/tools.js CHANGED
@@ -14,7 +14,7 @@ import { REPAIR_CLASS_ALIASES, resolveRepairClasses } from "./repair.js";
14
14
  import { readDurableSession } from "./auto-save.js";
15
15
  import { makeRestoreCommand } from "./restore-command.js";
16
16
  import * as path from 'node:path';
17
- import { candidateTotals, estimateTokens, toolResultCandidates } from "./render.js";
17
+ import { candidateTotals, defersAtArchive, toolResultCandidates } from "./render.js";
18
18
  import { detectPlans } from "./plans.js";
19
19
  import { makeHeaderParentReader, queryTopics, renderRulesBlock } from "./session-rules.js";
20
20
  import { rulesCommand } from "./rules-commands.js";
@@ -35,6 +35,15 @@ const jsonOutput = (render) => ({
35
35
  render: (_args, value) => [{ type: 'text', text: render(value) }],
36
36
  });
37
37
  const CALLER_MISSING = { ok: false, reason: 'no calling agent: this tool runs only inside an agent session' };
38
+ /**
39
+ * #330 — the shape of a budget receipt the MODEL may see: the size of the NOTICE the
40
+ * plugin measured against its allowance, both properties of an artifact being written.
41
+ * The admission inputs (`windowTokens`, `headerBoundTokens`) measure the live session —
42
+ * a gauge the model cannot read for itself and would only learn to guess with — so they
43
+ * are withheld here deliberately. The refusal REASON carries the same discipline (see
44
+ * continue-core); human door text and the logs may carry the full probe.
45
+ */
46
+ const noticeReceipt = (b) => ({ usedTokens: b.usedTokens, allowanceTokens: b.allowanceTokens });
38
47
  function callerOf(exec) {
39
48
  const agent = exec.agent;
40
49
  return agent ?? CALLER_MISSING;
@@ -112,9 +121,15 @@ export function buildChaptersTools(ctx, store, config) {
112
121
  // the parent's log is copied; a seeded `plan/mode` is a synthetic fact about
113
122
  // the boundary, and the kernel's own setup events still append after it
114
123
  // (measured: notice@0 → plan/mode@1 → end-seed@2 → permission/sandbox/…).
124
+ // #319 part 2 (invariant-2 amendment 2026-11-05): the SEED carries STATE events only.
125
+ // A seeded user/message at surface[0] is what poisoned every continuation child against
126
+ // the host's own cold-load validator (issue #314: the kernel records its first-request
127
+ // header AFTER our notice, and its reader then refuses the log). The TOC notice is now
128
+ // AUTHORED as the child's first turn — the position every loadable session has always
129
+ // had for its first content: inside an open turn, after the kernel's own header.
115
130
  const handle = await ctx.agents.create({
116
131
  sessionId,
117
- seed: [noticeEvent, ...modeEvents],
132
+ seed: [...modeEvents],
118
133
  inheritedEventCount: 0,
119
134
  meta: { cwd, isSeeded: false, ...(mountPreset !== undefined && mountPreset !== null ? { agentPreset: mountPreset } : {}) },
120
135
  ...(callerOptions.provider !== undefined ? { agentOptions: callerOptions } : {}),
@@ -154,11 +169,82 @@ export function buildChaptersTools(ctx, store, config) {
154
169
  catch (error) {
155
170
  ctx.logger?.warn?.(`dsh-chapters: child title refused (${String(error)}); child remains untitled`);
156
171
  }
157
- finally {
158
- // The live handle is ours only until the child is handed to the user:
159
- // holding it blocks their resume ("already owned by an active write
160
- // handle", measured r3). Dispose after the live-work, keep the session.
161
- await handle.dispose?.();
172
+ // #319: author the TOC as the child's first turn — LOUD when the seam is absent. A
173
+ // child that never receives its archive believes it has none; refusing an un-birth-able
174
+ // child beats gifting the user a confidently confused session (#54's silent-fallback
175
+ // lesson, aimed this time at authoring).
176
+ // Dispose FIRST, author SECOND — the r3 law in a new place: while we hold the create
177
+ // handle the child is "already owned by an active write handle", and a followup queued
178
+ // into that grip never starts a turn (measured on the plans rig: a 9-event child with
179
+ // zero user/messages — a silent unbirth, precisely what the loud-absence rule exists
180
+ // to catch). The prompt loop's authoring pattern is get-after-release; birth follows it.
181
+ await handle.dispose?.();
182
+ try {
183
+ const nd = noticeEvent.data;
184
+ const msg = {
185
+ id: `${sessionId}-toc`,
186
+ role: 'user',
187
+ ...(nd.source !== undefined ? { source: nd.source } : {}),
188
+ ...(nd.content !== undefined ? { content: nd.content } : {}),
189
+ };
190
+ const agents = ctx.agents;
191
+ // A warm child answers the registry directly; a cold one needs the SDK's own rail:
192
+ // resume -> author -> HOLD the lease (a disposed holder silently drops the queued
193
+ // followup: measured, the child persisted 10 events and zero user messages), and
194
+ // release only when its first turn/end lands or the safety window expires. The
195
+ // browser can then take the session; a hold-race at worst shows the host's own
196
+ // 'active write handle' once and the next attempt lands.
197
+ const warm = agents.get?.(sessionId);
198
+ const authorOf = (x) => {
199
+ if (x == null)
200
+ return null;
201
+ const direct = typeof x.followup === 'function' ? x.followup : null;
202
+ const inner = typeof x.agent?.followup === 'function' ? x.agent.followup : null;
203
+ return direct ?? inner;
204
+ };
205
+ let receiver = warm ?? null;
206
+ let fn = authorOf(warm);
207
+ let lease = null;
208
+ if (fn === null) {
209
+ if (typeof agents.resume !== 'function')
210
+ throw new Error('no live agent and no agents.resume seam — cannot author the birth TOC on this host (#319)');
211
+ lease = (await agents.resume({
212
+ resumeSessionId: sessionId,
213
+ ...(callerOptions.provider !== undefined ? { agentOptions: callerOptions } : {}),
214
+ setup: async (agentCtx) => {
215
+ const presets = ctx.get?.('agentPresets');
216
+ if (presets?.mount !== undefined)
217
+ await presets.mount(agentCtx, mountPreset);
218
+ },
219
+ })) ?? null;
220
+ receiver = lease?.agent ?? lease;
221
+ fn = authorOf(lease);
222
+ }
223
+ if (fn === null)
224
+ throw new Error(`no followup seam reachable for ${sessionId} (warm=${JSON.stringify(Object.keys((warm ?? {}))).slice(0, 80)}, lease=${lease === null ? 'absent' : JSON.stringify(Object.keys(lease)).slice(0, 80)}) — refusing a child that would never see its TOC (#319)`);
225
+ fn.call(receiver, msg);
226
+ if (lease !== null) {
227
+ const release = async () => { try {
228
+ await lease.dispose?.();
229
+ }
230
+ catch { /* the lease is best-effort after authoring */ } };
231
+ // LIFECYCLE, measured (the enrich leg, twice): the browser ATTACHES to the child
232
+ // while its birth turn runs; disposing our lease at turn/end kills the agent out
233
+ // from under that bound view — the composer never returns (420s/240s stalls).
234
+ // Release-at-birth-starves the queued followup (10-event silent unbirth). There is
235
+ // no safe mid-process release point for a handle the UI may be bound to — which is
236
+ // exactly why the SDK server's sessions map holds its handles for the process
237
+ // lifetime (server.ts getOrCreateSession; no release path at all). We mirror it:
238
+ // the lease lives until the host process does. Cross-RESUME contention (r3) was
239
+ // measured for handles over never-started sessions; a child that has run a turn is
240
+ // the SDK's own case, and the reload leg proves the restart side clean.
241
+ void release; // retained: no release point is safe while a view may be bound
242
+ }
243
+ }
244
+ catch (error) {
245
+ // The child EXISTS and is durable even if authoring fails — a half-born child still
246
+ // has chapters cited by its own TOC-less state; refuse loudly, name the repair.
247
+ throw new Error(`birth TOC authoring failed for ${sessionId}: ${String(error?.message ?? error)}`);
162
248
  }
163
249
  return { warnings: attach.warnings };
164
250
  },
@@ -168,9 +254,10 @@ export function buildChaptersTools(ctx, store, config) {
168
254
  // ---------------------------------------------------------------- segment
169
255
  const chaptersSegment = defineTool({
170
256
  name: 'chapters_segment',
171
- description: 'Facts for planning a chapter archive of THIS session: the completed-turn archive ceiling, '
172
- + 'every tool result with its real size, and the chapters already in the registry. '
173
- + 'Returns ranges for you to propose in chapters_continue — you never write chapter text; the plugin renders it from the log.',
257
+ description: 'Facts for planning a chapter archive of THIS session: the completed-turn ceiling, which tool '
258
+ + 'results will be cited as file references versus repeated inline, and the chapters already in '
259
+ + 'the registry. Returns ranges for you to propose in chapters_continue — you never write chapter '
260
+ + 'text; the plugin renders it from the log.',
174
261
  parameters: {},
175
262
  output: jsonOutput((value) => JSON.stringify(value, null, 1)),
176
263
  async execute(_args, exec) {
@@ -195,8 +282,6 @@ export function buildChaptersTools(ctx, store, config) {
195
282
  title: p.title,
196
283
  status: p.status,
197
284
  resultSeq: p.resultSeq,
198
- bytes: p.bytes,
199
- estimatedTokens: estimateTokens(p.text),
200
285
  outline: p.outline,
201
286
  verdict: p.verdict === null ? null : p.verdict.slice(0, 200),
202
287
  });
@@ -218,10 +303,11 @@ export function buildChaptersTools(ctx, store, config) {
218
303
  : { planHint: 'a submitted plan is a topic boundary: the chapter that carries it ENDS there, and its title becomes the chapter title' }),
219
304
  // fresh literals, not the ToolResultCandidate interface: anonymous
220
305
  // object types carry the implicit index signature JsonValue needs.
221
- // #61: the candidate list is CAPPED and says so. The field version returned 49,932 characters
222
- // while also reporting `Omitted 275266 bytes` — ~81K est tokens into a 32K-class window, asking
223
- // the model to keep/drop-judge a list it had not received. Ranking is by size descending, so the
224
- // cap removes the SMALL entries and the big ones a real decision turns on stay visible.
306
+ // #61: the candidate list is CAPPED and says so — but #330 took the SIZE
307
+ // NUMBERS out of it: per-result bytes/token estimates read to the model as a
308
+ // fuel gauge, and the cap line's "KB withheld" was the same quantity the
309
+ // caller cannot verify. The list says what is on it and what the archive will
310
+ // reference by default; the plugin does the measuring.
225
311
  ...(() => {
226
312
  const range = { title: '', summary: '', startSeq: 0, endSeq: ceiling };
227
313
  const cap = config.segmentCandidateCapTokens ?? 4000;
@@ -230,17 +316,18 @@ export function buildChaptersTools(ctx, store, config) {
230
316
  : toolResultCandidates(below, range);
231
317
  const totals = candidateTotals(below, range);
232
318
  const withheld = Math.max(0, totals.count - kept.length);
233
- const withheldBytes = Math.max(0, totals.bytes - kept.reduce((m, c) => m + c.bytes, 0));
319
+ const floor = config.toolResultDeferFloorTokens ?? 200;
234
320
  return {
235
- toolResults: kept.map((c) => ({ seq: c.seq, toolName: c.toolName, bytes: c.bytes, estimatedTokens: c.estimatedTokens, excerpt: c.excerpt })),
236
- toolResultsReport: `showing ${kept.length} of ${totals.count} candidates by size, ${(withheldBytes / 1024).toFixed(0)} KB withheld`
237
- + (cap > 0 ? ` (segmentCandidateCapTokens=${cap})` : ' (uncapped)'),
321
+ // `deferred` is the SAME decision the renderer makes (one predicate,
322
+ // defersAtArchive): this result's full text will be cited as a file path
323
+ // in its chapter rather than repeated. An archive fact, not a session one.
324
+ toolResults: kept.map((c) => ({ seq: c.seq, toolName: c.toolName, excerpt: c.excerpt, deferred: defersAtArchive(c.estimatedTokens, floor) })),
325
+ toolResultsReport: `listing ${kept.length} of ${totals.count} tool results${withheld > 0 ? ` (${String(withheld)} smaller ones omitted by the cap${cap > 0 ? `, segmentCandidateCapTokens=${cap}` : ''})` : ''}`,
238
326
  };
239
327
  })(),
240
328
  existingChapters: callerState.chapters.map((c) => ({
241
329
  number: c.number, path: c.path, title: c.title, startSeq: c.startSeq, endSeq: c.endSeq,
242
330
  })),
243
- budgetHint: { continuationBudgetRatio: config.continuationBudgetRatio, chapterTokenTarget: config.chapterTokenTarget },
244
331
  };
245
332
  },
246
333
  });
@@ -249,12 +336,12 @@ export function buildChaptersTools(ctx, store, config) {
249
336
  name: 'chapters_continue',
250
337
  description: 'Archive this conversation as verbatim Markdown chapters and open a NEW session that starts from their '
251
338
  + 'table of contents plus your handoff note. Supply event ranges (startSeq/endSeq) — never chapter text; '
252
- + 'the plugin renders bodies from the session log. This session is left untouched; the child gets its own '
253
- + 'cache and can reload any chapter with read. Oversized tool results defer to reference files by default; '
254
- + 'toolResultOverrides marks the exceptions you want kept inline (it still writes the artifact).',
339
+ + 'the plugin renders bodies from the session log. This session is left untouched; the child can reload any '
340
+ + 'chapter with read. Large tool results are cited as file references in the chapter by default; '
341
+ + 'toolResultOverrides names the few you want repeated inline instead (the file is still written).',
255
342
  parameters: {
256
343
  title: { type: 'string', required: true, description: 'Name for the continued session.' },
257
- handoffNote: { type: 'string', required: true, description: 'State of play for the child: what was in progress, decisions held, the next step. Budget-checked as part of the notice, never silently truncated.' },
344
+ handoffNote: { type: 'string', required: true, description: 'State of play for the child: what was in progress, decisions held, the next step. It reaches the child whole, never clipped.' },
258
345
  chapters: {
259
346
  type: 'array',
260
347
  required: true,
@@ -278,7 +365,7 @@ export function buildChaptersTools(ctx, store, config) {
278
365
  additionalProperties: false,
279
366
  properties: {
280
367
  seq: { type: 'integer', required: true, description: 'The tool result event seq (from chapters_segment toolResults).' },
281
- inline: { type: 'boolean', required: true, description: 'Keep inline (true) or defer (false), overriding the size default for this one result.' },
368
+ inline: { type: 'boolean', required: true, description: 'Repeat this one result inline (true) or as a file reference (false), overriding the archive default for it.' },
282
369
  },
283
370
  },
284
371
  },
@@ -318,7 +405,7 @@ export function buildChaptersTools(ctx, store, config) {
318
405
  ...(result.presetUsed !== undefined ? { presetUsed: result.presetUsed } : {}),
319
406
  ...(result.chapters !== undefined ? { chapters: result.chapters } : {}),
320
407
  ...(result.warnings !== undefined && result.warnings.length > 0 ? { warnings: result.warnings } : {}),
321
- ...(result.budget !== undefined ? { budget: result.budget } : {}),
408
+ ...(result.budget !== undefined ? { budget: noticeReceipt(result.budget) } : {}),
322
409
  };
323
410
  }
324
411
  catch (error) {
@@ -327,7 +414,7 @@ export function buildChaptersTools(ctx, store, config) {
327
414
  return {
328
415
  ok: false,
329
416
  reason: refusal.reason ?? 'refused',
330
- ...(refusal.budget !== undefined ? { budget: refusal.budget } : {}),
417
+ ...(refusal.budget !== undefined ? { budget: noticeReceipt(refusal.budget) } : {}),
331
418
  ...(refusal.warnings !== undefined && refusal.warnings.length > 0 ? { warnings: refusal.warnings } : {}),
332
419
  };
333
420
  }
@@ -339,11 +426,11 @@ export function buildChaptersTools(ctx, store, config) {
339
426
  const chaptersFork = defineTool({
340
427
  name: 'chapters_fork',
341
428
  description: 'Open a SIBLING session citing the same chapter archive this one already has — nothing new is '
342
- + 'archived, no files written, no numbers spent. Use for trying a genuinely different approach '
343
- + 'while the current session keeps working. Your handoff note says what the sibling should do.',
429
+ + 'archived, no files written, no chapter numbers consumed. Use for trying a genuinely different '
430
+ + 'approach while the current session keeps working. Your handoff note says what the sibling should do.',
344
431
  parameters: {
345
432
  title: { type: 'string', required: true, description: 'Name for the forked session.' },
346
- handoffNote: { type: 'string', required: true, description: 'What the sibling is for — its whole context is the archive TOC plus this note.' },
433
+ handoffNote: { type: 'string', required: true, description: 'What the sibling is for — it starts from the archive TOC plus this note.' },
347
434
  },
348
435
  output: jsonOutput((value) => JSON.stringify(value, null, 1)),
349
436
  async execute(args, exec) {
@@ -377,13 +464,13 @@ export function buildChaptersTools(ctx, store, config) {
377
464
  ok: true,
378
465
  ...(result.childSessionId !== undefined ? { childSessionId: result.childSessionId } : {}),
379
466
  ...(result.presetUsed !== undefined ? { presetUsed: result.presetUsed } : {}),
380
- ...(result.budget !== undefined ? { budget: result.budget } : {}),
467
+ ...(result.budget !== undefined ? { budget: noticeReceipt(result.budget) } : {}),
381
468
  };
382
469
  }
383
470
  catch (error) {
384
471
  const refusal = refusalResult(error);
385
472
  if (refusal !== null) {
386
- return { ok: false, reason: refusal.reason ?? 'refused', ...(refusal.budget !== undefined ? { budget: refusal.budget } : {}) };
473
+ return { ok: false, reason: refusal.reason ?? 'refused', ...(refusal.budget !== undefined ? { budget: noticeReceipt(refusal.budget) } : {}) };
387
474
  }
388
475
  return { ok: false, reason: `chapters_fork failed: ${error?.stack ?? String(error)}`.slice(0, 800) };
389
476
  }
@@ -679,7 +766,7 @@ export function buildChaptersTools(ctx, store, config) {
679
766
  + 'Pass a topic or keyword query; raise maxTokens to see more of the ranked list. Results are file paths readable with the read tool.',
680
767
  parameters: {
681
768
  query: { type: 'string', required: true, description: 'Topic or keyword query.' },
682
- maxTokens: { type: 'number', description: 'Token budget for the result list (default 400; raise to page deeper).' },
769
+ maxTokens: { type: 'number', description: 'Cap on the returned list length (default 400; raise to page deeper).' },
683
770
  },
684
771
  output: jsonOutput((value) => JSON.stringify(value, null, 1)),
685
772
  async execute(args, exec) {
@@ -757,17 +844,17 @@ export function buildChaptersTools(ctx, store, config) {
757
844
  });
758
845
  const chaptersArtifact = defineTool({
759
846
  name: 'chapters_artifact',
760
- description: 'Query a stored artifact (a tool result too large to sit in context — deferred blobs and arrival-stored documents alike) '
847
+ description: 'Query a stored artifact (a large tool result or arrival-stored document the archive keeps as a file) '
761
848
  + 'WITHOUT loading it whole: action "toc" = heading map with line numbers (structured/markdown files), '
762
849
  + '"search" = query (regex or phrase) → small matched blocks with line numbers, "read" = exact line range. '
763
- + 'path accepts the artifacts/… path or the bare sha256 from the stub line.',
850
+ + 'path accepts the artifacts/… path or the bare sha256 from the reference line.',
764
851
  parameters: {
765
852
  path: { type: 'string', required: true, description: 'Artifact reference from the stub: artifacts/<xx>/<sha>.txt path or the 64-hex sha.' },
766
853
  action: { type: 'string', required: true, description: 'One of: toc | search | read.' },
767
854
  query: { type: 'string', description: 'Required for search: regex or literal phrase (case-insensitive).' },
768
855
  offset: { type: 'number', description: 'read: first line (1-based). Default 1.' },
769
856
  limit: { type: 'number', description: 'read: line count (hard cap 400).' },
770
- maxTokens: { type: 'number', description: 'search: budget for returned blocks (default 400).' },
857
+ maxTokens: { type: 'number', description: 'search: how many matched blocks to return (default 400).' },
771
858
  },
772
859
  output: jsonOutput((value) => JSON.stringify(value, null, 1)),
773
860
  async execute(args, exec) {
@@ -851,12 +938,12 @@ export function buildChaptersTools(ctx, store, config) {
851
938
  const chaptersRules = defineTool({
852
939
  name: 'chapters_rules',
853
940
  description: 'Assemble the rules that govern a task: the approved project tier plus this session tree\u2019s '
854
- + 'captured session rules, verbatim, within budget. Run it BEFORE starting a task. The answer '
941
+ + 'captured session rules, verbatim. Run it BEFORE starting a task. The answer '
855
942
  + 'names what it withheld, so "you are seeing all of them" is a fact rather than a guess.',
856
943
  parameters: {
857
944
  query: { type: 'string', required: true, description: 'What the session is about to do, in a sentence or two \u2014 it selects relevance.' },
858
945
  scope: { type: 'string', description: "'all' (default) or 'project' to see only the shared tier a branch would inherit." },
859
- maxTokens: { type: 'number', description: 'Token ceiling for this answer (defaults to coreRulesBudgetTokens).' },
946
+ maxTokens: { type: 'number', description: 'Cap on the returned rules text (default: the configured core-rules budget).' },
860
947
  },
861
948
  output: jsonOutput((value) => JSON.stringify(value, null, 1)),
862
949
  async execute(args, exec) {
@@ -1045,6 +1132,15 @@ export function buildChaptersTools(ctx, store, config) {
1045
1132
  const restoreCommand = makeRestoreCommand({ store, config, portsFor, runRepair });
1046
1133
  return { segment: chaptersSegment, chaptersContinue, chaptersFork, chaptersSearch, chaptersArtifact, chaptersRulePropose, chaptersRules, forkCommand, continueCommand, saveCommand, repairCommand, restoreCommand };
1047
1134
  }
1135
+ /**
1136
+ * The realm-side registrar (#330): the seven `chapters_*` tools and the three
1137
+ * continuation door commands mount on the plane that requested them — ONLY the
1138
+ * `chapters-tools` row inside the preset composition calls this, from
1139
+ * `src/tools-row.ts`. The host plane never calls it: a tool registered on the host
1140
+ * plane rides EVERY session's request whatever preset composes (measured in the #319
1141
+ * e2e logs as `chapters_*` schemas inside `standard`-preset headers), which is the leak
1142
+ * #330 exists to close.
1143
+ */
1048
1144
  export function registerChaptersTools(ctx, store, config) {
1049
1145
  const built = buildChaptersTools(ctx, store, config);
1050
1146
  const disposeSegment = ctx.tools.register(built.segment);
@@ -1058,11 +1154,10 @@ export function registerChaptersTools(ctx, store, config) {
1058
1154
  const commands = ctx.get?.('commands');
1059
1155
  if (commands?.register !== undefined) {
1060
1156
  try {
1061
- // Both deterministic doors register on the same seam. Keep EVERY disposer: a loop
1062
- // that overwrote `disposeCommand` would leak the first registration and unregister
1063
- // only whichever door was added last.
1157
+ // Keep EVERY disposer: a loop that overwrote `disposeCommand` would leak the
1158
+ // first registration and unregister only whichever door was added last.
1064
1159
  const commandDisposers = [];
1065
- for (const def of [built.forkCommand, built.continueCommand, built.saveCommand, built.repairCommand, built.restoreCommand]) {
1160
+ for (const def of [built.forkCommand, built.continueCommand, built.saveCommand]) {
1066
1161
  const disposer = commands.register(def);
1067
1162
  if (typeof disposer === 'function')
1068
1163
  commandDisposers.push(disposer);
@@ -1089,4 +1184,30 @@ export function registerChaptersTools(ctx, store, config) {
1089
1184
  disposeCommand?.();
1090
1185
  };
1091
1186
  }
1187
+ /**
1188
+ * The host-side registrar (#330): `/chapters-repair` and `/chapters-restore` stay
1189
+ * operator-side so a broken chapters archive is fixable FROM ANY SESSION — a poisoned
1190
+ * chapters child may not compose its realm at all, and the restore door (#319) is the
1191
+ * documented way in. Command text is not a model prompt surface; these registrations
1192
+ * are human reach, not agent attention, which is the line #330 draws.
1193
+ */
1194
+ export function registerChaptersRepairRestore(ctx, store, config) {
1195
+ const built = buildChaptersTools(ctx, store, config);
1196
+ const disposers = [];
1197
+ const commands = ctx.get?.('commands');
1198
+ if (commands?.register !== undefined) {
1199
+ try {
1200
+ for (const def of [built.repairCommand, built.restoreCommand]) {
1201
+ const disposer = commands.register(def);
1202
+ if (typeof disposer === 'function')
1203
+ disposers.push(disposer);
1204
+ }
1205
+ }
1206
+ catch (error) {
1207
+ ctx.logger?.warn?.(`dsh-chapters: repair/restore command registration failed (${String(error)})`);
1208
+ }
1209
+ }
1210
+ return () => { for (const d of disposers)
1211
+ d(); };
1212
+ }
1092
1213
  //# sourceMappingURL=tools.js.map