dsh-project-mcp 0.4.0 → 0.4.2

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/index.js CHANGED
@@ -882,6 +882,7 @@ function installActivation(options) {
882
882
  if (next === tracker.state) return;
883
883
  tracker.state = next;
884
884
  options.setAutoState?.(next);
885
+ options.onOfferedChanged?.();
885
886
  };
886
887
  /** Every name the session's explicit activation and context-driven tiers offer. */
887
888
  const offeredNames = () => {
@@ -931,6 +932,7 @@ function installActivation(options) {
931
932
  * continuation's value comes back by identity.
932
933
  */
933
934
  const contain = (result) => {
935
+ if (!Array.isArray(result.tools)) return result;
934
936
  const foreign = options.foreign?.() ?? NO_FOREIGN;
935
937
  if (foreign.size === 0) return result;
936
938
  const kept = result.tools.filter((tool) => !foreign.has(tool.name));
@@ -954,9 +956,13 @@ function installActivation(options) {
954
956
  return foreign.size === 0 ? surface : surface.filter((schema) => !foreign.has(schema.name));
955
957
  };
956
958
  const merge = (result) => {
959
+ const policy = options.policy?.() ?? DEFAULT_TOOL_POLICY;
960
+ if (!Array.isArray(result.tools)) {
961
+ if (policy.mode === "disclosure") advance();
962
+ return result;
963
+ }
957
964
  const surface = wholeSurface();
958
965
  if (surface.length === 0) return contain(result);
959
- const policy = options.policy?.() ?? DEFAULT_TOOL_POLICY;
960
966
  if (policy.mode === "off") {
961
967
  const mounted = options.available();
962
968
  if (mounted.length === 0) return contain(result);
@@ -998,6 +1004,7 @@ function installActivation(options) {
998
1004
  tracker.state = resetAutoOffer(tracker.state);
999
1005
  tracker.calls = [];
1000
1006
  tracker.changed = false;
1007
+ options.onOfferedChanged?.();
1001
1008
  return;
1002
1009
  }
1003
1010
  if (event?.type === "user/message") {
@@ -1025,6 +1032,7 @@ function installActivation(options) {
1025
1032
  activate: (names) => {
1026
1033
  recordActivated(names);
1027
1034
  options.setState(activate(options.state(), names, Date.now()));
1035
+ options.onOfferedChanged?.();
1028
1036
  },
1029
1037
  ...options.searchLimit === void 0 ? {} : { defaultLimit: options.searchLimit }
1030
1038
  });
@@ -2494,11 +2502,14 @@ const FORWARDED_TO = Symbol("dsh-project-mcp.forwarded-to");
2494
2502
  * dispatch would apply pre-execute listeners and guards twice.
2495
2503
  * @param project - the definition to forward, read for its surface.
2496
2504
  * @param lookup - resolves the current project definition of this name.
2505
+ * @param deferred - whether this forwarder asks for deferred loading, so the
2506
+ * model's tool list leaves it out while the registry keeps it callable.
2497
2507
  * @returns the definition to register in a session's layer.
2498
2508
  */
2499
- function forwarder(project, lookup) {
2509
+ function forwarder(project, lookup, deferred) {
2500
2510
  return Object.assign({
2501
2511
  ...project,
2512
+ ...deferred ? { deferLoading: true } : {},
2502
2513
  async execute(args, exec) {
2503
2514
  const live = lookup();
2504
2515
  if (live === void 0) throw new Error(`the project's "${project.name}" is no longer registered; the shared instance was released or replaced`);
@@ -2523,7 +2534,7 @@ function forwardProjectTools(options) {
2523
2534
  const project = options.registry.get(name, options.project);
2524
2535
  if (project === void 0) continue;
2525
2536
  try {
2526
- disposes.push(tools.register(forwarder(project, () => options.registry.get(name, options.project))));
2537
+ disposes.push(tools.register(forwarder(project, () => options.registry.get(name, options.project), options.deferred?.(name) === true)));
2527
2538
  } catch {
2528
2539
  continue;
2529
2540
  }
@@ -2549,7 +2560,8 @@ function forwardProjectTools(options) {
2549
2560
  * which the live first copy refuses as a duplicate. A bridge that steps aside
2550
2561
  * for a duplicate (it must, for the session's own tools) then drops those names
2551
2562
  * silently, and a full pass records `namesIn` as the whole set, so the loss is
2552
- * frozen for every later pass. That is the defect this class exists to close.
2563
+ * frozen for every later pass. That is the first defect this class exists to
2564
+ * close.
2553
2565
  *
2554
2566
  * So: a pass requested from inside a pass only marks the batch dirty, and the
2555
2567
  * frame that owns the batch runs one more pass when it is complete — which is
@@ -2557,17 +2569,38 @@ function forwardProjectTools(options) {
2557
2569
  * the old batch is released **before** the new one is registered, because one
2558
2570
  * layer holds one entry per name: registering over a live batch would refuse
2559
2571
  * every name it already had.
2572
+ *
2573
+ * Owning the re-entry is not enough on its own, and the shape of the event is
2574
+ * why. Replacing a batch of N entries announces 2·N changes — one per disposal
2575
+ * and one per registration — and the event carries no origin, so every session
2576
+ * watching the stream runs a pass for every one of them, and every pass begins
2577
+ * by projecting the project's whole catalog, which the registry answers by deep
2578
+ * cloning each visible definition's JSON schema. The registry per pass is what
2579
+ * makes that cost real: one MCP generation swap was measured holding the event
2580
+ * loop for the full 54 seconds of a CPU profile (47% of its samples inside this
2581
+ * sync, 52% in the collector the projections feed), while the plugin's own
2582
+ * frames were 0.46% of it. So {@link note} is the seat a `tools/change`
2583
+ * subscription takes, not {@link sync}: a change that arrives during a pass is
2584
+ * absorbed by it, and a burst that arrives between passes costs **one** queued
2585
+ * pass however many events it carries. A stale forwarder is safe in the window
2586
+ * that opens — it resolves the project entry at call time and fails closed when
2587
+ * there is none (`forwarder`) — and every read path brings the batch level
2588
+ * before it reads, so a reader never waits for the queue.
2560
2589
  */
2561
2590
  var ForwardBatch = class {
2562
2591
  options;
2563
2592
  /** The names the live batch was registered for; `undefined` before the first pass. */
2564
2593
  #namesIn = void 0;
2594
+ /** The names the live batch registered as deferred; `undefined` with no live batch. */
2595
+ #deferredIn = void 0;
2565
2596
  /** Disposer of the live registration batch; `undefined` while none is live. */
2566
2597
  #release = void 0;
2567
2598
  /** Whether an owning frame is inside {@link sync}, registering right now. */
2568
2599
  #building = false;
2569
2600
  /** Whether a pass asked for while {@link #building} still needs a run. */
2570
2601
  #again = false;
2602
+ /** Whether a scheduled pass is already waiting for a burst of changes. */
2603
+ #queued = false;
2571
2604
  constructor(options) {
2572
2605
  this.options = options;
2573
2606
  }
@@ -2582,11 +2615,12 @@ var ForwardBatch = class {
2582
2615
  return this.#namesIn;
2583
2616
  }
2584
2617
  /**
2585
- * Bring the session's layer level with the project's live tool set.
2618
+ * Bring the session's layer level with the project's live tool set, now.
2586
2619
  *
2587
2620
  * Cheap when it already is: an unchanged set short-circuits and leaves the
2588
2621
  * live batch — and its generation of definitions — untouched. Re-entrant
2589
- * while registering: see the class note.
2622
+ * while registering, and bounded to {@link MAX_SYNC_PASSES} synchronous
2623
+ * rounds so no registry state can hold the caller's frame: see the class note.
2590
2624
  * @returns nothing; a failure from the probe or the registry propagates.
2591
2625
  */
2592
2626
  sync() {
@@ -2594,17 +2628,42 @@ var ForwardBatch = class {
2594
2628
  this.#again = true;
2595
2629
  return;
2596
2630
  }
2631
+ this.#queued = false;
2597
2632
  this.#building = true;
2598
2633
  try {
2599
- do {
2634
+ for (let pass = 0; pass < 4; pass += 1) {
2600
2635
  this.#again = false;
2601
2636
  this.#syncOnce();
2602
- } while (this.#again);
2637
+ if (!this.#again) return;
2638
+ }
2639
+ this.#schedule(true);
2603
2640
  } finally {
2604
2641
  this.#building = false;
2605
2642
  }
2606
2643
  }
2607
2644
  /**
2645
+ * Note that the registry changed, and bring the batch level — off this stack.
2646
+ *
2647
+ * This is the seat a `tools/change` subscription takes, and the reason it is
2648
+ * not {@link sync}: the event is emitted once per entry registered and once
2649
+ * per entry disposed, from inside the registry's own insertion and removal,
2650
+ * so one MCP generation swap is a burst of thousands. A change that arrives
2651
+ * while a pass is running is absorbed by that pass — it re-reads the set it is
2652
+ * replacing before it returns — and a burst that arrives between passes costs
2653
+ * one pass: the first queues, every later one folds into it.
2654
+ *
2655
+ * Nothing reads a stale layer for it. Every read path brings the batch level
2656
+ * first (`src/runtime.ts`, `mountedSchemas`), and the queued pass has run
2657
+ * before any turn that could read the layer at all.
2658
+ */
2659
+ note() {
2660
+ if (this.#building) {
2661
+ this.#again = true;
2662
+ return;
2663
+ }
2664
+ this.#schedule(false);
2665
+ }
2666
+ /**
2608
2667
  * Drop the live batch: the session keeps no forwarder, and the next
2609
2668
  * {@link sync} starts from nothing rather than amending a stale set.
2610
2669
  * Idempotent.
@@ -2613,26 +2672,57 @@ var ForwardBatch = class {
2613
2672
  * session is subscribed to that event; a pass re-entered from there must not
2614
2673
  * resurrect the batch it is watching being dropped. So the guard is held for
2615
2674
  * the whole release, and the pass it queues is discarded rather than run.
2675
+ *
2676
+ * The guard is *held*, not taken: a drop that runs inside a pass — a detach
2677
+ * driven from a listener, a scope torn down under a registration — restores
2678
+ * the pass's own `building` rather than clearing it. Clearing it there would
2679
+ * let the next `tools/change` start a nested pass inside a frame that still
2680
+ * owns one, which is exactly the re-entry this class exists to own.
2616
2681
  */
2617
2682
  drop() {
2683
+ const building = this.#building;
2618
2684
  this.#building = true;
2619
2685
  try {
2620
2686
  this.#releaseBatch();
2621
2687
  } finally {
2622
- this.#building = false;
2688
+ this.#building = building;
2623
2689
  this.#again = false;
2690
+ this.#queued = false;
2624
2691
  }
2625
2692
  }
2693
+ /**
2694
+ * Queue the one deferred pass a burst of changes needs.
2695
+ * @param yielding - run it on the timer queue rather than the microtask queue.
2696
+ * A pass that overran {@link MAX_SYNC_PASSES} asks for this: a chain of
2697
+ * microtasks still starves timers and I/O, a round of timers does not.
2698
+ */
2699
+ #schedule(yielding) {
2700
+ if (this.#queued) return;
2701
+ this.#queued = true;
2702
+ const run = () => {
2703
+ if (!this.#queued) return;
2704
+ this.#queued = false;
2705
+ try {
2706
+ this.sync();
2707
+ } catch (error) {
2708
+ this.options.onError?.(error);
2709
+ }
2710
+ };
2711
+ if (yielding) setTimeout(run, 0);
2712
+ else queueMicrotask(run);
2713
+ }
2626
2714
  /** One pass: read the project's set, then replace the batch when it moved. */
2627
2715
  #syncOnce() {
2628
2716
  const names = this.options.names();
2629
2717
  if (names === void 0) return;
2630
- if (this.#namesIn !== void 0 && sameNames(this.#namesIn, names)) return;
2718
+ const deferred = new Set(this.options.deferred?.() ?? []);
2719
+ if (this.#namesIn !== void 0 && sameNames(this.#namesIn, names) && sameNameSet(this.#deferredIn, deferred)) return;
2631
2720
  try {
2632
2721
  this.#releaseBatch();
2633
2722
  } catch {}
2634
- this.#release = this.options.register(names);
2723
+ this.#release = this.options.register(names, deferred);
2635
2724
  this.#namesIn = names;
2725
+ this.#deferredIn = deferred;
2636
2726
  }
2637
2727
  /**
2638
2728
  * Release the live batch and forget it.
@@ -2644,6 +2734,7 @@ var ForwardBatch = class {
2644
2734
  const release = this.#release;
2645
2735
  this.#release = void 0;
2646
2736
  this.#namesIn = void 0;
2737
+ this.#deferredIn = void 0;
2647
2738
  release?.();
2648
2739
  }
2649
2740
  };
@@ -2685,6 +2776,22 @@ function sameNames(left, right) {
2685
2776
  return left.length === right.length && left.every((name, index) => name === right[index]);
2686
2777
  }
2687
2778
  /**
2779
+ * Whether two deferred-name sets are the same set.
2780
+ *
2781
+ * The batch short-circuits a pass whose forwarded names did not move, and it
2782
+ * must not do that when the *deferred* subset moved instead: the flag rides in
2783
+ * the registered definition, so a stale batch presents a stale answer. Order
2784
+ * carries no meaning here, hence a set comparison rather than {@link sameNames}.
2785
+ * @param left - the deferred set of the live batch; `undefined` with no live batch.
2786
+ * @param right - the deferred set this pass read.
2787
+ * @returns whether the two describe the same names.
2788
+ */
2789
+ function sameNameSet(left, right) {
2790
+ if (left === void 0 || left.size !== right.size) return false;
2791
+ for (const name of right) if (!left.has(name)) return false;
2792
+ return true;
2793
+ }
2794
+ /**
2688
2795
  * One ring per project root, oldest event first.
2689
2796
  *
2690
2797
  * Kept per root because two projects of one host are two histories; the history
@@ -4125,6 +4232,7 @@ var ProjectMcpRuntime = class {
4125
4232
  messageParams: { projectRoot: request.projectRoot }
4126
4233
  };
4127
4234
  policy.setPin(request.projectRoot, request.tool, request.pinned);
4235
+ this.refreshPresentation(request.projectRoot);
4128
4236
  this.notify();
4129
4237
  return {
4130
4238
  ok: true,
@@ -4163,6 +4271,7 @@ var ProjectMcpRuntime = class {
4163
4271
  messageParams: { projectRoot: request.projectRoot }
4164
4272
  };
4165
4273
  policy.setMode(request.projectRoot, request.mode);
4274
+ this.refreshPresentation(request.projectRoot);
4166
4275
  this.notify();
4167
4276
  return {
4168
4277
  ok: true,
@@ -4228,6 +4337,65 @@ var ProjectMcpRuntime = class {
4228
4337
  return this.options.policy?.forProject(projectRoot) ?? DEFAULT_TOOL_POLICY;
4229
4338
  }
4230
4339
  /**
4340
+ * Re-apply the presentation of every session working in one project.
4341
+ *
4342
+ * A pin or a mode is read live by the panel and by the guidance, but the
4343
+ * forwarders carry their `deferLoading` flag from the pass that registered
4344
+ * them, so the sessions of that project have to run one — off the caller's
4345
+ * stack, like every other change note.
4346
+ * @param projectRoot - the project whose policy just moved.
4347
+ */
4348
+ refreshPresentation(projectRoot) {
4349
+ for (const state of this.states.values()) {
4350
+ if (state.projectRoot !== projectRoot) continue;
4351
+ state.bridge?.batch.note();
4352
+ }
4353
+ }
4354
+ /**
4355
+ * The names one session's presentation offers the model right now.
4356
+ *
4357
+ * The counterpart of the assembly wiring's own `offeredNames`, read where the
4358
+ * presentation lives outside that assembly — in the bridge's forwarders. It is
4359
+ * the counter-seeded baseline, the session's activations, the context tier's
4360
+ * window, and the project's pins; the same four sources the assembly-side
4361
+ * `wanted` set is built from, so the two cannot drift.
4362
+ * @param state - the session to read.
4363
+ * @returns the offered public names.
4364
+ */
4365
+ offeredNamesOf(state) {
4366
+ const names = new Set(presentedNames(this.seedActivation(state)));
4367
+ const auto = state.auto;
4368
+ if (auto !== void 0) for (const name of autoPresentedNames(auto)) names.add(name);
4369
+ for (const pin of this.policyFor(state.projectRoot).pins) names.add(pin);
4370
+ return names;
4371
+ }
4372
+ /**
4373
+ * The names one session presents as deferred: what it mounts that it does not
4374
+ * offer.
4375
+ *
4376
+ * Empty when there is nothing to defer — activation off, `direct`, or a
4377
+ * surface that fits the budget — because deferring a schema the request would
4378
+ * have carried anyway only makes the declaration list harder to read, and the
4379
+ * prefix-cache argument for it is gone. The budget is the same
4380
+ * {@link surfaceChars} reading the panel and the assembly gate use, so the
4381
+ * deferred set and the "hidden" number a panel shows are one decision.
4382
+ * @param state - the session whose presentation is being registered.
4383
+ * @returns the names whose forwarders carry `deferLoading`, in registry order.
4384
+ */
4385
+ deferredNamesOf(state) {
4386
+ if (!(this.config.activationEnabled ?? true)) return [];
4387
+ const policy = this.policyFor(state.projectRoot);
4388
+ if (policy.mode === "direct") return [];
4389
+ const home = this.homeOf(state);
4390
+ const mounted = home === void 0 ? [] : this.schemasOf(home, state.agent.id);
4391
+ if (policy.mode === "disclosure") {
4392
+ const budget = this.config.activationToolBudgetChars ?? 4e4;
4393
+ if (!overToolBudget(surfaceChars(mounted), budget)) return [];
4394
+ }
4395
+ const offered = this.offeredNamesOf(state);
4396
+ return mounted.map((schema) => schema.name).filter((name) => !offered.has(name));
4397
+ }
4398
+ /**
4231
4399
  * Whether one project root has a live session on this host.
4232
4400
  * @param projectRoot - project root a policy request names.
4233
4401
  * @returns `true` when a bound session resolved to that root.
@@ -5424,23 +5592,32 @@ var ProjectMcpRuntime = class {
5424
5592
  const bridge = {
5425
5593
  batch: new ForwardBatch({
5426
5594
  names: () => {
5595
+ const project = state.project;
5596
+ if (project === void 0) return void 0;
5427
5597
  try {
5428
- return projectToolNames(state.project?.key ?? {}, (scope) => this.bridgeSchemas(scope), servers());
5598
+ return projectToolNames(project.key, (scope) => this.bridgeSchemas(scope), servers());
5429
5599
  } catch (error) {
5430
5600
  this.ctx.logger.warn(`project-mcp: reading the tools to forward to session ${state.agent.id} failed: ${errorText(error)}`);
5431
5601
  return;
5432
5602
  }
5433
5603
  },
5434
- register: (names) => forwardProjectTools({
5435
- ctx: context,
5436
- project: state.project?.key ?? {},
5437
- names,
5438
- registry
5439
- })
5604
+ deferred: () => this.deferredNamesOf(state),
5605
+ register: (names, deferred) => {
5606
+ const project = state.project;
5607
+ if (project === void 0) return () => void 0;
5608
+ return forwardProjectTools({
5609
+ ctx: context,
5610
+ project: project.key,
5611
+ names,
5612
+ deferred: (name) => deferred.has(name),
5613
+ registry
5614
+ });
5615
+ },
5616
+ onError: (error) => this.reportBridgeFailure(state, error)
5440
5617
  }),
5441
5618
  detach: () => void 0
5442
5619
  };
5443
- const detach = state.scope.ctx.on("tools/change", () => this.syncBridge(state));
5620
+ const detach = state.scope.ctx.on("tools/change", () => this.noteBridge(state));
5444
5621
  bridge.detach = typeof detach === "function" ? detach : () => void 0;
5445
5622
  state.bridge = bridge;
5446
5623
  this.syncBridge(state);
@@ -5461,9 +5638,37 @@ var ProjectMcpRuntime = class {
5461
5638
  try {
5462
5639
  bridge.batch.sync();
5463
5640
  } catch (error) {
5464
- this.ctx.logger.warn(`project-mcp: forwarding the tools of ${state.project?.projectRoot ?? "the project"} into session ${state.agent.id} failed: ${errorText(error)}`);
5641
+ this.reportBridgeFailure(state, error);
5465
5642
  }
5466
5643
  }
5644
+ /**
5645
+ * Note one registry change for one session's bridge, off the emitter's stack.
5646
+ *
5647
+ * The event this answers is emitted synchronously from inside the registry's
5648
+ * own insertion and removal — once per entry in, once per entry out — so one
5649
+ * MCP generation swap is a burst of thousands. Running the pass here would
5650
+ * make whoever registered a tool pay for every session watching the project,
5651
+ * and each pass projects the project's whole catalog. The batch folds the
5652
+ * burst into one queued pass instead, which is also why this is not
5653
+ * {@link syncBridge}: the read paths, the mount settle and the scope wiring
5654
+ * all bring the batch level synchronously, before anything reads the layer.
5655
+ * @param state - the session whose bridge noticed the change.
5656
+ */
5657
+ noteBridge(state) {
5658
+ state.bridge?.batch.note();
5659
+ }
5660
+ /**
5661
+ * Write the one warning line a failed bridge pass is allowed.
5662
+ *
5663
+ * Shared by the synchronous pass and by the one a batch runs on its own: a
5664
+ * scheduled pass has no caller left to propagate its failure to, so the batch
5665
+ * hands it here through `onError` rather than swallowing it.
5666
+ * @param state - the session whose bridge failed.
5667
+ * @param error - what the pass threw.
5668
+ */
5669
+ reportBridgeFailure(state, error) {
5670
+ this.ctx.logger.warn(`project-mcp: forwarding the tools of ${state.project?.projectRoot ?? "the project"} into session ${state.agent.id} failed: ${errorText(error)}`);
5671
+ }
5467
5672
  /** The project scope's visible schemas, as {@link projectToolNames} reads them. */
5468
5673
  bridgeSchemas(scope) {
5469
5674
  return this.bridgeRegistry().schemas(scope);
@@ -5590,6 +5795,7 @@ var ProjectMcpRuntime = class {
5590
5795
  visible: () => this.visibleSchemas(state),
5591
5796
  foreign: () => this.foreignNamesOf(state),
5592
5797
  policy: () => this.policyFor(state.projectRoot),
5798
+ onOfferedChanged: () => state.bridge?.batch.note(),
5593
5799
  step: () => state.step,
5594
5800
  onActivated: (names, step) => {
5595
5801
  for (const name of names) state.steps.set(name, step);