dsh-project-mcp 0.3.1 → 0.4.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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-project-mcp",
3
3
  "description": "Per-project MCP servers for DeepSeek Harness: mounts the MCP servers a project declares into the sessions working in it",
4
- "version": "0.3.1",
4
+ "version": "0.4.1",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
7
7
  "types": "lib/index.d.ts",
@@ -43,6 +43,22 @@
43
43
  "./cordis.patch.yml": "./cordis.patch.yml",
44
44
  "./package.json": "./package.json"
45
45
  },
46
+ "scripts": {
47
+ "build": "tsc -p tsconfig.json && tsdown && node scripts/wrap-client.mjs",
48
+ "prepack": "pnpm build",
49
+ "typecheck": "tsc -p tsconfig.json",
50
+ "test": "vitest run",
51
+ "coverage": "vitest run --coverage",
52
+ "e2e": "node scripts/e2e-boot.mjs",
53
+ "check": "tsc -p tsconfig.json && tsdown && node scripts/wrap-client.mjs && vitest run --coverage && node scripts/audit.mjs",
54
+ "smoke": "node scripts/live-smoke.mjs",
55
+ "design:parity": "node scripts/design-parity.mjs",
56
+ "test:bun": "bun test tests",
57
+ "smoke:bun": "bun scripts/live-smoke.mjs",
58
+ "audit": "node scripts/audit.mjs",
59
+ "audit:bun": "bun scripts/audit.mjs",
60
+ "check:config": "node scripts/check-config.mjs"
61
+ },
46
62
  "dsh": {
47
63
  "bundle": {
48
64
  "patch": "./cordis.patch.yml"
@@ -83,20 +99,5 @@
83
99
  "typescript": "^7.0.2",
84
100
  "unrun": "^0.3.1",
85
101
  "vitest": "^5.0.2"
86
- },
87
- "scripts": {
88
- "build": "tsc -p tsconfig.json && tsdown && node scripts/wrap-client.mjs",
89
- "typecheck": "tsc -p tsconfig.json",
90
- "test": "vitest run",
91
- "coverage": "vitest run --coverage",
92
- "e2e": "node scripts/e2e-boot.mjs",
93
- "check": "tsc -p tsconfig.json && tsdown && node scripts/wrap-client.mjs && vitest run --coverage && node scripts/audit.mjs",
94
- "smoke": "node scripts/live-smoke.mjs",
95
- "design:parity": "node scripts/design-parity.mjs",
96
- "test:bun": "bun test tests",
97
- "smoke:bun": "bun scripts/live-smoke.mjs",
98
- "audit": "node scripts/audit.mjs",
99
- "audit:bun": "bun scripts/audit.mjs",
100
- "check:config": "node scripts/check-config.mjs"
101
102
  }
102
- }
103
+ }
package/src/activation.ts CHANGED
@@ -5,17 +5,20 @@
5
5
  * every tool the project owns. This module keeps the *presentation* list small
6
6
  * without touching the registry:
7
7
  *
8
- * - the usage counters seed a **baseline** of tools the project actually calls
9
- * ({@link seedFromUsage}) — they are offered directly from the first step on;
8
+ * - the usage counters seed a **baseline** of tools the project has called — one
9
+ * call is enough ({@link seedFromUsage}) — and they are offered directly from
10
+ * the first step on;
10
11
  * - the newest task text ranks the project's mounted tools with BM25, and the
11
12
  * best matches are offered through a **sticky window** that holds one offered
12
- * set across several steps ({@link advanceAutoOffer});
13
+ * set across the session's steps ({@link advanceAutoOffer});
13
14
  * - the rest are discovered through the `mcp_search_tools` tool this module
14
15
  * registers in the agent scope, which **activates** the matches for the next
15
16
  * step ({@link activate});
16
- * - a tool that is never called falls out again ({@link pruneIdle}), and a
17
- * compaction ends the session's activations while the counter baseline stays
18
- * ({@link onCompaction});
17
+ * - a compaction ends the session's activations that no call backs, while the
18
+ * ones the model really called and the counter baseline stay
19
+ * ({@link onCompaction}); idle pruning ({@link pruneIdle}) stays available
20
+ * through a positive `toolIdleMs`, and the shipped `0` leaves it off, so the
21
+ * compaction boundary is the one place that shrinks the offered set;
19
22
  * - the agent's own `system-prompt/assemble` listener puts the active schemas
20
23
  * back into the assembled request ({@link withActiveTools}).
21
24
  *
@@ -39,14 +42,30 @@ import type { OfferedTool, ServerUsage, SessionTools, ToolPolicy } from './types
39
42
  /** `true` while the session may offer MCP tools through search + activation. */
40
43
  export const DEFAULT_ACTIVATION_ENABLED = true
41
44
 
42
- /** Tools seeded into the baseline from the durable counters. */
43
- export const DEFAULT_ACTIVATION_SEEDED = 8
45
+ /**
46
+ * Tools seeded into the baseline from the durable counters. A project with a
47
+ * few dozen mounted tools calls more than a handful of them, so the cap sits
48
+ * above the narrow window that used to evict a tool the project really uses.
49
+ */
50
+ export const DEFAULT_ACTIVATION_SEEDED = 16
44
51
 
45
- /** Calls one tool needs in the counters before it is seeded. */
46
- export const DEFAULT_ACTIVATION_MIN_CALLS = 5
52
+ /**
53
+ * Calls one tool needs in the counters before it is seeded. One call is enough:
54
+ * a tool the project actually uses enters the durable baseline the first time it
55
+ * is called, so the baseline grows from real usage instead of waiting for the
56
+ * counters to reach an arbitrary threshold.
57
+ */
58
+ export const DEFAULT_ACTIVATION_MIN_CALLS = 1
47
59
 
48
- /** How long a session-activated tool survives without a call (`0` disables). */
49
- export const DEFAULT_TOOL_IDLE_MS = 1_800_000
60
+ /**
61
+ * How long a session-activated tool survives without a call (`0` disables).
62
+ *
63
+ * The shipped `0` keeps a searched tool offered for the rest of the session:
64
+ * dropping it mid-session shrinks the request and rewrites the prompt prefix,
65
+ * which invalidates the provider's prefix cache, so time-based removal stays an
66
+ * explicit opt-in.
67
+ */
68
+ export const DEFAULT_TOOL_IDLE_MS = 0
50
69
 
51
70
  /** Matches one `mcp_search_tools` call activates when it omits `limit`. */
52
71
  export const DEFAULT_SEARCH_LIMIT = 8
@@ -80,11 +99,15 @@ export const MAX_AUTO_ACTIVATION_LIMIT = 50
80
99
  * Extra user messages a context-driven offer survives after the one that ranked
81
100
  * it; `0` keeps only that message. The offering set is recomputed when the task
82
101
  * context moves, so this is what holds one tool list across several steps.
102
+ *
103
+ * The shipped window spans a whole session: dropping an offer mid-session
104
+ * rewrites the prompt prefix and invalidates the provider's prefix cache, so the
105
+ * context tier grows and only resets at a compaction.
83
106
  */
84
- export const DEFAULT_AUTO_ACTIVATION_STICKY_STEPS = 2
107
+ export const DEFAULT_AUTO_ACTIVATION_STICKY_STEPS = 100
85
108
 
86
109
  /** Hard cap on the sticky window, however the config asks for more. */
87
- export const MAX_AUTO_ACTIVATION_STICKY_STEPS = 20
110
+ export const MAX_AUTO_ACTIVATION_STICKY_STEPS = 1000
88
111
 
89
112
  /**
90
113
  * Serialized size of the MCP surface a session may offer directly before this
@@ -241,24 +264,39 @@ export interface SessionEventLike {
241
264
  * One session's activation state.
242
265
  *
243
266
  * `baseline` is the counter-seeded set and outlives a compaction; `active` holds
244
- * the names this session activated through search, each with the epoch
245
- * milliseconds of its last touch, and is what idle pruning and compaction clear.
246
- * Both are read-only because every transition returns a new state.
267
+ * the names this session activated through search or the context tier, each with
268
+ * the epoch milliseconds of its last touch, and is what idle pruning and
269
+ * compaction trim. `used` records the calls the session made for this plugin's
270
+ * own namespace — the evidence a compaction keeps an activation by, because a
271
+ * tool the model called is one the session really uses. It is cumulative for the
272
+ * session and never bounded, so the compaction boundary shrinks the offers no
273
+ * call backs and never shrinks a used tool again.
274
+ *
275
+ * Every field is read-only because every transition returns a new state.
247
276
  */
248
277
  export interface ActivationState {
249
278
  /** Public names the durable counters proved hot; always offered. */
250
279
  readonly baseline: ReadonlySet<string>
251
280
  /** Session-activated public names mapped to their last touch. */
252
281
  readonly active: ReadonlyMap<string, number>
282
+ /**
283
+ * `mcp__` names this session called at least once and the durable baseline
284
+ * does not already keep. Read by nothing but {@link onCompaction}, and
285
+ * cumulative for the session: it is deliberately never bounded, so with the
286
+ * shipped `DEFAULT_TOOL_IDLE_MS` of `0` nothing else removes a name and a tool
287
+ * the session used stays offered for the rest of the session, across every
288
+ * further compaction.
289
+ */
290
+ readonly used: ReadonlySet<string>
253
291
  }
254
292
 
255
293
  /**
256
294
  * Build one session's state.
257
295
  * @param baseline - counter-seeded public names; defaults to none.
258
- * @returns an empty active set over that baseline.
296
+ * @returns an empty active set and an empty used record over that baseline.
259
297
  */
260
298
  export function createActivationState(baseline: Iterable<string> = []): ActivationState {
261
- return { baseline: new Set(baseline), active: new Map() }
299
+ return { baseline: new Set(baseline), active: new Map(), used: new Set() }
262
300
  }
263
301
 
264
302
  /** How {@link seedFromUsage} reads the durable counters. */
@@ -324,13 +362,20 @@ export function activate(
324
362
  active ??= new Map(state.active)
325
363
  active.set(name, at)
326
364
  }
327
- return active === undefined ? state : { baseline: state.baseline, active }
365
+ return active === undefined ? state : { baseline: state.baseline, active, used: state.used }
328
366
  }
329
367
 
330
368
  /**
331
- * Refresh the freshness of a tool the session actually called. A call is what
332
- * keeps a session-activated tool offered; a name that is not active (a baseline
333
- * tool, or a tool the model called by name without activating it) is untouched.
369
+ * Record a call — the freshness of a session-activated tool and the evidence a
370
+ * compaction keeps it by.
371
+ *
372
+ * `active` is refreshed exactly as before: a call is what keeps a
373
+ * session-activated tool offered. `used` records the call itself, but only for
374
+ * this plugin's own namespace: the core tools (`read`, `bash`, …) ride the same
375
+ * `tools/result` hook, and they are no part of a session's MCP activation state.
376
+ * A baseline name is not recorded either — the durable baseline already keeps it
377
+ * offered, so recording the call would only make a compaction look like it
378
+ * changed something.
334
379
  *
335
380
  * @param state - activation state before the call.
336
381
  * @param name - public name of the called tool.
@@ -339,10 +384,22 @@ export function activate(
339
384
  */
340
385
  export function noteUse(state: ActivationState, name: string, at: number): ActivationState {
341
386
  const previous = state.active.get(name)
342
- if (previous === undefined || previous === at) return state
343
- const active = new Map(state.active)
344
- active.set(name, at)
345
- return { baseline: state.baseline, active }
387
+ const refresh = previous !== undefined && previous !== at
388
+ // `used` post-dates the interface: a state an embedder built before the field
389
+ // existed reads as a session that has used nothing, so the read is optional
390
+ // and the write coalesces an empty record instead of throwing.
391
+ const already = state.used?.has(name) === true
392
+ const record = name.startsWith('mcp__') && !state.baseline.has(name) && !already
393
+ if (!refresh && !record) return state
394
+ const active = refresh ? new Map(state.active) : undefined
395
+ active?.set(name, at)
396
+ const used = record ? new Set(state.used ?? []) : undefined
397
+ used?.add(name)
398
+ return {
399
+ baseline: state.baseline,
400
+ active: active ?? state.active,
401
+ used: used ?? state.used ?? new Set(),
402
+ }
346
403
  }
347
404
 
348
405
  /**
@@ -350,6 +407,13 @@ export function noteUse(state: ActivationState, name: string, at: number): Activ
350
407
  * The baseline is never pruned: it comes from the durable counters, not from the
351
408
  * session. `idleMs <= 0` disables pruning.
352
409
  *
410
+ * A positive `idleMs` is an explicit opt-in to *forgetting*: an evicted name
411
+ * leaves the used record with the offer it was about, so the sweep is final —
412
+ * a later compaction cannot read the call back and resurrect what time already
413
+ * dropped. A name the model needs again is activated again through search. The
414
+ * names still inside the window keep their record, and a sweep that evicts
415
+ * nothing returns its input.
416
+ *
353
417
  * @param state - activation state at `now`.
354
418
  * @param now - epoch milliseconds of the sweep.
355
419
  * @param idleMs - age at which a tool falls out.
@@ -358,23 +422,68 @@ export function noteUse(state: ActivationState, name: string, at: number): Activ
358
422
  export function pruneIdle(state: ActivationState, now: number, idleMs: number): ActivationState {
359
423
  if (idleMs <= 0 || state.active.size === 0) return state
360
424
  let active: Map<string, number> | undefined
425
+ let used: Set<string> | undefined
361
426
  for (const [name, at] of state.active) {
362
427
  if (now - at < idleMs) continue
363
428
  active ??= new Map(state.active)
364
429
  active.delete(name)
430
+ // `used` post-dates the interface, so a legacy state simply has no record to
431
+ // forget; a record that is there is copied before it is dropped.
432
+ if (state.used?.has(name) !== true) continue
433
+ used ??= new Set(state.used ?? [])
434
+ used.delete(name)
365
435
  }
366
- return active === undefined ? state : { baseline: state.baseline, active }
436
+ return active === undefined
437
+ ? state
438
+ : { baseline: state.baseline, active, used: used ?? state.used ?? new Set() }
367
439
  }
368
440
 
369
441
  /**
370
- * End the session's activations — a compaction rewrote the conversation they
371
- * belonged to — while keeping the counter baseline.
442
+ * End the session's activations that no call backs, at the compaction boundary.
443
+ *
444
+ * A compaction rewrites the conversation, so the provider's prompt prefix is
445
+ * recomputed anyway: this is the one boundary where dropping a tool costs no
446
+ * cache, which is why idle time is off by default and why this is the only place
447
+ * the offered set shrinks. Only the part the session never used goes — an offer
448
+ * from a context match or a search that the model did not act on. A tool this
449
+ * session did call is one it really uses, so it stays active, stamped with its
450
+ * last touch; evicting it would charge a re-discovery step for a tool the
451
+ * session demonstrably needs. A used name that was never activated falls back to
452
+ * the compaction's own clock. The counter baseline is never pruned.
453
+ *
454
+ * The used record is cumulative for the session and deliberately never bounded:
455
+ * with the shipped `DEFAULT_TOOL_IDLE_MS` of `0` nothing else removes a name, so
456
+ * a tool the session used stays offered for the rest of the session, across every
457
+ * further compaction. This boundary shrinks the offers no call backs — it never
458
+ * shrinks one the session used again.
459
+ *
372
460
  * @param state - activation state before the compaction.
373
- * @returns the updated state, or the input when no session tool was active.
461
+ * @param at - epoch milliseconds of the compaction.
462
+ * @returns the updated state, or the input when nothing was active or used, or
463
+ * when the rebuild is equivalent to what is already there — a caller compares
464
+ * by identity to tell a real change from a boundary that changed nothing.
374
465
  */
375
- export function onCompaction(state: ActivationState): ActivationState {
376
- if (state.active.size === 0) return state
377
- return { baseline: state.baseline, active: new Map() }
466
+ export function onCompaction(state: ActivationState, at: number): ActivationState {
467
+ // `used` post-dates the interface: a state an embedder built before the field
468
+ // existed reads as a session that has used nothing.
469
+ const used = state.used ?? new Set<string>()
470
+ if (state.active.size === 0 && used.size === 0) return state
471
+ const active = new Map<string, number>()
472
+ for (const name of used) active.set(name, state.active.get(name) ?? at)
473
+ // A second compaction with no new call rebuilds exactly the map already there,
474
+ // and an equal-but-different object would read as a change to every caller
475
+ // that compares by identity. Same names and same stamps: the input comes back.
476
+ if (active.size === state.active.size) {
477
+ let equivalent = true
478
+ for (const [name, stamp] of active) {
479
+ if (state.active.get(name) !== stamp) {
480
+ equivalent = false
481
+ break
482
+ }
483
+ }
484
+ if (equivalent) return state
485
+ }
486
+ return { baseline: state.baseline, active, used: state.used ?? new Set() }
378
487
  }
379
488
 
380
489
  /**
@@ -858,7 +967,18 @@ export function autoOffers(state: AutoOfferState): readonly string[] {
858
967
  return entries.map((entry) => entry.name)
859
968
  }
860
969
 
861
- /** Whether two context-driven states describe the same offered set and history. */
970
+ /**
971
+ * Whether two context-driven states offer the same names.
972
+ *
973
+ * Only the presented names are compared, never the advance stamp and never the
974
+ * per-name window stamps, so an advance that changes nothing hands back the
975
+ * previous state without ticking the advance counter: the sticky window ages by
976
+ * changes of the offered set, not by input count. This was reviewed as a
977
+ * possible stickiness off-by-one and cannot produce a wrong offered set — a
978
+ * stall can only hold names the ranking has just chosen again, and it ends at
979
+ * the first advance whose set differs — so do not re-chase an age here before
980
+ * reading `advanceAutoOffer`.
981
+ */
862
982
  function sameAutoOffer(left: AutoOfferState, right: AutoOfferState): boolean {
863
983
  const leftNames = autoPresentedNames(left)
864
984
  const rightNames = autoPresentedNames(right)
@@ -1207,10 +1327,10 @@ export interface ActivationWiringOptions {
1207
1327
  */
1208
1328
  readonly onActivated?: (names: readonly string[], step: number) => void
1209
1329
  /**
1210
- * Told that a compaction ended the session's activations, so the caller can
1211
- * drop the step records that belong to them. Absent leaves the records in
1212
- * place, which only means a later activation of the same name may carry the
1213
- * step of the offer the compaction removed.
1330
+ * Told that a compaction ended some of the session's activations, so the
1331
+ * caller can drop the step records that belonged to the ones it removed.
1332
+ * Absent leaves the records in place, which only means a later activation of
1333
+ * the same name may carry the step of the offer the compaction removed.
1214
1334
  */
1215
1335
  readonly onCompaction?: () => void
1216
1336
  /** Context-driven state to start from; defaults to an empty state. */
@@ -1463,10 +1583,11 @@ export function installActivation(options: ActivationWiringOptions): () => void
1463
1583
  const observe = (_session: unknown, event: SessionEventLike): void => {
1464
1584
  try {
1465
1585
  if (event?.type === 'compaction/end') {
1466
- options.setState(onCompaction(options.state()))
1467
- // The step records belong to activations a compaction has just dropped,
1468
- // so they go with them: a name activated again after this is stamped
1469
- // with the step it returns on, not with the one it left on.
1586
+ options.setState(onCompaction(options.state(), Date.now()))
1587
+ // The step records of the activations the compaction just dropped go
1588
+ // with them: a name activated again after this is stamped with the step
1589
+ // it returns on, not with the one it left on, while a tool the session
1590
+ // really used keeps the step its offer happened on.
1470
1591
  options.onCompaction?.()
1471
1592
  // A compaction rewrote the conversation the offers belonged to, so the
1472
1593
  // context tier starts over; the counter baseline is untouched.
package/src/bridge.ts CHANGED
@@ -33,7 +33,11 @@
33
33
  * it level with the project's live set: the set is re-read on every trigger,
34
34
  * the batch is replaced as a whole (released before the replacement is
35
35
  * registered), and the re-entry every registration forces on the sync through
36
- * `tools/change` is owned rather than left to tear the batch down.
36
+ * `tools/change` is owned rather than left to tear the batch down. Because that
37
+ * event is emitted once per entry registered and once per entry disposed, the
38
+ * subscription takes {@link ForwardBatch.note} — which folds a whole burst into
39
+ * one queued pass — and never {@link ForwardBatch.sync}, whose work belongs to
40
+ * the frame that asked for it.
37
41
  *
38
42
  * The module is import-free of `@deepseek-ai/dsh-tools` on purpose, exactly like
39
43
  * {@link ./activation.ts}: the registry, definition and schema surfaces are
@@ -320,8 +324,30 @@ export interface ForwardBatchOptions {
320
324
  * @returns the exact releaser that drops the whole batch.
321
325
  */
322
326
  readonly register: (names: readonly string[]) => () => void
327
+ /**
328
+ * Report a failure thrown by a pass this batch ran on its own.
329
+ *
330
+ * A pass requested by {@link ForwardBatch.note} runs off the caller's stack:
331
+ * the registry call that announced the change has already returned, and so
332
+ * has every frame that could have propagated the failure. Without this the
333
+ * batch would go quiet — no forwarder, and no trace of why.
334
+ * @param error - what the scheduled pass threw.
335
+ */
336
+ readonly onError?: (error: unknown) => void
323
337
  }
324
338
 
339
+ /**
340
+ * How many synchronous passes one {@link ForwardBatch.sync} may run.
341
+ *
342
+ * Two is the ordinary ceiling: a pass that replaced the batch is re-entered once
343
+ * by its own announcements and short-circuits on the second round, and a pass
344
+ * that found the set unchanged exits on the first. The extra room is for a set
345
+ * that genuinely moved while the batch was registering — and the ceiling itself
346
+ * is what stops a registry that keeps moving under the batch from holding the
347
+ * event loop for as long as it likes.
348
+ */
349
+ export const MAX_SYNC_PASSES = 4
350
+
325
351
  /**
326
352
  * One session's live forwarding batch, kept level with the project's live tools.
327
353
  *
@@ -334,7 +360,8 @@ export interface ForwardBatchOptions {
334
360
  * which the live first copy refuses as a duplicate. A bridge that steps aside
335
361
  * for a duplicate (it must, for the session's own tools) then drops those names
336
362
  * silently, and a full pass records `namesIn` as the whole set, so the loss is
337
- * frozen for every later pass. That is the defect this class exists to close.
363
+ * frozen for every later pass. That is the first defect this class exists to
364
+ * close.
338
365
  *
339
366
  * So: a pass requested from inside a pass only marks the batch dirty, and the
340
367
  * frame that owns the batch runs one more pass when it is complete — which is
@@ -342,6 +369,23 @@ export interface ForwardBatchOptions {
342
369
  * the old batch is released **before** the new one is registered, because one
343
370
  * layer holds one entry per name: registering over a live batch would refuse
344
371
  * every name it already had.
372
+ *
373
+ * Owning the re-entry is not enough on its own, and the shape of the event is
374
+ * why. Replacing a batch of N entries announces 2·N changes — one per disposal
375
+ * and one per registration — and the event carries no origin, so every session
376
+ * watching the stream runs a pass for every one of them, and every pass begins
377
+ * by projecting the project's whole catalog, which the registry answers by deep
378
+ * cloning each visible definition's JSON schema. The registry per pass is what
379
+ * makes that cost real: one MCP generation swap was measured holding the event
380
+ * loop for the full 54 seconds of a CPU profile (47% of its samples inside this
381
+ * sync, 52% in the collector the projections feed), while the plugin's own
382
+ * frames were 0.46% of it. So {@link note} is the seat a `tools/change`
383
+ * subscription takes, not {@link sync}: a change that arrives during a pass is
384
+ * absorbed by it, and a burst that arrives between passes costs **one** queued
385
+ * pass however many events it carries. A stale forwarder is safe in the window
386
+ * that opens — it resolves the project entry at call time and fails closed when
387
+ * there is none (`forwarder`) — and every read path brings the batch level
388
+ * before it reads, so a reader never waits for the queue.
345
389
  */
346
390
  export class ForwardBatch {
347
391
  /** The names the live batch was registered for; `undefined` before the first pass. */
@@ -352,6 +396,8 @@ export class ForwardBatch {
352
396
  #building = false
353
397
  /** Whether a pass asked for while {@link #building} still needs a run. */
354
398
  #again = false
399
+ /** Whether a scheduled pass is already waiting for a burst of changes. */
400
+ #queued = false
355
401
 
356
402
  constructor(private readonly options: ForwardBatchOptions) {}
357
403
 
@@ -367,11 +413,12 @@ export class ForwardBatch {
367
413
  }
368
414
 
369
415
  /**
370
- * Bring the session's layer level with the project's live tool set.
416
+ * Bring the session's layer level with the project's live tool set, now.
371
417
  *
372
418
  * Cheap when it already is: an unchanged set short-circuits and leaves the
373
419
  * live batch — and its generation of definitions — untouched. Re-entrant
374
- * while registering: see the class note.
420
+ * while registering, and bounded to {@link MAX_SYNC_PASSES} synchronous
421
+ * rounds so no registry state can hold the caller's frame: see the class note.
375
422
  * @returns nothing; a failure from the probe or the registry propagates.
376
423
  */
377
424
  sync(): void {
@@ -379,17 +426,47 @@ export class ForwardBatch {
379
426
  this.#again = true
380
427
  return
381
428
  }
429
+ // A queued pass would read the very registry this one is about to read, so
430
+ // it is dropped here rather than left to repeat the probe.
431
+ this.#queued = false
382
432
  this.#building = true
383
433
  try {
384
- do {
434
+ for (let pass = 0; pass < MAX_SYNC_PASSES; pass += 1) {
385
435
  this.#again = false
386
436
  this.#syncOnce()
387
- } while (this.#again)
437
+ if (!this.#again) return
438
+ }
439
+ // Still moving after a full round: hand the rest to the queue. A registry
440
+ // that keeps changing under the batch must not hold the caller's frame.
441
+ this.#schedule(true)
388
442
  } finally {
389
443
  this.#building = false
390
444
  }
391
445
  }
392
446
 
447
+ /**
448
+ * Note that the registry changed, and bring the batch level — off this stack.
449
+ *
450
+ * This is the seat a `tools/change` subscription takes, and the reason it is
451
+ * not {@link sync}: the event is emitted once per entry registered and once
452
+ * per entry disposed, from inside the registry's own insertion and removal,
453
+ * so one MCP generation swap is a burst of thousands. A change that arrives
454
+ * while a pass is running is absorbed by that pass — it re-reads the set it is
455
+ * replacing before it returns — and a burst that arrives between passes costs
456
+ * one pass: the first queues, every later one folds into it.
457
+ *
458
+ * Nothing reads a stale layer for it. Every read path brings the batch level
459
+ * first (`src/runtime.ts`, `mountedSchemas`), and the queued pass has run
460
+ * before any turn that could read the layer at all.
461
+ */
462
+ note(): void {
463
+ if (this.#building) {
464
+ this.#again = true
465
+ return
466
+ }
467
+ this.#schedule(false)
468
+ }
469
+
393
470
  /**
394
471
  * Drop the live batch: the session keeps no forwarder, and the next
395
472
  * {@link sync} starts from nothing rather than amending a stale set.
@@ -399,15 +476,45 @@ export class ForwardBatch {
399
476
  * session is subscribed to that event; a pass re-entered from there must not
400
477
  * resurrect the batch it is watching being dropped. So the guard is held for
401
478
  * the whole release, and the pass it queues is discarded rather than run.
479
+ *
480
+ * The guard is *held*, not taken: a drop that runs inside a pass — a detach
481
+ * driven from a listener, a scope torn down under a registration — restores
482
+ * the pass's own `building` rather than clearing it. Clearing it there would
483
+ * let the next `tools/change` start a nested pass inside a frame that still
484
+ * owns one, which is exactly the re-entry this class exists to own.
402
485
  */
403
486
  drop(): void {
487
+ const building = this.#building
404
488
  this.#building = true
405
489
  try {
406
490
  this.#releaseBatch()
407
491
  } finally {
408
- this.#building = false
492
+ this.#building = building
409
493
  this.#again = false
494
+ this.#queued = false
495
+ }
496
+ }
497
+
498
+ /**
499
+ * Queue the one deferred pass a burst of changes needs.
500
+ * @param yielding - run it on the timer queue rather than the microtask queue.
501
+ * A pass that overran {@link MAX_SYNC_PASSES} asks for this: a chain of
502
+ * microtasks still starves timers and I/O, a round of timers does not.
503
+ */
504
+ #schedule(yielding: boolean): void {
505
+ if (this.#queued) return
506
+ this.#queued = true
507
+ const run = (): void => {
508
+ if (!this.#queued) return
509
+ this.#queued = false
510
+ try {
511
+ this.sync()
512
+ } catch (error) {
513
+ this.options.onError?.(error)
514
+ }
410
515
  }
516
+ if (yielding) setTimeout(run, 0)
517
+ else queueMicrotask(run)
411
518
  }
412
519
 
413
520
  /** One pass: read the project's set, then replace the batch when it moved. */
@@ -456,15 +456,15 @@ export const zh: Record<UiKey, string> = {
456
456
  configActivationSeeded: '预置工具数',
457
457
  configActivationSeededHint: '在计数累计之前,从第一步就提供的工具数;0 表示不预置',
458
458
  configActivationMinCalls: '固定所需调用次数',
459
- configActivationMinCallsHint: '计数器在调用达到此次数后直接固定该工具',
459
+ configActivationMinCallsHint: '调用达到此次数后,计数器会直接固定该工具;0 表示只要有过调用就固定',
460
460
  configToolIdleMs: '工具闲置超时(毫秒)',
461
- configToolIdleMsHint: '工具超过此时长未使用将从请求中移除',
461
+ configToolIdleMsHint: '工具超过此时长未使用将从请求中移除;0 表示整个会话都保留',
462
462
  configGuidanceEnabled: '系统提示指引',
463
463
  configGuidanceEnabledHint: '将本插件的使用说明注入会话提示',
464
464
  configActivationAutoLimit: '自动激活上限',
465
465
  configActivationAutoLimitHint: '计数器最多可自行加入的工具数(0–50)',
466
466
  configActivationAutoStickySteps: '黏滞步数',
467
- configActivationAutoStickyStepsHint: '刚使用过的工具无论计数如何都保持固定的步数(0–20)',
467
+ configActivationAutoStickyStepsHint: '按任务上下文提供的工具额外保留多少条用户消息;0 表示仅保留当前消息(0–1000)',
468
468
  configActivationToolBudgetChars: '工具预算(字符)',
469
469
  configActivationToolBudgetCharsHint: '单次请求携带的工具模式字符预算(≥ 1000)',
470
470
  configAllowGlobalWrite: '允许全局写入',
@@ -876,15 +876,15 @@ export const ru: Record<UiKey, string> = {
876
876
  configActivationSeeded: 'Предустановленные инструменты',
877
877
  configActivationSeededHint: 'Инструменты, предлагаемые с первого шага, до накопления счётчиков; 0 — не предлагать',
878
878
  configActivationMinCalls: 'Вызовов до закрепления',
879
- configActivationMinCallsHint: 'После стольких вызовов счётчики закрепляют инструмент напрямую',
879
+ configActivationMinCallsHint: 'После стольких вызовов счётчики закрепляют инструмент напрямую; 0 — закрепить любой инструмент с записанным вызовом',
880
880
  configToolIdleMs: 'Тайм-аут простоя инструмента (мс)',
881
- configToolIdleMsHint: 'Инструмент, не использованный за это время, исключается из запроса',
881
+ configToolIdleMsHint: 'Инструмент, не использованный за это время, исключается из запроса; 0 — оставить его на всю сессию',
882
882
  configGuidanceEnabled: 'Подсказки в системном промпте',
883
883
  configGuidanceEnabledHint: 'Добавлять рабочие заметки плагина в промпт сессии',
884
884
  configActivationAutoLimit: 'Лимит автоактивации',
885
885
  configActivationAutoLimitHint: 'Максимум инструментов, которые счётчики могут добавить сами (0–50)',
886
886
  configActivationAutoStickySteps: 'Шагов закрепления',
887
- configActivationAutoStickyStepsHint: 'Сколько шагов только что использованный инструмент остаётся закреплённым независимо от счётчиков (0–20)',
887
+ configActivationAutoStickyStepsHint: 'Сколько пользовательских сообщений предложенный по контексту инструмент остаётся предложенным; 0 — только для этого сообщения (0–1000)',
888
888
  configActivationToolBudgetChars: 'Бюджет инструментов (символы)',
889
889
  configActivationToolBudgetCharsHint: 'Бюджет в символах на схемы инструментов в одном запросе (≥ 1000)',
890
890
  configAllowGlobalWrite: 'Глобальная запись',