dsh-project-mcp 0.2.0 → 0.4.0

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.d.ts ADDED
@@ -0,0 +1,3785 @@
1
+ import z from "@deepseek-ai/schemastery";
2
+ import { Config as Config$1 } from "@deepseek-ai/dsh-mcp-client";
3
+ import { Scope } from "@deepseek-ai/dsh-scope";
4
+ import { Context } from "@deepseek-ai/cordis";
5
+ import { IncomingMessage, ServerResponse } from "node:http";
6
+ //#region src/bridge.d.ts
7
+ /**
8
+ * F-19 forwarding bridge: one `mcp-client` per project, a thin definition per
9
+ * session.
10
+ *
11
+ * A preset composition mounts each session's tools from its own preset subtree,
12
+ * and `agent-presets` binds every composed agent's scope key to the preset's
13
+ * standing key *before* the agent is published. `dsh-scope` binds a key to one
14
+ * parent exactly once, so the project's scope can never join that session's
15
+ * chain — `bindScopeParent` throws, and the runtime's only remaining option was
16
+ * to mount the same declarations again under the session's own scope: one child
17
+ * process per session.
18
+ *
19
+ * The bridge takes the other path. The project keeps its one instance mounted in
20
+ * the project's own scope; a session whose chain cannot reach that scope gets a
21
+ * *forwarding* definition registered in its own layer instead. The forwarder
22
+ * carries the project tool's model-facing surface, and each call resolves the
23
+ * project's live definition by name and runs it:
24
+ *
25
+ * ```
26
+ * project scope session scope (per session)
27
+ * ┌────────────────────────┐ ┌──────────────────────────────────┐
28
+ * │ mcp-client instance │ │ register("mcp__a__run") ──────┐ │
29
+ * │ register("mcp__a__run")│◄────────┼── get("mcp__a__run", project) │ │
30
+ * │ execute(args, exec) │ │ → projectDefinition.execute │ │
31
+ * └────────────────────────┘ └──────────────────────────────────┘
32
+ * ```
33
+ *
34
+ * The resolution is by name at call time, not a captured definition object,
35
+ * because `mcp-client` swaps its whole tool generation on every `tools/list`
36
+ * refresh: a captured definition would keep executing a disposed generation.
37
+ *
38
+ * One session owns one live batch of forwarders, and {@link ForwardBatch} keeps
39
+ * it level with the project's live set: the set is re-read on every trigger,
40
+ * the batch is replaced as a whole (released before the replacement is
41
+ * registered), and the re-entry every registration forces on the sync through
42
+ * `tools/change` is owned rather than left to tear the batch down.
43
+ *
44
+ * The module is import-free of `@deepseek-ai/dsh-tools` on purpose, exactly like
45
+ * {@link ./activation.ts}: the registry, definition and schema surfaces are
46
+ * described by the minimal structural types below, so the plugin stays
47
+ * installable in a deployment that does not carry the tools package.
48
+ *
49
+ * @module dsh-project-mcp/bridge
50
+ */
51
+ /**
52
+ * Minimal structural view of one model-facing content block.
53
+ *
54
+ * Deliberately open: every block the harness vocabulary carries has a `type` and
55
+ * its own fields, so this is a supertype of all of them. That is what lets a
56
+ * project definition typed against the real `ContentBlock` be copied into a
57
+ * forwarder without a cast at the seam.
58
+ */
59
+ interface TextBlockLike$1 {
60
+ /** Block discriminant, eg `text`. */
61
+ readonly type: string;
62
+ /** Every other block field, unread here. */
63
+ readonly [key: string]: unknown;
64
+ }
65
+ /**
66
+ * Minimal structural view of one model-facing tool schema.
67
+ *
68
+ * It is the shape of `ctx.tools.schemas(scope)` entries, described locally
69
+ * because `@deepseek-ai/dsh-tools` is a peer this plugin does not import.
70
+ */
71
+ interface BridgeToolSchema {
72
+ /** Public registry name, eg `mcp__alpha__run`. */
73
+ readonly name: string;
74
+ /** Model-facing description. */
75
+ readonly description: string;
76
+ /** JSON Schema object arguments. */
77
+ readonly parameters: Record<string, unknown>;
78
+ }
79
+ /**
80
+ * Minimal structural view of one registered tool definition.
81
+ *
82
+ * Every field except `execute` is carried over from the project's definition
83
+ * verbatim — copied as a whole (`forwarder` spreads the definition), never by
84
+ * enumerating the fields this module happens to know, so the forwarding entry is
85
+ * indistinguishable from the original to everything that reads a definition:
86
+ * schema projection, presentation metadata and callbacks, the concurrency
87
+ * classifier, the timeout budget, the output renderer and the last-mile
88
+ * `finalizeContent` the registry snapshots from the definition the session
89
+ * resolves.
90
+ */
91
+ interface ForwardableDefinition extends BridgeToolSchema {
92
+ /** Canonical output contract: schema plus model-facing renderer. */
93
+ readonly output: {
94
+ /** Enforced JSON Schema of the canonical value `execute` returns. */
95
+ readonly schema: Record<string, unknown>;
96
+ /**
97
+ * Project the canonical value onto model-facing content.
98
+ * @param args - parsed call arguments.
99
+ * @param value - the validated canonical value.
100
+ * @returns the content blocks the model sees.
101
+ */
102
+ render(args: unknown, value: never): readonly TextBlockLike$1[];
103
+ /**
104
+ * Optional presentation projection, preserved so a call renders the same
105
+ * card through either layer.
106
+ * @param args - parsed call arguments.
107
+ * @param value - the validated canonical value.
108
+ * @returns the presentation metadata.
109
+ */
110
+ presentationMeta?(args: unknown, value: never): unknown;
111
+ };
112
+ /** Cooperative timeout budget, preserved for the timeout policy wrapper. */
113
+ readonly timeoutMs?: number;
114
+ /**
115
+ * Pure sibling-overlap classifier. Preserved: a forwarder that dropped it
116
+ * would make every forwarded call exclusive while the project tool is
117
+ * parallel-safe.
118
+ * @param args - parsed call arguments.
119
+ * @returns whether this call may join a parallel group.
120
+ */
121
+ isConcurrencySafe?(args: unknown): boolean;
122
+ /**
123
+ * Last-mile transform of the model-facing content, preserved.
124
+ *
125
+ * The registry snapshots this from the definition the *session* resolves —
126
+ * which is the forwarder, not the project's entry — and calls it once per
127
+ * normalized outcome. A forwarder that dropped it would silently degrade
128
+ * every provider result that relies on it: an MCP result's stored images, for
129
+ * one, would arrive as the adapter's plain text fallback.
130
+ * @param exec - the execution identity, passed through unchanged.
131
+ * @param result - the normalized outcome before materialization.
132
+ * @returns replacement content, or `undefined` to preserve the current one.
133
+ */
134
+ finalizeContent?(exec: unknown, result: unknown): readonly TextBlockLike$1[] | undefined;
135
+ /**
136
+ * Pending-state presentation, preserved so a forwarded call renders the same
137
+ * card as the project's own entry.
138
+ * @param args - parsed call arguments.
139
+ * @returns the presentation intent, or `undefined` for the generic card.
140
+ */
141
+ presentCall?(args: unknown): unknown;
142
+ /**
143
+ * Completed-state presentation, preserved for the same reason.
144
+ * @param args - parsed call arguments.
145
+ * @param result - the durable result projection.
146
+ * @returns the presentation intent, or `undefined` to keep the pending one.
147
+ */
148
+ presentResult?(args: unknown, result: unknown): unknown;
149
+ /**
150
+ * Run one accepted call.
151
+ * @param args - parsed call arguments.
152
+ * @param exec - execution identity, cancellation, and context deferral.
153
+ * @returns the canonical value declared by `output.schema`.
154
+ */
155
+ execute(args: unknown, exec: never): Promise<unknown>;
156
+ }
157
+ /**
158
+ * The registry surface the bridge reads: one scoped lookup and one scoped
159
+ * schema probe.
160
+ *
161
+ * `get(name, scope)` is the registry's public lookup and `schemas(scope)` its
162
+ * public schema projection (`@deepseek-ai/dsh-tools` `ToolRuntime`); passing the
163
+ * project's scope key reads the project's own layer and its ancestors, which is
164
+ * where the shared instance registered its tools.
165
+ */
166
+ interface BridgeRegistryLike {
167
+ /**
168
+ * Resolve one tool as one scope sees it.
169
+ * @param name - registered tool name.
170
+ * @param scope - viewing scope key; omitted reads the global view.
171
+ * @returns the visible definition, or `undefined` when none is.
172
+ */
173
+ get(name: string, scope?: object): ForwardableDefinition | undefined;
174
+ /**
175
+ * Project one scope's visible definitions onto their model-facing schemas.
176
+ * @param scope - viewing scope key; omitted reads the global view.
177
+ * @returns one schema per visible tool, in registry order.
178
+ */
179
+ schemas(scope?: object): readonly BridgeToolSchema[];
180
+ }
181
+ /**
182
+ * The registration context slices the bridge touches.
183
+ *
184
+ * A session's scope context is passed in, so `register` files every entry into
185
+ * that session's own layer — the one layer this session owns, where the name is
186
+ * visible to itself and to nobody else.
187
+ */
188
+ interface BridgeContextLike {
189
+ /** Resolve one service, the injection-free read the plugin already uses. */
190
+ get(name: string): unknown;
191
+ }
192
+ /**
193
+ * The names to forward, and how to register one batch of them.
194
+ *
195
+ * Both are read fresh on every pass: `names` because a server publishing a late
196
+ * `tools/list` (or dropping one) is the ordinary life of a project, and
197
+ * `register` because a pass can be requested from inside a pass.
198
+ */
199
+ interface ForwardBatchOptions {
200
+ /**
201
+ * The project's live tool names, probed on every pass.
202
+ *
203
+ * `undefined` reports a probe that failed: it says nothing about what the
204
+ * project publishes, so the batch it could not describe is the batch that
205
+ * stays live.
206
+ * @returns the names this session should forward, or `undefined` on failure.
207
+ */
208
+ readonly names: () => readonly string[] | undefined;
209
+ /**
210
+ * Register one batch of forwarders over the session's layer, which this call
211
+ * reaches empty-handed: the batch it replaces is released first.
212
+ * @param names - the names to forward, in registry order.
213
+ * @returns the exact releaser that drops the whole batch.
214
+ */
215
+ readonly register: (names: readonly string[]) => () => void;
216
+ }
217
+ /**
218
+ * One session's live forwarding batch, kept level with the project's live tools.
219
+ *
220
+ * The registry announces every registration by emitting `tools/change`
221
+ * synchronously from inside the insertion, and a bridged session is subscribed
222
+ * to exactly that event (`src/runtime.ts`, `installBridge`). A pass therefore
223
+ * re-enters itself once per forwarder it registers. Nothing else owns that
224
+ * re-entry, and left unowned it tears the batch down: the nested pass finds a
225
+ * batch still being built, releases it, and registers a second copy of it —
226
+ * which the live first copy refuses as a duplicate. A bridge that steps aside
227
+ * for a duplicate (it must, for the session's own tools) then drops those names
228
+ * silently, and a full pass records `namesIn` as the whole set, so the loss is
229
+ * frozen for every later pass. That is the defect this class exists to close.
230
+ *
231
+ * So: a pass requested from inside a pass only marks the batch dirty, and the
232
+ * frame that owns the batch runs one more pass when it is complete — which is
233
+ * also how a project set that changed mid-registration is still honoured. And
234
+ * the old batch is released **before** the new one is registered, because one
235
+ * layer holds one entry per name: registering over a live batch would refuse
236
+ * every name it already had.
237
+ */
238
+ declare class ForwardBatch {
239
+ #private;
240
+ private readonly options;
241
+ constructor(options: ForwardBatchOptions);
242
+ /**
243
+ * The names the live batch was registered for.
244
+ *
245
+ * `undefined` before the first successful pass, and again after a pass whose
246
+ * registration failed: an unset state is what makes the next pass retry
247
+ * rather than short-circuit on a set that never landed.
248
+ */
249
+ get namesIn(): readonly string[] | undefined;
250
+ /**
251
+ * Bring the session's layer level with the project's live tool set.
252
+ *
253
+ * Cheap when it already is: an unchanged set short-circuits and leaves the
254
+ * live batch — and its generation of definitions — untouched. Re-entrant
255
+ * while registering: see the class note.
256
+ * @returns nothing; a failure from the probe or the registry propagates.
257
+ */
258
+ sync(): void;
259
+ /**
260
+ * Drop the live batch: the session keeps no forwarder, and the next
261
+ * {@link sync} starts from nothing rather than amending a stale set.
262
+ * Idempotent.
263
+ *
264
+ * The release announces itself (`tools/change`) once per entry, and the
265
+ * session is subscribed to that event; a pass re-entered from there must not
266
+ * resurrect the batch it is watching being dropped. So the guard is held for
267
+ * the whole release, and the pass it queues is discarded rather than run.
268
+ */
269
+ drop(): void;
270
+ }
271
+ //#endregion
272
+ //#region src/types.d.ts
273
+ /**
274
+ * Shared row/snapshot vocabulary for `dsh-project-mcp`.
275
+ *
276
+ * The host half publishes a {@link ProjectSnapshot} through the `projectMcp`
277
+ * service so a future Web UI (or a test) can read what is mounted without
278
+ * importing the runtime.
279
+ *
280
+ * @module dsh-project-mcp/types
281
+ */
282
+ /** Runtime state of one project-declared MCP server. */
283
+ type ServerStatus =
284
+ /** Mounted and its tools are visible in the owning scope. */
285
+ 'active' |
286
+ /** Mounted; activation or the initial connection has not settled yet. */
287
+ 'connecting' |
288
+ /**
289
+ * Declared, parsed, and not mounted: either `lazy` has not seen this
290
+ * session's first turn yet, or the session went idle and its mounts were
291
+ * released (`idleTimeoutMs`). The next turn mounts it again.
292
+ */
293
+ 'idle' |
294
+ /** Declared with `enabled: false` — never mounted. */
295
+ 'disabled' |
296
+ /** The same `serverName` is reserved by a live profile-level instance. */
297
+ 'conflict' |
298
+ /** The entry or its mount failed; `detail` carries the reason. */
299
+ 'error';
300
+ /** One server row of a project snapshot. */
301
+ interface ServerRow {
302
+ /** `serverName` (the `mcpServers` key, sanitized). */
303
+ name: string;
304
+ /** Current lifecycle state. */
305
+ status: ServerStatus;
306
+ /** Project root the entry was read from. */
307
+ projectRoot: string;
308
+ /** Absolute path of the declaring document. */
309
+ source?: string;
310
+ /** `stdio` or `streamable-http`, when the entry parsed. */
311
+ transport?: 'stdio' | 'streamable-http';
312
+ /**
313
+ * Failure, stall or conflict explanation. Redacted on purpose: it names the
314
+ * command but never its arguments, and an HTTP endpoint keeps its path but
315
+ * drops the query string, because both can carry credentials.
316
+ */
317
+ detail?: string;
318
+ /**
319
+ * Stable wire code of `detail` (`projectMcp.host` namespace), for
320
+ * client-side translation. Optional and additive, exactly like
321
+ * {@link blockedCode}: the prose field keeps its byte-identical English and
322
+ * stays the fallback, so a client and a host of different builds degrade
323
+ * rather than break.
324
+ */
325
+ detailCode?: string;
326
+ /**
327
+ * Flat params of {@link detailCode}; a name ending in `Code` is itself a
328
+ * wire code the client resolves two-level.
329
+ */
330
+ detailParams?: Record<string, string>;
331
+ /**
332
+ * Parsed body of the entry, for the editor. Absent when the entry did not
333
+ * parse — there is nothing to edit then.
334
+ */
335
+ entry?: EntrySnapshot;
336
+ /** Where this row may be written back, when it may be written at all. */
337
+ writeScope?: WriteScope;
338
+ /** One line saying why writing is unavailable; always set for `readonly`. */
339
+ writeBlockedReason?: string;
340
+ /**
341
+ * Stable wire code of `writeBlockedReason` (`projectMcp.host` namespace),
342
+ * for client-side translation. Optional and additive: the prose field keeps
343
+ * its byte-identical English and stays the fallback, so a client and a host
344
+ * of different builds degrade rather than break.
345
+ */
346
+ blockedCode?: string;
347
+ /**
348
+ * Flat params of {@link blockedCode}; a name ending in `Code` is itself a
349
+ * wire code the client resolves two-level.
350
+ */
351
+ blockedParams?: Record<string, string>;
352
+ /**
353
+ * Opaque content revision of the declaring document at snapshot time. A save
354
+ * must carry the revision it was built from: a mismatch means the document
355
+ * changed underneath the editor, and the write is refused rather than merged.
356
+ */
357
+ documentRevision?: string;
358
+ }
359
+ /**
360
+ * How one `env` or `headers` entry is known to the host.
361
+ *
362
+ * A value can come from the declaring document, be answered outside it (the
363
+ * project's own `.env` or the credentials file), or be withheld because it is a
364
+ * credential. {@link EntryField.masked} is the field
365
+ * that changes how a write treats it: a masked key submitted without a `value` is
366
+ * kept exactly as the document declares it, so an editor that cannot see a secret
367
+ * can never erase or replace one.
368
+ */
369
+ interface EntryField {
370
+ /** Key exactly as declared. */
371
+ readonly key: string;
372
+ /** Literal value; absent when the host withholds it. */
373
+ readonly value?: string;
374
+ /** `true` when `value` is absent because the value is a secret. */
375
+ readonly masked?: true;
376
+ /**
377
+ * `true` when the key is answered outside the document — by the project's
378
+ * `.env` or by the credentials file. The name predates the project dotenv
379
+ * sources; the meaning the write path reads is "never write this value back".
380
+ */
381
+ readonly fromCredentials?: true;
382
+ }
383
+ /**
384
+ * One server entry as the host parsed it, for an editor.
385
+ *
386
+ * Every field is what the declaring document holds — a resolved default is never
387
+ * folded in, because a save replaces the declaration, not the runtime config.
388
+ */
389
+ interface EntrySnapshot {
390
+ /** Transport the entry declares. */
391
+ readonly transport: 'stdio' | 'streamable-http';
392
+ /** `stdio`: the program to run. */
393
+ readonly command?: string;
394
+ /** `stdio`: its arguments, verbatim. */
395
+ readonly args?: readonly string[];
396
+ /** `stdio`: working directory, when the entry declares one. */
397
+ readonly cwd?: string;
398
+ /** `stdio`: declared environment, secrets masked. */
399
+ readonly env?: readonly EntryField[];
400
+ /** `streamable-http`: the endpoint, with a credential-bearing query dropped. */
401
+ readonly url?: string;
402
+ /** `streamable-http`: declared headers, secrets masked. */
403
+ readonly headers?: readonly EntryField[];
404
+ /** `false` when the declaration disables the server; absent means enabled. */
405
+ readonly enabled?: boolean;
406
+ /** Declared connect timeout in milliseconds, when the entry sets one. */
407
+ readonly connectTimeoutMs?: number;
408
+ /**
409
+ * Keys the editor does not present, kept in their declared order and written
410
+ * back untouched. A save replaces the entry wholesale, so dropping them would
411
+ * delete configuration the panel never showed.
412
+ */
413
+ readonly extra?: Readonly<Record<string, unknown>>;
414
+ }
415
+ /**
416
+ * Whether one row's declaring document may be rewritten.
417
+ *
418
+ * - `project` — one of the deployment's project documents (`localFiles`,
419
+ * `<project>/.dsh/mcp.json` out of the box);
420
+ * - `global` — one of its global documents (`globalFiles`), written only with an
421
+ * explicit per-write consent;
422
+ * - `readonly` — the profile, `<DSH_HOME>` or a bundled document: never written.
423
+ */
424
+ type WriteScope = 'project' | 'global' | 'readonly';
425
+ /**
426
+ * One document a project is configured to read.
427
+ *
428
+ * The list a project publishes is exactly its read order — global documents
429
+ * first, then the project's own — so the panel's priority number is an index
430
+ * into it and never a table of hardcoded file names.
431
+ */
432
+ interface ConfiguredFile {
433
+ /** Absolute path of the document. */
434
+ readonly path: string;
435
+ /**
436
+ * `global` — read for every project, before its own documents; `project` —
437
+ * read from the project root.
438
+ */
439
+ readonly scope: 'global' | 'project';
440
+ }
441
+ /** Diagnostics surfaced alongside the rows. */
442
+ interface SnapshotIssue {
443
+ /** Absolute path of the declaring document. */
444
+ source: string;
445
+ /** Server the diagnostic belongs to, when entry-scoped. */
446
+ server?: string;
447
+ /** `error` or `warning`. */
448
+ level: 'error' | 'warning';
449
+ /** Human-readable text. */
450
+ message: string;
451
+ /**
452
+ * Stable wire code of `message` (`projectMcp.host` namespace), for
453
+ * client-side translation. Optional and additive: `message` keeps its
454
+ * byte-identical English and stays the fallback. Behavioural matches key on
455
+ * this field — never on the prose, which the client may have translated.
456
+ */
457
+ code?: string;
458
+ /**
459
+ * Flat params of {@link SnapshotIssue.code}; a name ending in `Code` is
460
+ * itself a wire code the client resolves two-level.
461
+ */
462
+ params?: Record<string, string>;
463
+ }
464
+ /**
465
+ * One session's own view of the project it works in.
466
+ *
467
+ * Sessions of one project are independent: each mounts its own servers, and one
468
+ * may have them running while another has not started a turn yet. The panel
469
+ * needs that split, because a project-level merge alone cannot say *which*
470
+ * session holds a mount.
471
+ */
472
+ interface SessionSnapshot {
473
+ /** Agent (session) id. */
474
+ id: string;
475
+ /** Rows for this session alone, in document order. */
476
+ rows: ServerRow[];
477
+ /** Diagnostics this session surfaced. */
478
+ issues: SnapshotIssue[];
479
+ /** What this session offers the model, when the host has mounted for it. */
480
+ tools?: SessionTools;
481
+ /**
482
+ * How many events of the project's ring belong to this session. Absent for a
483
+ * session that produced none, so the tab's log badge reads a real `0`.
484
+ */
485
+ logCount?: number;
486
+ /**
487
+ * `serverName` conflicts this session last reconciled: a profile-level
488
+ * instance that already owns a name, or one name two project documents
489
+ * declare. Published even when empty, so a reader can tell "this session
490
+ * reported none" from a host that does not report conflicts at all.
491
+ */
492
+ conflicts?: readonly ServerConflict[];
493
+ }
494
+ /** One tool a session offers the model, and what put it in the request. */
495
+ interface OfferedTool {
496
+ /** Public registry name, eg `mcp__tglider__workspace`. */
497
+ readonly name: string;
498
+ /**
499
+ * The tier that offered it: `session` activated on demand through the search
500
+ * tool, `context` ranked from the task text of the current conversation. The
501
+ * counter-seeded baseline is not this shape — it is a plain name list in
502
+ * {@link SessionTools.baseline}.
503
+ */
504
+ readonly via: 'session' | 'context';
505
+ /**
506
+ * Epoch milliseconds of the last offer or call. Absent for the context tier,
507
+ * whose live state stamps an advance rather than a clock reading.
508
+ */
509
+ readonly at?: number;
510
+ /**
511
+ * Number of the agent step (from `1`) the tool was offered at, or `undefined`
512
+ * for a host that does not count steps. A panel that reads no number draws no
513
+ * step tag at all rather than a made-up one.
514
+ */
515
+ readonly step?: number;
516
+ }
517
+ /**
518
+ * One accepted field of a tool's `parameters` schema, as the panel lists it.
519
+ *
520
+ * A field is listed from the definition the host already holds, so its type and
521
+ * its `required` flag are the schema's own and neither is inferred from the
522
+ * tool's name. Nesting stops at the top level: an object or array field is drawn
523
+ * as its type, not expanded, because the panel lists what a call takes rather
524
+ * than mirroring a schema. Schema `default` values are deliberately not part of
525
+ * this shape — a default can carry a value the tool did not mean to publish.
526
+ */
527
+ interface ToolField {
528
+ /** Property name, as the schema declares it. */
529
+ readonly name: string;
530
+ /** JSON Schema `type` of the field, or `any` when the schema names none. */
531
+ readonly type: string;
532
+ /** `true` when the schema's own `required` array names this property. */
533
+ readonly required: boolean;
534
+ /** The property's own `description`, when the schema publishes one. */
535
+ readonly description?: string;
536
+ }
537
+ /**
538
+ * Why one name is not in this session's request, in the host's own terms.
539
+ *
540
+ * The decision belongs to the host and the panel does not recompute it, so the
541
+ * reason travels as data and its copy lives in the client's dictionaries. Every
542
+ * figure here is a host measurement — the definition's own serialized size, the
543
+ * session's budget, what the offered set already carries — so a reason line
544
+ * invents no number. That is the same discipline as contract C2's step tag.
545
+ */
546
+ interface ToolReason {
547
+ /**
548
+ * Which decision left the name out. `budget` is the disclosure mode pushing it
549
+ * past {@link ToolReason.budget}: the whole mounted surface is registered, and
550
+ * this definition did not fit the request.
551
+ */
552
+ readonly kind: 'budget';
553
+ /** Serialized size of this definition, in characters — the host's own figure. */
554
+ readonly chars?: number;
555
+ /** The session's tool budget in characters, when the host budgeted one. */
556
+ readonly budget?: number;
557
+ /** Characters the offered set already carries, when the host measured them. */
558
+ readonly used?: number;
559
+ }
560
+ /**
561
+ * One tool's detail, answered on demand for a row the reader opened.
562
+ *
563
+ * The panel fetches this instead of carrying it in the snapshot: the snapshot
564
+ * travels on every change frame and every poll, while a description and a schema
565
+ * are read once per opened row. The text is model-facing and arrives as data —
566
+ * it is never copied into a dictionary, is not translated, and is drawn as the
567
+ * host published it.
568
+ */
569
+ interface ToolFacts {
570
+ /** Public registry name this record answers about. */
571
+ readonly name: string;
572
+ /** The definition's model-facing description, when the host holds one. */
573
+ readonly description?: string;
574
+ /** Accepted fields, in schema order; empty when the tool declares none. */
575
+ readonly fields: readonly ToolField[];
576
+ /** Why the name is not offered, when it is not. Absent for an offered name. */
577
+ readonly reason?: ToolReason;
578
+ }
579
+ /**
580
+ * Another loaded plugin that owns the assembled tool list.
581
+ *
582
+ * The plugin and such an owner cannot shape one request together: the outer
583
+ * listener of whoever assembles last rewrites `assembly.tools`, so the plugin's
584
+ * own deferral would be re-applied over an already-trimmed list. The host
585
+ * reports the owner instead of silently composing with it, and a panel prints
586
+ * the coexistence note only when this record is published.
587
+ */
588
+ interface PresentationOwner {
589
+ /** Loader entry name, for example `dsh-progressive-tools`. */
590
+ readonly name: string;
591
+ /** One line saying why coexisting in one request is impossible. */
592
+ readonly note: string;
593
+ /**
594
+ * The `projectMcp.host` code of {@link note} (F-48): the client translates
595
+ * by it and falls back to `note`'s English, byte-identical, when the code is
596
+ * absent or unknown. No params — the note is one fixed sentence.
597
+ */
598
+ readonly noteCode?: string;
599
+ }
600
+ /**
601
+ * One `serverName` two declarations fight over.
602
+ *
603
+ * `profile` is the profile-level `mcp-client` instance that already owns the
604
+ * name: the project entry mounts only through the local alias the user chose,
605
+ * and never under the contested name itself. `duplicate` is one name declared by
606
+ * more than one project document: the highest-priority document wins and the
607
+ * others are ignored.
608
+ */
609
+ interface ServerConflict {
610
+ /** `serverName` the declarations share. */
611
+ readonly server: string;
612
+ /** `profile` — a profile-level instance owns the name; `duplicate` — two documents. */
613
+ readonly kind: 'profile' | 'duplicate';
614
+ /** Declaring documents, the winner first. */
615
+ readonly sources: readonly string[];
616
+ /** One line: who wins, and why. */
617
+ readonly message: string;
618
+ /**
619
+ * The `projectMcp.host` code of {@link message} (F-48): the client translates
620
+ * by it and falls back to `message`'s English, byte-identical, when the code
621
+ * is absent (a host older than the field) or unknown to its dictionaries.
622
+ */
623
+ readonly code?: string;
624
+ /**
625
+ * Flat params of {@link code}; numbers stringify at emission. A name ending
626
+ * in `Code` is itself a wire code, resolved two-level through the same
627
+ * namespace and substituted under the plain name.
628
+ */
629
+ readonly params?: Record<string, string>;
630
+ /**
631
+ * The local name this project's entry mounts under when the user chose
632
+ * `local`, as `mcp__<alias>__<tool>` in the model's own list. Published on a
633
+ * `profile` conflict even while the choice is still the profile's, so the
634
+ * panel can offer the alias it would use rather than inventing one.
635
+ */
636
+ readonly alias?: string;
637
+ /**
638
+ * What the project's policy says about this name. Absent on a `duplicate`,
639
+ * which no choice resolves, and on a host older than this field.
640
+ */
641
+ readonly choice?: ConflictChoice;
642
+ }
643
+ /**
644
+ * What one live session currently offers the model.
645
+ *
646
+ * Measured from the session's own state, not from the project: two sessions of
647
+ * one project differ as soon as one of them has called a tool, and the panel's
648
+ * promise is to show what *this* session's model sees.
649
+ */
650
+ interface SessionTools {
651
+ /** Live agent (session) id this row describes. */
652
+ readonly sessionId: string;
653
+ /**
654
+ * Names offered because the durable counters proved them hot, plus the pins;
655
+ * empty in `off`, which offers none of the project's tools.
656
+ */
657
+ readonly baseline: readonly string[];
658
+ /** Names this session activated on demand, oldest first; empty in `off`. */
659
+ readonly activated: readonly OfferedTool[];
660
+ /** Names the task context offered, oldest first; empty in `off`. */
661
+ readonly context: readonly OfferedTool[];
662
+ /**
663
+ * Names mounted for the project but not offered by this plugin, sorted. In
664
+ * `disclosure` these are the names the budget pushed out of the request; in
665
+ * `direct` the list is empty, because nothing is filtered; in `off` it is the
666
+ * whole mounted surface, because a project that is switched off is offered not
667
+ * at all. Its length is exactly the count a panel shows as hidden — and such a
668
+ * panel has to read {@link ToolPolicy.mode} first, since tools another
669
+ * presentation plugin leaves in the request are not this one's offers.
670
+ */
671
+ readonly deferred: readonly string[];
672
+ /** Tools mounted for the project in total. */
673
+ readonly mounted: number;
674
+ /** Serialized size of the mounted surface, in characters. */
675
+ readonly surfaceChars: number;
676
+ /**
677
+ * Serialized size of the offered set — {@link SessionTools.baseline} plus the
678
+ * `activated` and `context` names — in characters. Absent from a host that
679
+ * does not split the surface, and then a panel prints no request estimate
680
+ * rather than inventing one.
681
+ */
682
+ readonly visibleChars?: number;
683
+ /**
684
+ * Serialized size of {@link SessionTools.deferred}, in characters: exactly the
685
+ * part of the mounted surface this plugin leaves out of the request. `0` when
686
+ * nothing is deferred, so a panel that found this field may divide it by four
687
+ * for a token estimate.
688
+ */
689
+ readonly deferredChars?: number;
690
+ /**
691
+ * Configured deferral budget in characters. `0` means there is no threshold at
692
+ * all: every surface counts as over budget, so tools are deferred however small
693
+ * the project is. Read {@link SessionTools.deferring} rather than comparing this
694
+ * with {@link SessionTools.surfaceChars} — the host owns the rule.
695
+ */
696
+ readonly budgetChars: number;
697
+ /**
698
+ * `true` while the surface is over the budget, so tools really are deferred.
699
+ * Only `disclosure` can defer: `direct` filters nothing and `off` offers
700
+ * nothing, so both report `false` however large the mounted surface is.
701
+ */
702
+ readonly deferring: boolean;
703
+ }
704
+ /** How one project's MCP tools are offered to the model. */
705
+ type ToolMode =
706
+ /** Offer the baseline and the on-demand tiers (the shipped behaviour). */
707
+ 'disclosure' |
708
+ /** Never defer: every mounted tool is listed in every request. */
709
+ 'direct' |
710
+ /** Do not offer this project's MCP tools at all. */
711
+ 'off';
712
+ /**
713
+ * How one `serverName` a project shares with a live profile instance is shown.
714
+ *
715
+ * The profile's instance owns the name in every scope, so the two declarations
716
+ * cannot both mount under it. `profile` keeps the profile's tools exactly as
717
+ * they are and leaves the project's entry unmounted; `local` mounts the
718
+ * project's entry under a local namespace (see `src/naming.ts`) so both toolsets
719
+ * reach the model — the only difference being the names they carry; `native`
720
+ * mounts the project's entry under the name it declares, which is the nearer
721
+ * declaration in this project's own sessions and so shadows the profile's tools
722
+ * of that name there, while every other project keeps seeing the profile's.
723
+ */
724
+ type ConflictChoice =
725
+ /** The profile instance keeps the name; the project entry does not mount. */
726
+ 'profile' |
727
+ /** The project entry mounts under its local alias, next to the profile's. */
728
+ 'local' |
729
+ /** The project entry mounts under the declared name, shadowing the profile's in this project. */
730
+ 'native';
731
+ /**
732
+ * One project's tool policy.
733
+ *
734
+ * The mode decides whether tools are deferred, the pins are the names the user
735
+ * insists on — a pinned tool is offered from the first step of every request, is
736
+ * never dropped by idle pruning or by a compaction, and is not counted against
737
+ * the deferral budget's reading of what is hidden — and the aliases remember, per
738
+ * conflicting `serverName`, which of the two declarations the user chose to see.
739
+ */
740
+ interface ToolPolicy {
741
+ /** Mode in force. */
742
+ readonly mode: ToolMode;
743
+ /**
744
+ * Public registry names pinned for this project, in the order the user pinned
745
+ * them. A name the project no longer mounts is kept: the declaration may come
746
+ * back, and a pin that silently disappeared would be a surprise.
747
+ */
748
+ readonly pins: readonly string[];
749
+ /**
750
+ * Choice per contested `serverName`. Optional so every fixture, host and
751
+ * stored document written before this field existed keeps meaning exactly
752
+ * what it meant: a name that is absent is one the user never chose about,
753
+ * and the shipped answer is the profile's instance. The store publishes an
754
+ * empty map rather than dropping the field, so a reader may treat `undefined`
755
+ * and `{}` alike.
756
+ */
757
+ readonly aliases?: Readonly<Record<string, ConflictChoice>>;
758
+ }
759
+ /**
760
+ * How much one MCP server of one project has been used.
761
+ *
762
+ * Counted on the host from the tool registry's own events, so it is exact rather
763
+ * than sampled, and keyed by project root: sessions come and go, the numbers
764
+ * stay, which is what makes them usable for later decisions about a project.
765
+ */
766
+ interface ServerUsage {
767
+ /** Calls dispatched through the registry, successful or not. */
768
+ calls: number;
769
+ /** Calls whose result carried an error. */
770
+ errors: number;
771
+ /** ISO timestamp of the most recent call. */
772
+ lastUsedAt?: string;
773
+ /**
774
+ * Per tool counts, keyed by the tool name as declared by the server, i.e.
775
+ * without the `mcp__<serverName>__` prefix the registry publishes it under.
776
+ */
777
+ tools: Record<string, number>;
778
+ /**
779
+ * The same readings split by session, keyed by the session (agent) id the
780
+ * panel already uses everywhere else.
781
+ *
782
+ * Additive since F-34: a document written before this field existed is read as
783
+ * it is — `USAGE_VERSION` does not move, because a reader that meets an unknown
784
+ * version refuses the whole document and every counter would start from zero.
785
+ * Absent means "counted before the split", never "no calls".
786
+ */
787
+ sessions?: Record<string, SessionUsage>;
788
+ }
789
+ /**
790
+ * One session's share of a server's counters.
791
+ *
792
+ * A server is mounted for a project and a project's sessions share it, so the
793
+ * project total says what the project used while this says what *this* session
794
+ * did; the two differ exactly when other sessions of the project called the
795
+ * server, which is the case a panel scoped to one session could not show.
796
+ */
797
+ interface SessionUsage {
798
+ /** Calls this session dispatched through the registry. */
799
+ calls: number;
800
+ /** Of those, the ones whose result carried an error. */
801
+ errors: number;
802
+ /** ISO timestamp of this session's most recent call. */
803
+ lastUsedAt?: string;
804
+ /** This session's counts, keyed by the tool name as the server declares it. */
805
+ tools: Record<string, number>;
806
+ }
807
+ /**
808
+ * How serious one plugin event is, as the Logs tab colours it.
809
+ *
810
+ * Four levels, mapped from the lifecycle line the host already writes: `info`
811
+ * for a mount being registered, `up` for one whose tools became visible, `warn`
812
+ * for a stall or a release, `error` for a failed mount and the unmount that
813
+ * follows it. They are the labels the tab draws, not a host severity scale.
814
+ */
815
+ type LogLevel =
816
+ /** The instance is being registered (`project-mcp: mounting …`). */
817
+ 'info' |
818
+ /** The instance's tools are visible (`… is up …`). */
819
+ 'up' |
820
+ /** A stall, a repeated pass, or a release the operator did not ask for. */
821
+ 'warn' |
822
+ /** The mount failed, or a failed mount is being torn down. */
823
+ 'error';
824
+ /**
825
+ * One lifecycle event, as the Logs tab lists it.
826
+ *
827
+ * The plugin's own events only — a mount, a start, a stop, a failure — mirroring
828
+ * the lines the host writes to the DSH log, so the two readers see the same
829
+ * facts. Events live in a per-project ring (`src/logs.ts`); the newest ones ride
830
+ * in the snapshot, the rest are paged over the route.
831
+ */
832
+ interface LogEvent {
833
+ /** When the event happened, epoch ms. */
834
+ readonly at: number;
835
+ /** How serious it is, as the tab colours it. */
836
+ readonly level: LogLevel;
837
+ /** Project root the event belongs to; the ring is keyed by it. */
838
+ readonly projectRoot: string;
839
+ /**
840
+ * Session the event is attributed to. Set exactly when the lifecycle line it
841
+ * mirrors names one — `mounting`, `is up`, a stall — and absent on a
842
+ * project-level event such as a shared instance's unmount.
843
+ */
844
+ readonly sessionId?: string;
845
+ /** `serverName` the event is about; absent for an event with no server. */
846
+ readonly server?: string;
847
+ /** One line, without a newline: one event is one row of the tab. */
848
+ readonly message: string;
849
+ /**
850
+ * The three facts an error carries — the failure, the endpoint, the declaring
851
+ * document — and no advice: the server row already offers the retry.
852
+ */
853
+ readonly detail?: string;
854
+ /**
855
+ * Wire code of {@link LogEvent.message} (F-48), into the `projectMcp.host`
856
+ * namespace. Optional: a host older than the field sends prose only, and the
857
+ * client falls back to {@link LogEvent.message}.
858
+ */
859
+ readonly code?: string;
860
+ /** Flat params of {@link LogEvent.code}; numbers are stringified at emission. */
861
+ readonly params?: Record<string, string>;
862
+ /** Wire code of {@link LogEvent.detail}, the same additive companion. */
863
+ readonly detailCode?: string;
864
+ /** Flat params of {@link LogEvent.detailCode}. */
865
+ readonly detailParams?: Record<string, string>;
866
+ }
867
+ /** Everything one project contributes to the live runtime. */
868
+ interface ProjectSnapshot {
869
+ /** Project root the agents below resolved to. */
870
+ projectRoot: string;
871
+ /**
872
+ * Documents this project is configured to read, in priority order — global
873
+ * ones first, then the project's own. Published even when empty, so a panel
874
+ * can tell "this deployment reads nothing" from a host that does not report
875
+ * its documents at all. Absent only from a snapshot a host older than this
876
+ * field produced, and then a reader falls back to the shipped names rather
877
+ * than inventing a priority.
878
+ */
879
+ files?: readonly ConfiguredFile[];
880
+ /**
881
+ * The tool policy in force for this project. Absent only from a snapshot a host
882
+ * older than the policy store produced; a reader treats that as the shipped
883
+ * default, {@link DEFAULT_TOOL_POLICY}.
884
+ */
885
+ policy?: ToolPolicy;
886
+ /** Live agent (session) ids currently bound to this project. */
887
+ sessionIds: string[];
888
+ /**
889
+ * Merged rows for every declared server, in document order. When sessions
890
+ * disagree about one server, the more actionable state wins, so a mounted or
891
+ * broken server is never hidden behind a session that has not turned yet.
892
+ */
893
+ rows: ServerRow[];
894
+ /** Parse and lifecycle diagnostics, deduplicated across the sessions. */
895
+ issues: SnapshotIssue[];
896
+ /** The same data split per session, in session-registration order. */
897
+ sessions: SessionSnapshot[];
898
+ /**
899
+ * Usage counters keyed by `serverName`, remembered across sessions. Absent
900
+ * while the host half has counted nothing for this project yet.
901
+ */
902
+ usage?: Record<string, ServerUsage>;
903
+ /**
904
+ * Another loaded plugin that owns the assembled tool list, when the profile
905
+ * has one. Absent means this plugin is the only owner — a panel that reads no
906
+ * record draws no coexistence notice.
907
+ */
908
+ presentation?: PresentationOwner;
909
+ /**
910
+ * Real `serverName` conflicts of this project: a profile-level instance that
911
+ * already owns a name, or one name two project documents declare. The list is
912
+ * always published — an empty one is the honest answer "no conflicts", which
913
+ * is what lets a panel report that instead of offering a disabled button.
914
+ */
915
+ conflicts?: readonly ServerConflict[];
916
+ /**
917
+ * The newest events of this project's ring, oldest first, at most the page
918
+ * size (50). Absent for a project that has recorded nothing, so a tab draws
919
+ * its empty state rather than an empty list.
920
+ */
921
+ logs?: readonly LogEvent[];
922
+ /**
923
+ * How many events the project's ring holds right now, `0…200`. Absent exactly
924
+ * when {@link ProjectSnapshot.logs} is: no events, nothing to count.
925
+ */
926
+ logCount?: number;
927
+ }
928
+ /** Whole-plugin snapshot: one entry per project with live agents. */
929
+ interface McpSnapshot {
930
+ /** `true` while the agents service has been observed. */
931
+ ready: boolean;
932
+ /** Projects with at least one live agent. */
933
+ projects: ProjectSnapshot[];
934
+ /**
935
+ * Documents this deployment is configured to read, exactly as the config
936
+ * spells them — `local` relative to a project root, `global` relative to
937
+ * `$HOME` (or absolute). Published for the surfaces that must speak about the
938
+ * deployment itself, with no project at hand: the empty state names what would
939
+ * be read instead of a file name baked into the client. Absent from a snapshot
940
+ * a host older than this field produced.
941
+ */
942
+ sources?: {
943
+ readonly local: readonly string[];
944
+ readonly global: readonly string[];
945
+ };
946
+ /** Absolute paths currently watched for config edits. */
947
+ watchedFiles: string[];
948
+ }
949
+ /**
950
+ * One pushed picture: what the status channel sends.
951
+ *
952
+ * The snapshot travels whole rather than as a delta, so a frame that arrives
953
+ * after a gap is still a complete answer — the panel can apply it without
954
+ * asking for anything back. `revision` counts the changes the host has announced
955
+ * and is what a late or repeated frame is judged by.
956
+ */
957
+ interface SnapshotChange {
958
+ /** Monotonic change counter, starting at `0` for the picture a stream opens on. */
959
+ revision: number;
960
+ /** The whole picture at that revision. */
961
+ snapshot: McpSnapshot;
962
+ }
963
+ //#endregion
964
+ //#region src/activation.d.ts
965
+ /** `true` while the session may offer MCP tools through search + activation. */
966
+ export declare const DEFAULT_ACTIVATION_ENABLED = true;
967
+ /**
968
+ * Tools seeded into the baseline from the durable counters. A project with a
969
+ * few dozen mounted tools calls more than a handful of them, so the cap sits
970
+ * above the narrow window that used to evict a tool the project really uses.
971
+ */
972
+ export declare const DEFAULT_ACTIVATION_SEEDED = 16;
973
+ /**
974
+ * Calls one tool needs in the counters before it is seeded. One call is enough:
975
+ * a tool the project actually uses enters the durable baseline the first time it
976
+ * is called, so the baseline grows from real usage instead of waiting for the
977
+ * counters to reach an arbitrary threshold.
978
+ */
979
+ export declare const DEFAULT_ACTIVATION_MIN_CALLS = 1;
980
+ /**
981
+ * How long a session-activated tool survives without a call (`0` disables).
982
+ *
983
+ * The shipped `0` keeps a searched tool offered for the rest of the session:
984
+ * dropping it mid-session shrinks the request and rewrites the prompt prefix,
985
+ * which invalidates the provider's prefix cache, so time-based removal stays an
986
+ * explicit opt-in.
987
+ */
988
+ export declare const DEFAULT_TOOL_IDLE_MS = 0;
989
+ /** Matches one `mcp_search_tools` call activates when it omits `limit`. */
990
+ export declare const DEFAULT_SEARCH_LIMIT = 8;
991
+ /** Hard cap on matches one `mcp_search_tools` call may activate. */
992
+ export declare const MAX_SEARCH_LIMIT = 50;
993
+ /**
994
+ * Distinct query words one `mcp_search_tools` call scores at most. A query
995
+ * longer than that is a sentence, and its tail words add noise rather than
996
+ * signal — the first words are the ones the model chose first.
997
+ */
998
+ export declare const MAX_SEARCH_TOKENS = 8;
999
+ /** Registry name of the discovery tool this module registers. */
1000
+ export declare const SEARCH_TOOL_NAME = "mcp_search_tools";
1001
+ /**
1002
+ * Minimal structural view of one model-facing tool schema.
1003
+ *
1004
+ * It is the exact element type of `system-prompt/assemble`'s `tools` list and of
1005
+ * `ctx.tools.schemas()`, described locally because `@deepseek-ai/dsh-tools` is a
1006
+ * peer this plugin does not import.
1007
+ */
1008
+ interface ToolSchemaLike {
1009
+ /** Public registry name, eg `mcp__alpha__run`. */
1010
+ readonly name: string;
1011
+ /** Model-facing description. */
1012
+ readonly description: string;
1013
+ /** JSON Schema object arguments. */
1014
+ readonly parameters: Record<string, unknown>;
1015
+ }
1016
+ /** One text block of the model-facing content vocabulary. */
1017
+ interface TextBlockLike {
1018
+ /** Always `text`; the only block this module renders. */
1019
+ readonly type: 'text';
1020
+ /** Human-readable text. */
1021
+ readonly text: string;
1022
+ }
1023
+ /**
1024
+ * Minimal structural view of a tool definition as `ctx.tools.register` accepts
1025
+ * it. Only the fields this module writes are declared.
1026
+ */
1027
+ interface ToolDefinitionLike {
1028
+ /** Registry name presented to the model. */
1029
+ readonly name: string;
1030
+ /** Model-facing description. */
1031
+ readonly description: string;
1032
+ /** JSON Schema object arguments. */
1033
+ readonly parameters: Record<string, unknown>;
1034
+ /** Canonical output contract: a schema to validate and a content renderer. */
1035
+ readonly output: {
1036
+ /** Enforced JSON Schema of the canonical value `execute` returns. */
1037
+ readonly schema: Record<string, unknown>;
1038
+ /**
1039
+ * Project the canonical value onto model-facing content.
1040
+ * @param args - parsed call arguments.
1041
+ * @param value - the validated canonical value.
1042
+ * @returns the content blocks the model sees.
1043
+ */
1044
+ render(args: unknown, value: unknown): readonly TextBlockLike[];
1045
+ };
1046
+ /**
1047
+ * Run one accepted call.
1048
+ * @param args - parsed call arguments.
1049
+ * @param context - execution identity; unused here.
1050
+ * @returns the canonical value declared by `output.schema`.
1051
+ */
1052
+ execute(args: unknown, context: unknown): Promise<unknown>;
1053
+ }
1054
+ /** One listener as `ctx.on` accepts it (method syntax keeps parameters bivariant). */
1055
+ type ListenerLike = (...args: never[]) => unknown;
1056
+ /**
1057
+ * The agent-scoped context slices this module touches. Described structurally so
1058
+ * the wiring is testable without a live harness.
1059
+ */
1060
+ interface ActivationContextLike {
1061
+ /**
1062
+ * Register an event listener through the scope; the scope owns its disposal.
1063
+ * @param name - event name.
1064
+ * @param listener - listener called with the event's dispatch arguments.
1065
+ * @param options - `prepend` places the listener outermost in a waterfall.
1066
+ * @returns the disposer, or anything the runtime returns for one.
1067
+ */
1068
+ on(name: string, listener: ListenerLike, options?: {
1069
+ prepend?: boolean;
1070
+ }): unknown;
1071
+ /** The tool registry, through the scope so registrations stay scope-local. */
1072
+ readonly tools: {
1073
+ /**
1074
+ * Register a tool in the calling scope.
1075
+ * @param definition - schema and execution.
1076
+ * @returns the exact disposer that unregisters the tool.
1077
+ */
1078
+ register(definition: ToolDefinitionLike): () => void;
1079
+ };
1080
+ }
1081
+ /** The subset of one prompt assembly this module reads and returns. */
1082
+ interface AssemblyLike {
1083
+ /** Model-facing tool schemas, already in canonical order. */
1084
+ tools: ToolSchemaLike[];
1085
+ }
1086
+ /** Handler of the `system-prompt/assemble` waterfall this module installs. */
1087
+ type AssembleListener = (assembly: AssemblyLike, context: unknown, next: () => Promise<AssemblyLike>) => Promise<AssemblyLike>;
1088
+ /**
1089
+ * The fields the wiring reads from one appended session event: enough to catch
1090
+ * a `compaction/end` and to recover the task text of a committed `user/message`.
1091
+ */
1092
+ interface SessionEventLike {
1093
+ /** Session event type, eg `compaction/end`. */
1094
+ readonly type?: unknown;
1095
+ /** Event payload, present on every committed event (`event.data`). */
1096
+ readonly data?: unknown;
1097
+ }
1098
+ /**
1099
+ * One session's activation state.
1100
+ *
1101
+ * `baseline` is the counter-seeded set and outlives a compaction; `active` holds
1102
+ * the names this session activated through search or the context tier, each with
1103
+ * the epoch milliseconds of its last touch, and is what idle pruning and
1104
+ * compaction trim. `used` records the calls the session made for this plugin's
1105
+ * own namespace — the evidence a compaction keeps an activation by, because a
1106
+ * tool the model called is one the session really uses. It is cumulative for the
1107
+ * session and never bounded, so the compaction boundary shrinks the offers no
1108
+ * call backs and never shrinks a used tool again.
1109
+ *
1110
+ * Every field is read-only because every transition returns a new state.
1111
+ */
1112
+ interface ActivationState {
1113
+ /** Public names the durable counters proved hot; always offered. */
1114
+ readonly baseline: ReadonlySet<string>;
1115
+ /** Session-activated public names mapped to their last touch. */
1116
+ readonly active: ReadonlyMap<string, number>;
1117
+ /**
1118
+ * `mcp__` names this session called at least once and the durable baseline
1119
+ * does not already keep. Read by nothing but {@link onCompaction}, and
1120
+ * cumulative for the session: it is deliberately never bounded, so with the
1121
+ * shipped `DEFAULT_TOOL_IDLE_MS` of `0` nothing else removes a name and a tool
1122
+ * the session used stays offered for the rest of the session, across every
1123
+ * further compaction.
1124
+ */
1125
+ readonly used: ReadonlySet<string>;
1126
+ }
1127
+ /**
1128
+ * Build one session's state.
1129
+ * @param baseline - counter-seeded public names; defaults to none.
1130
+ * @returns an empty active set and an empty used record over that baseline.
1131
+ */
1132
+ export declare function createActivationState(baseline?: Iterable<string>): ActivationState;
1133
+ /** How {@link seedFromUsage} reads the durable counters. */
1134
+ interface SeedOptions {
1135
+ /** Maximum names seeded; `0` seeds none. */
1136
+ readonly count: number;
1137
+ /** Calls one tool needs before it is seeded. */
1138
+ readonly minCalls: number;
1139
+ }
1140
+ /**
1141
+ * Seed the baseline from a project's durable counters.
1142
+ *
1143
+ * The counters key tools by the name the server declares them under and servers
1144
+ * by `serverName`, so the public registry name is the `mcp__<server>` prefix plus
1145
+ * the tool key — the same reconstruction the counter's own attribution relies
1146
+ * on. A name the registry had to truncate cannot be reversed this way; such a
1147
+ * tool is simply not seeded, which is why the search tool stays the discovery
1148
+ * path of record.
1149
+ *
1150
+ * @param usage - counters of one project, or `undefined` when none were recorded.
1151
+ * @param options - seed cap and per-tool minimum.
1152
+ * @returns the baseline names, most-called first (name order breaks ties).
1153
+ */
1154
+ export declare function seedFromUsage(usage: Record<string, ServerUsage> | undefined, options: SeedOptions): Set<string>;
1155
+ /**
1156
+ * Activate names for this session, idempotently.
1157
+ *
1158
+ * A baseline name is skipped: it is already offered, so tracking it in the
1159
+ * session set would only make a compaction look like it changed something.
1160
+ *
1161
+ * @param state - activation state before the activation.
1162
+ * @param names - public names activated (already filtered to this plugin's mounts).
1163
+ * @param at - epoch milliseconds of the activation.
1164
+ * @returns the updated state, or the input when nothing changed.
1165
+ */
1166
+ export declare function activate(state: ActivationState, names: Iterable<string>, at: number): ActivationState;
1167
+ /**
1168
+ * Record a call — the freshness of a session-activated tool and the evidence a
1169
+ * compaction keeps it by.
1170
+ *
1171
+ * `active` is refreshed exactly as before: a call is what keeps a
1172
+ * session-activated tool offered. `used` records the call itself, but only for
1173
+ * this plugin's own namespace: the core tools (`read`, `bash`, …) ride the same
1174
+ * `tools/result` hook, and they are no part of a session's MCP activation state.
1175
+ * A baseline name is not recorded either — the durable baseline already keeps it
1176
+ * offered, so recording the call would only make a compaction look like it
1177
+ * changed something.
1178
+ *
1179
+ * @param state - activation state before the call.
1180
+ * @param name - public name of the called tool.
1181
+ * @param at - epoch milliseconds of the call.
1182
+ * @returns the updated state, or the input when nothing changed.
1183
+ */
1184
+ export declare function noteUse(state: ActivationState, name: string, at: number): ActivationState;
1185
+ /**
1186
+ * Drop the session-activated tools that have not been called for `idleMs`.
1187
+ * The baseline is never pruned: it comes from the durable counters, not from the
1188
+ * session. `idleMs <= 0` disables pruning.
1189
+ *
1190
+ * A positive `idleMs` is an explicit opt-in to *forgetting*: an evicted name
1191
+ * leaves the used record with the offer it was about, so the sweep is final —
1192
+ * a later compaction cannot read the call back and resurrect what time already
1193
+ * dropped. A name the model needs again is activated again through search. The
1194
+ * names still inside the window keep their record, and a sweep that evicts
1195
+ * nothing returns its input.
1196
+ *
1197
+ * @param state - activation state at `now`.
1198
+ * @param now - epoch milliseconds of the sweep.
1199
+ * @param idleMs - age at which a tool falls out.
1200
+ * @returns the updated state, or the input when nothing was stale.
1201
+ */
1202
+ export declare function pruneIdle(state: ActivationState, now: number, idleMs: number): ActivationState;
1203
+ /**
1204
+ * End the session's activations that no call backs, at the compaction boundary.
1205
+ *
1206
+ * A compaction rewrites the conversation, so the provider's prompt prefix is
1207
+ * recomputed anyway: this is the one boundary where dropping a tool costs no
1208
+ * cache, which is why idle time is off by default and why this is the only place
1209
+ * the offered set shrinks. Only the part the session never used goes — an offer
1210
+ * from a context match or a search that the model did not act on. A tool this
1211
+ * session did call is one it really uses, so it stays active, stamped with its
1212
+ * last touch; evicting it would charge a re-discovery step for a tool the
1213
+ * session demonstrably needs. A used name that was never activated falls back to
1214
+ * the compaction's own clock. The counter baseline is never pruned.
1215
+ *
1216
+ * The used record is cumulative for the session and deliberately never bounded:
1217
+ * with the shipped `DEFAULT_TOOL_IDLE_MS` of `0` nothing else removes a name, so
1218
+ * a tool the session used stays offered for the rest of the session, across every
1219
+ * further compaction. This boundary shrinks the offers no call backs — it never
1220
+ * shrinks one the session used again.
1221
+ *
1222
+ * @param state - activation state before the compaction.
1223
+ * @param at - epoch milliseconds of the compaction.
1224
+ * @returns the updated state, or the input when nothing was active or used, or
1225
+ * when the rebuild is equivalent to what is already there — a caller compares
1226
+ * by identity to tell a real change from a boundary that changed nothing.
1227
+ */
1228
+ export declare function onCompaction(state: ActivationState, at: number): ActivationState;
1229
+ /**
1230
+ * Every name this session currently offers: the baseline plus the session's own
1231
+ * activations.
1232
+ * @param state - current activation state.
1233
+ * @returns the union; the baseline itself when nothing is session-activated.
1234
+ */
1235
+ export declare function presentedNames(state: ActivationState): ReadonlySet<string>;
1236
+ /**
1237
+ * Merge the session's active schemas into an already assembled tool list.
1238
+ *
1239
+ * Total and side-effect free: it copies the base list, never removes or reorders
1240
+ * an entry that is already there, and only appends an active schema that the
1241
+ * base does not already carry and that `available` actually publishes (a stale
1242
+ * baseline name of a server that is no longer mounted is silently skipped).
1243
+ * Missing schemas are inserted at their sorted position, so with the canonical
1244
+ * (lexicographic) base order DSH produces the result stays sorted; a deployment
1245
+ * with a custom `toolOrder` keeps its existing entries exactly where they were.
1246
+ *
1247
+ * @param baseTools - the assembly's tool list as the inner listeners left it.
1248
+ * @param available - live schemas this plugin may offer for the session.
1249
+ * @param activeNames - baseline plus session-activated public names.
1250
+ * @returns a new list; equal input yields an equal list.
1251
+ */
1252
+ export declare function withActiveTools(baseTools: readonly ToolSchemaLike[], available: readonly ToolSchemaLike[], activeNames: ReadonlySet<string>): ToolSchemaLike[];
1253
+ /**
1254
+ * The context-driven tier's state: a sticky window over the BM25 ranking of the
1255
+ * session's available tools.
1256
+ *
1257
+ * `window` maps a name to the decision that put it there, so a later decision
1258
+ * can count how long the name has been offered without renumbering anything.
1259
+ * {@link autoPresentedNames} reads the offered set back out. The state is
1260
+ * immutable; a decision that changes nothing returns its input object.
1261
+ */
1262
+ interface AutoOfferState {
1263
+ /** Name -> decision stamp of every name still inside the sticky window. */
1264
+ readonly window: ReadonlyMap<string, number>;
1265
+ }
1266
+ /** Construction options for the `mcp_search_tools` definition. */
1267
+ interface SearchToolOptions {
1268
+ /** Live schemas the search matches and may activate: the whole visible MCP surface. */
1269
+ readonly available: () => readonly ToolSchemaLike[];
1270
+ /** Record the matched names as activated for the session. */
1271
+ readonly activate: (names: readonly string[]) => void;
1272
+ /** Cap applied when a call omits `limit`; defaults to {@link DEFAULT_SEARCH_LIMIT}. */
1273
+ readonly defaultLimit?: number;
1274
+ }
1275
+ /**
1276
+ * Build the `mcp_search_tools` definition.
1277
+ *
1278
+ * The tool never pretends: a query that matches nothing says so, and it only
1279
+ * ever offers schemas its session actually sees (the caller supplies that
1280
+ * filtered list). Activating is enough to present a tool from the *next* step
1281
+ * on, because the assembly listener reads the state at every request.
1282
+ *
1283
+ * @param options - the session's visible schemas and activation sink.
1284
+ * @returns a registry-ready definition.
1285
+ */
1286
+ export declare function createSearchTool(options: SearchToolOptions): ToolDefinitionLike;
1287
+ /** What the wiring needs from the runtime; everything is read at use time. */
1288
+ interface ActivationWiringOptions {
1289
+ /** Agent-scoped context; both the listener and the search tool live here. */
1290
+ readonly ctx: ActivationContextLike;
1291
+ /** Current activation state of the session. */
1292
+ readonly state: () => ActivationState;
1293
+ /** Replace the session's activation state after a transition. */
1294
+ readonly setState: (next: ActivationState) => void;
1295
+ /** Live schemas of the tools this plugin mounted for the session. */
1296
+ readonly available: () => readonly ToolSchemaLike[];
1297
+ /**
1298
+ * Every MCP schema the session sees — the profile plane, this plugin's own
1299
+ * mounts, and any F-19 forwarders — beyond {@link available}. The deferral
1300
+ * budget and the discovery tool count this whole surface, while the
1301
+ * context-driven tier and the usage counters keep reading `available` alone.
1302
+ * Absent means `available` is the whole surface, so a deployment whose
1303
+ * presentation owner already hides the profile plane keeps today's behaviour.
1304
+ */
1305
+ readonly visible?: () => readonly ToolSchemaLike[];
1306
+ /**
1307
+ * Names that belong to ANOTHER project mounted in this process, which this
1308
+ * session must never be offered. The runtime computes the set from the other
1309
+ * projects it manages, and the assembly listener drops every such name from
1310
+ * the assembled request — whatever the tool mode, and however large the
1311
+ * surface. The budget and the discovery tool keep counting the whole visible
1312
+ * surface, so this only trims the final list and never re-feeds the deferral
1313
+ * decision. Absent means nothing is foreign, which keeps a deployment without
1314
+ * the containment probe on today's behaviour.
1315
+ */
1316
+ readonly foreign?: () => ReadonlySet<string>;
1317
+ /** Cap on the tools one search activates; defaults to {@link DEFAULT_SEARCH_LIMIT}. */
1318
+ readonly searchLimit?: number;
1319
+ /**
1320
+ * Cap on the names the context-driven tier offers at once; defaults to
1321
+ * {@link DEFAULT_AUTO_ACTIVATION_LIMIT}, and `0` disables the tier.
1322
+ */
1323
+ readonly autoLimit?: number;
1324
+ /** Extra advances a context offer survives; defaults to {@link DEFAULT_AUTO_ACTIVATION_STICKY_STEPS}. */
1325
+ readonly autoStickySteps?: number;
1326
+ /** Lowest BM25 score the context-driven tier may offer; defaults to {@link MIN_AUTO_SCORE}. */
1327
+ readonly autoMinScore?: number;
1328
+ /**
1329
+ * Serialized size of the MCP surface, in characters, above which this module
1330
+ * defers tools at all; defaults to {@link DEFAULT_TOOL_BUDGET_CHARS}. `0`
1331
+ * defers every surface, however small.
1332
+ */
1333
+ readonly toolBudgetChars?: number;
1334
+ /**
1335
+ * Live tool policy of the session's project; absent means the shipped default,
1336
+ * {@link DEFAULT_TOOL_POLICY}. Read at every assembly, so a mode or pin change
1337
+ * applies from the next step on, without re-minting the scope.
1338
+ */
1339
+ readonly policy?: () => ToolPolicy;
1340
+ /**
1341
+ * Number of the agent step this plugin is currently on, counted by the caller
1342
+ * from its own `agent/pre-step` hook. Read when a search activates names, so
1343
+ * the record of that offer carries the step it happened on. Absent means the
1344
+ * caller counts no steps, and then an activation records none.
1345
+ */
1346
+ readonly step?: () => number;
1347
+ /**
1348
+ * Told the names one search just activated, and the step it happened on, so
1349
+ * the caller can keep that stamp for the lifetime of the session — longer
1350
+ * than one scope's wiring, which an idle release disposes. Absent drops the
1351
+ * stamp: the offer is still recorded, it simply carries no step.
1352
+ */
1353
+ readonly onActivated?: (names: readonly string[], step: number) => void;
1354
+ /**
1355
+ * Told that a compaction ended some of the session's activations, so the
1356
+ * caller can drop the step records that belonged to the ones it removed.
1357
+ * Absent leaves the records in place, which only means a later activation of
1358
+ * the same name may carry the step of the offer the compaction removed.
1359
+ */
1360
+ readonly onCompaction?: () => void;
1361
+ /** Context-driven state to start from; defaults to an empty state. */
1362
+ readonly autoState?: AutoOfferState;
1363
+ /** Sink for the context-driven state after every advance that changed it. */
1364
+ readonly setAutoState?: (next: AutoOfferState) => void;
1365
+ /** Sink for a contained failure of this plugin's own work. */
1366
+ readonly onError?: (error: unknown) => void;
1367
+ }
1368
+ /**
1369
+ * Install the session wiring on one agent scope: the `system-prompt/assemble`
1370
+ * listener, the `mcp_search_tools` registration, and the `session/event`
1371
+ * listener that feeds compaction, the task context, and the recent-call names.
1372
+ *
1373
+ * The listener is prepended so it is the **outermost** handler of the waterfall:
1374
+ * `next()` has already run every plugin that filters the catalogue (the
1375
+ * `dsh-progressive-tools` presentation this replaces), and the list it returns is
1376
+ * the one that runs. Idle pruning is not wired here — the runtime already
1377
+ * watches `agent/status`, and it calls {@link pruneIdle} on that transition.
1378
+ *
1379
+ * The context-driven tier advances only when the task context actually moves: a
1380
+ * new user message or a new tool call. When it does, and the resulting offered
1381
+ * set is the one the previous advance produced, this returns the identical
1382
+ * assembly object, so nothing downstream treats the tool list as changed.
1383
+ *
1384
+ * @param options - scope, session state accessors, and the mounted-schema probe.
1385
+ * @returns the disposer that unregisters everything installed here.
1386
+ */
1387
+ export declare function installActivation(options: ActivationWiringOptions): () => void;
1388
+ //#endregion
1389
+ //#region src/shared.d.ts
1390
+ /** Route prefix the host serves and the sidebar panel fetches. */
1391
+ export declare const ROUTE_PREFIX = "/project-mcp";
1392
+ /** Sidebar tab id; also the `SidebarTab.type` the panel opens as. */
1393
+ export declare const TAB_ID = "dsh-project-mcp:servers";
1394
+ /** Pin or unpin one tool of one project. */
1395
+ interface PinRequest {
1396
+ /** Project root the tool belongs to. */
1397
+ readonly projectRoot: string;
1398
+ /** Public registry name, eg `mcp__tglider__workspace`. */
1399
+ readonly tool: string;
1400
+ /** `true` pins it, `false` unpins it. */
1401
+ readonly pinned: boolean;
1402
+ }
1403
+ /** Set one project's tool mode. Pins travel in their own request. */
1404
+ interface PolicyRequest {
1405
+ /** Project root the mode applies to. */
1406
+ readonly projectRoot: string;
1407
+ /** The mode to store. */
1408
+ readonly mode: ToolMode;
1409
+ }
1410
+ /**
1411
+ * Choose which declaration of one contested `serverName` a project shows.
1412
+ *
1413
+ * The name stays the profile's either way; the answer decides whether the
1414
+ * project's own entry mounts beside it under a local namespace. The name is
1415
+ * carried as declared — the sanitized `mcpServers` key — because that is what
1416
+ * the conflict report names, and the local name is the plugin's to compute.
1417
+ */
1418
+ interface ConflictRequest {
1419
+ /** Project root the name belongs to. */
1420
+ readonly projectRoot: string;
1421
+ /** Contested `serverName`, as the project declared it. */
1422
+ readonly server: string;
1423
+ /** The declaration to show. */
1424
+ readonly choice: ConflictChoice;
1425
+ }
1426
+ /**
1427
+ * One entry a save writes.
1428
+ *
1429
+ * The panel submits the {@link EntrySnapshot} it was given, with the fields the
1430
+ * user changed. A masked `env`/`headers` key submitted without a `value` keeps
1431
+ * whatever the document declares for it; a key the submission omits is removed.
1432
+ */
1433
+ interface SaveRequest {
1434
+ /** Project root the edited row belongs to. */
1435
+ readonly projectRoot: string;
1436
+ /** `serverName` being edited. */
1437
+ readonly server: string;
1438
+ /** Absolute path of the document the entry came from. */
1439
+ readonly document: string;
1440
+ /** `documentRevision` the edit was built from; a mismatch refuses the write. */
1441
+ readonly revision: string;
1442
+ /** `true` acknowledges a write to the global tier; required only there. */
1443
+ readonly consent?: boolean;
1444
+ /** The entry body to write. */
1445
+ readonly entry: EntrySnapshot;
1446
+ }
1447
+ /** Error codes a save answers with, each with its own sentence in the panel. */
1448
+ type SaveErrorCode =
1449
+ /** The entry is not one this plugin would mount; nothing was written. */
1450
+ 'invalid' |
1451
+ /** The document may not be written: profile, `<DSH_HOME>`, or no consent. */
1452
+ 'blocked' |
1453
+ /** The document changed since the snapshot was taken; nothing was written. */
1454
+ 'conflict' |
1455
+ /** The document or the server is no longer there. */
1456
+ 'not-found' |
1457
+ /** The write itself failed; the document is left as it was. */
1458
+ 'failed';
1459
+ //#endregion
1460
+ //#region src/runtime.d.ts
1461
+ /** Live agent handle: only the fields this plugin consumes. */
1462
+ interface AgentLike {
1463
+ /** Session id, unique per agent. */
1464
+ readonly id: string;
1465
+ /** Session header carrying the working directory. */
1466
+ readonly session: {
1467
+ readonly header?: {
1468
+ readonly cwd?: string;
1469
+ };
1470
+ };
1471
+ /**
1472
+ * Host-reported lifecycle status, when the composition publishes one. Read
1473
+ * live where a release decision needs the truth rather than the last event
1474
+ * this plugin happened to see.
1475
+ */
1476
+ readonly status?: 'idle' | 'running';
1477
+ /** The agent's own Cordis context. */
1478
+ readonly ctx: Context;
1479
+ }
1480
+ /** The subset of `ctx.agents` used here. */
1481
+ interface AgentsLike {
1482
+ /** All live agents. */
1483
+ list(): AgentLike[];
1484
+ }
1485
+ /** One agent-plane event, as far as this plugin consumes it. */
1486
+ interface AgentEventLike {
1487
+ /** The subject agent. */
1488
+ agent: AgentLike;
1489
+ /** `agent/status` only: whether a turn is currently running. */
1490
+ status?: 'idle' | 'running';
1491
+ }
1492
+ /** The subset of the hosting scope used here. */
1493
+ interface AgentScopeLike {
1494
+ /** Agent registry (injected). */
1495
+ readonly agents: AgentsLike;
1496
+ /**
1497
+ * Subscribe to an agent lifecycle or turn event. `agent/pre-step` is a
1498
+ * waterfall hook, so its handler receives a continuation and must return it.
1499
+ */
1500
+ on(name: string, handler: (event: AgentEventLike, next: () => Promise<unknown>) => unknown): unknown;
1501
+ /** Register a fiber-scoped cleanup. */
1502
+ effect(fn: () => unknown, label?: string): unknown;
1503
+ }
1504
+ /** Resolved plugin configuration. */
1505
+ interface RuntimeConfig {
1506
+ /**
1507
+ * Project-relative MCP documents to read, lowest priority first. A spec is
1508
+ * relative to the project root, or absolute / `~/…` / `$DSH_HOME/…`.
1509
+ */
1510
+ localFiles: string[];
1511
+ /**
1512
+ * Global MCP documents read before a project's own, lowest priority first;
1513
+ * `[]` reads none.
1514
+ */
1515
+ globalFiles: string[];
1516
+ /**
1517
+ * Read the project's own dotenv documents (`<project>/.env` and
1518
+ * `<project>/.dsh/.env`) for `${...}` values.
1519
+ */
1520
+ envFiles?: boolean;
1521
+ inputs: Record<string, string>;
1522
+ projectMarkers: string[];
1523
+ fileMarkers: string[];
1524
+ toolCallTimeoutMs: number;
1525
+ failOnStartupError: boolean;
1526
+ /** Window after which a mount that produced no tool is reported as an error; `0` disables. */
1527
+ connectTimeoutMs: number;
1528
+ /** Mount a session's project on its first turn instead of at session creation. */
1529
+ lazy: boolean;
1530
+ /** Release a session's mounts after this much inactivity; `0` disables. */
1531
+ idleTimeoutMs: number;
1532
+ /** How long the first step of a turn may wait for a pending mount; `0` never waits. */
1533
+ activationWaitMs: number;
1534
+ profileWins: boolean;
1535
+ /**
1536
+ * Local namespace a project entry takes when a profile-level instance already
1537
+ * owns its `serverName` and the user chose to see the project's copy too.
1538
+ * Empty asks for one derived from the project's own folder
1539
+ * (`src/naming.ts`, {@link isValidLocalPrefix}); never longer than five
1540
+ * characters, because it is a name a person has to read in front of every
1541
+ * tool of that server.
1542
+ */
1543
+ localPrefix: string;
1544
+ watch: boolean;
1545
+ debounceMs: number;
1546
+ rescanIntervalMs: number;
1547
+ credentialsFile: string;
1548
+ /**
1549
+ * Offer the session's MCP tools through `mcp_search_tools` + activation, and
1550
+ * put the active ones back into each assembled request. Optional so a config
1551
+ * object that predates this feature keeps the shipped default.
1552
+ */
1553
+ activationEnabled?: boolean;
1554
+ /** Total tools the durable counters may seed into the baseline; `0` seeds none. */
1555
+ activationSeeded?: number;
1556
+ /** Calls one tool needs in the counters before it is seeded into the baseline. */
1557
+ activationMinCalls?: number;
1558
+ /** Drop a session-activated tool after this long without a call; `0` disables. */
1559
+ toolIdleMs?: number;
1560
+ /**
1561
+ * Publish one short project-MCP guidance section in the session's system
1562
+ * prompt, just ahead of the per-server `mcp:<server>` instruction blocks.
1563
+ * `false` registers no section at all. Optional so a config object that
1564
+ * predates this feature keeps the shipped default.
1565
+ */
1566
+ guidanceEnabled?: boolean;
1567
+ /**
1568
+ * Cap on the names the context-driven tier offers at once; `0` disables the
1569
+ * tier. Optional so a config object that predates this feature keeps the
1570
+ * shipped default.
1571
+ */
1572
+ activationAutoLimit?: number;
1573
+ /** Extra advances one context-driven offer survives after leaving the ranking. */
1574
+ activationAutoStickySteps?: number;
1575
+ /**
1576
+ * Serialized size of a session's MCP surface, in characters, above which its
1577
+ * tools are offered on demand instead of being listed; `0` defers every
1578
+ * surface, however small.
1579
+ */
1580
+ activationToolBudgetChars?: number;
1581
+ /**
1582
+ * Permit writes to the documents of the `globalFiles` list. Off by default:
1583
+ * a global write needs both this switch and an explicit per-write `consent`,
1584
+ * so a panel mistake cannot rewrite every project's servers. Optional so a
1585
+ * config object that predates this feature keeps it disabled.
1586
+ */
1587
+ allowGlobalWrite?: boolean;
1588
+ }
1589
+ /**
1590
+ * Outcome of {@link ProjectMcpRuntime.saveEntry}: the fresh snapshot after a
1591
+ * write, or the code the route maps to a status.
1592
+ */
1593
+ type SaveOutcome = {
1594
+ readonly ok: true;
1595
+ readonly snapshot: McpSnapshot;
1596
+ } | {
1597
+ readonly ok: false;
1598
+ readonly code: SaveErrorCode;
1599
+ readonly message: string;
1600
+ /**
1601
+ * Stable wire code of `message` (`projectMcp.host` namespace), for
1602
+ * client-side translation (F-48); the prose `message` keeps its
1603
+ * byte-identical English and stays the fallback.
1604
+ */
1605
+ readonly messageCode?: string;
1606
+ /** Flat params of {@link messageCode}, stringified at emission. */
1607
+ readonly messageParams?: Record<string, string>;
1608
+ };
1609
+ /**
1610
+ * Outcome of {@link ProjectMcpRuntime.setPin} and
1611
+ * {@link ProjectMcpRuntime.setPolicy}: the fresh snapshot after the store was
1612
+ * changed, or the code the route maps to a status. Both refusals are `400`s:
1613
+ * `not-found` for a project this host has no live session in, `invalid` for a
1614
+ * mode no assembly knows, `failed` when the host was built without a policy
1615
+ * store.
1616
+ */
1617
+ type PolicyOutcome = {
1618
+ readonly ok: true;
1619
+ readonly snapshot: McpSnapshot;
1620
+ } | {
1621
+ readonly ok: false;
1622
+ readonly code: SaveErrorCode;
1623
+ readonly message: string;
1624
+ /** Wire code of `message`, the same contract as {@link SaveOutcome}'s. */
1625
+ readonly messageCode?: string;
1626
+ /** Flat params of {@link messageCode}, stringified at emission. */
1627
+ readonly messageParams?: Record<string, string>;
1628
+ };
1629
+ /**
1630
+ * Outcome of {@link ProjectMcpRuntime.toolFactsOf}: one tool's on-demand detail,
1631
+ * or the code the route maps to a status.
1632
+ *
1633
+ * A refusal is a `404`: the route only asks about a project root, a session id
1634
+ * and a name a panel read from a snapshot, so one this host does not know is a
1635
+ * stale read rather than a malformed request — the three parameters themselves
1636
+ * are checked by the route. The prose stays plain English and uncoded, the way
1637
+ * `GET logs` refuses.
1638
+ */
1639
+ type ToolFactsOutcome = {
1640
+ readonly ok: true;
1641
+ readonly value: ToolFacts;
1642
+ } | {
1643
+ readonly ok: false;
1644
+ readonly code: SaveErrorCode;
1645
+ readonly message: string;
1646
+ };
1647
+ /**
1648
+ * Identity of the Cordis scope one project's servers are mounted in. Every
1649
+ * session of that project is parented to it, so the registrations inside are
1650
+ * visible to those sessions and to nobody else.
1651
+ */
1652
+ interface ProjectScopeKey {
1653
+ /** Project root whose sessions share this scope. */
1654
+ readonly projectRoot: string;
1655
+ }
1656
+ /** Injection points that tests override; production uses the real defaults. */
1657
+ interface RuntimeOptions {
1658
+ /** Plugin object mounted per server; defaults to `@deepseek-ai/dsh-mcp-client`. */
1659
+ plugin?: unknown;
1660
+ /**
1661
+ * Scope factory; defaults to `createScope` from `@deepseek-ai/dsh-scope`.
1662
+ * Called once per session and once per project that mounts something. The
1663
+ * parent link of a session scope is established by the runtime itself, before
1664
+ * this is called — the factory only mints the scope. A session key is the
1665
+ * agent's own scope key; a project key is a {@link ProjectScopeKey}.
1666
+ */
1667
+ createScope?: (ctx: Context, key: AgentLike | ProjectScopeKey) => Pick<Scope, 'ctx' | 'dispose'>;
1668
+ /**
1669
+ * Registry surface the forwarding bridge reads: one scoped lookup. It is read
1670
+ * off the plugin's own context by default, which is the same `ctx.tools` the
1671
+ * registration path uses; tests override it with their double's registry.
1672
+ */
1673
+ registry?: BridgeRegistryLike;
1674
+ /**
1675
+ * Bridge context factory; defaults to reading the scope tag
1676
+ * ({@link scopeOf}) from the minted scope's context and wiring the registry
1677
+ * getter to it. A test whose scope double is a plain object overrides this,
1678
+ * because its contexts carry no `dsh-scope` tag to read.
1679
+ */
1680
+ bridgeContext?: (scope: Pick<Scope, 'ctx' | 'dispose'>) => BridgeContextLike;
1681
+ /** Durable counters `snapshot()` publishes alongside the rows; absent means none. */
1682
+ usage?: UsageSource;
1683
+ /**
1684
+ * Durable per-project policy the snapshot publishes and the assembly reads;
1685
+ * absent means every project keeps {@link DEFAULT_TOOL_POLICY}.
1686
+ */
1687
+ policy?: PolicySource;
1688
+ }
1689
+ /** Read-only view of the durable counters, consulted by {@link ProjectMcpRuntime.snapshot}. */
1690
+ interface UsageSource {
1691
+ /** Counters recorded for one project root, or `undefined` when it has none. */
1692
+ forProject(projectRoot: string): Record<string, ServerUsage> | undefined;
1693
+ }
1694
+ /**
1695
+ * The durable policy as the runtime consumes it: read on every snapshot and
1696
+ * every assembly, written by the two panel service methods. Structural on
1697
+ * purpose, so a test can pass a plain object and the plugin does not depend on
1698
+ * the store class.
1699
+ */
1700
+ interface PolicySource {
1701
+ /** Policy of one project root; the shipped default when none is stored. */
1702
+ forProject(projectRoot: string): ToolPolicy;
1703
+ /** Store one project's mode and return the policy now in force. */
1704
+ setMode(projectRoot: string, mode: ToolMode): ToolPolicy;
1705
+ /** Pin or unpin one tool of one project and return the policy now in force. */
1706
+ setPin(projectRoot: string, tool: string, pinned: boolean): ToolPolicy;
1707
+ /**
1708
+ * Store which declaration of one contested `serverName` the project shows and
1709
+ * return the policy now in force.
1710
+ */
1711
+ setConflictChoice(projectRoot: string, server: string, choice: ConflictChoice): ToolPolicy;
1712
+ }
1713
+ /**
1714
+ * What this plugin currently mounts for one live agent: the project root the
1715
+ * agent resolved to and the server names it mounted there.
1716
+ */
1717
+ interface AgentMounts {
1718
+ /** Project root the agent's working directory resolved to. */
1719
+ projectRoot: string;
1720
+ /** Names of the servers this plugin mounted for that agent right now. */
1721
+ servers: ReadonlySet<string>;
1722
+ }
1723
+ /** Minimal fiber surface used for mount bookkeeping. */
1724
+ interface MountFiber {
1725
+ dispose(): unknown;
1726
+ await?(): Promise<unknown>;
1727
+ }
1728
+ /** Why one pass may start a project's servers for one session. */
1729
+ type MountTrigger = 'turn' | 'mounted' | 'eager' | 'operator';
1730
+ /** What one session contributes to the mount decision of one pass. */
1731
+ interface MountDecision {
1732
+ /** Whether `lazy` is on: without it a session mounts as soon as it exists. */
1733
+ lazy: boolean;
1734
+ /** This session's own turn asked for its project (a pre-step or a `running` status). */
1735
+ activationPending: boolean;
1736
+ /** This session already holds mounts, so a pass reconciles them live. */
1737
+ mounted: boolean;
1738
+ /** An operator asked for exactly this session (`syncNow`, `retry`, an edit). */
1739
+ operatorRequested: boolean;
1740
+ }
1741
+ /**
1742
+ * Sessions one pass may mount without their own turn asking: `'all'` for an
1743
+ * operator call that reconciles every session, a set of session ids for a pass
1744
+ * that belongs to one project, the project root itself for an operator call
1745
+ * scoped to a project — matched while the pass runs, so it also covers a session
1746
+ * whose working directory has not been read yet — and no requests at all for a
1747
+ * pass driven by a turn, an event or the rescan tick.
1748
+ */
1749
+ type PassRequests = 'all' | ReadonlySet<string> | {
1750
+ readonly projectRoot: string;
1751
+ };
1752
+ /**
1753
+ * Decide whether one pass may start servers for one session, and why.
1754
+ *
1755
+ * The plugin's isolation rule lives here: a session starts the servers of the
1756
+ * project its working directory resolves to only when *that* session asks to
1757
+ * work there — its own turn, an operator request that names it, or a
1758
+ * deployment that turned `lazy` off. A session that is merely live (restored,
1759
+ * listed, idle, or another session's neighbour) never starts anything, and a
1760
+ * session that already holds mounts is reconciled so edits reach them.
1761
+ * @param decision - what one session contributes to one pass.
1762
+ * @returns the trigger, or `undefined` when the session must stay idle.
1763
+ */
1764
+ export declare function mountTrigger(decision: MountDecision): MountTrigger | undefined;
1765
+ interface MountedInstance {
1766
+ name: string;
1767
+ /**
1768
+ * The `serverName` this mount actually registers under: the declared name, or
1769
+ * the local alias when a profile instance owns the declared one. It is what
1770
+ * the registry prefixes this server's tools with, so every lookup that goes by
1771
+ * tool prefix — status, guidance, the activation baseline — reads this and
1772
+ * never {@link name}.
1773
+ */
1774
+ runtimeName: string;
1775
+ /** Project root whose declaration this instance was mounted from. */
1776
+ projectRoot: string;
1777
+ fingerprint: string;
1778
+ fiber: MountFiber | undefined;
1779
+ status: ServerStatus;
1780
+ detail: string | undefined;
1781
+ /** Wire companions of {@link MountedInstance.detail} (F-48), set with it. */
1782
+ detailCode: string | undefined;
1783
+ detailParams: Record<string, string> | undefined;
1784
+ source: string | undefined;
1785
+ transport: 'stdio' | 'streamable-http' | undefined;
1786
+ /** Endpoint label already stripped of arguments and query strings. */
1787
+ endpoint: string;
1788
+ /** When this mount started, for the connect watchdog. */
1789
+ startedAt: number;
1790
+ /** `true` once the watchdog has reported the mount as never connected. */
1791
+ stalled: boolean;
1792
+ /** `true` when activation itself failed, so no retry can revive this fiber. */
1793
+ failed: boolean;
1794
+ }
1795
+ /**
1796
+ * The forwarding bridge one session holds when its key could not be joined to
1797
+ * its project's chain: the thin definitions registered in the session's own
1798
+ * layer, and the subscription that keeps them level with the project's live
1799
+ * tool set.
1800
+ */
1801
+ interface BridgeForwarders {
1802
+ /**
1803
+ * The session's live registration batch. It owns the swap and the re-entrancy
1804
+ * every registration forces on it (`tools/change` is emitted from inside the
1805
+ * insertion, and the session is subscribed to it).
1806
+ */
1807
+ readonly batch: ForwardBatch;
1808
+ /** Disposer of the project-scope `tools/change` subscription. */
1809
+ detach: () => void;
1810
+ }
1811
+ /**
1812
+ * Where one session's MCP instances live — one home per project, forever.
1813
+ *
1814
+ * A session whose scope key could be parented to its project resolves the
1815
+ * project's shared home directly: one scope and one process per declared
1816
+ * server, shared by every session that works there. A session whose key the
1817
+ * harness already parented to something else cannot join that chain —
1818
+ * `dsh-scope` binds a key once, and the agent-preset roster binds every
1819
+ * composed agent before it is published — so it holds the SAME project home and
1820
+ * reads it through the forwarding bridge: a thin definition in its own layer
1821
+ * whose call runs the project's own. That is what makes "one process per
1822
+ * project" true in a preset composition too, instead of one instance per
1823
+ * session. See `docs/design/contracts/bridge.md`.
1824
+ */
1825
+ interface MountHome {
1826
+ /** The project root whose declarations this home serves. */
1827
+ projectRoot: string;
1828
+ /** Scope key the mcp-client instances are mounted under. */
1829
+ key: AgentLike | ProjectScopeKey;
1830
+ /** The scope those instances live in; `undefined` before the first mount. */
1831
+ scope: Pick<Scope, 'ctx' | 'dispose'> | undefined;
1832
+ /** One live instance per declared `serverName`. */
1833
+ mounts: Map<string, MountedInstance>;
1834
+ /** `true` when every session of the project shares this home. */
1835
+ shared: boolean;
1836
+ }
1837
+ /**
1838
+ * One project's shared mount state: the scope its sessions' servers are
1839
+ * registered in, and the live mounts those sessions share. The scope is minted
1840
+ * with the project's first mount and dropped with its last holder, so a project
1841
+ * costs one scope and one process per declared server however many sessions
1842
+ * work in it.
1843
+ */
1844
+ interface ProjectState extends MountHome {
1845
+ projectRoot: string;
1846
+ /** Scope key the project's registrations are tagged with. */
1847
+ key: ProjectScopeKey;
1848
+ /** The project scope; `undefined` before the first mount and after teardown. */
1849
+ scope: Pick<Scope, 'ctx' | 'dispose'> | undefined;
1850
+ /** One live instance per declared `serverName`, shared by every holder. */
1851
+ mounts: Map<string, MountedInstance>;
1852
+ shared: true;
1853
+ }
1854
+ interface AgentState {
1855
+ agent: AgentLike;
1856
+ cwd: string | undefined;
1857
+ projectRoot: string | undefined;
1858
+ /**
1859
+ * Digest of the last reconciled pass: the document set, the profile
1860
+ * reservations, and the published state of the shared mounts. Identical means
1861
+ * "nothing to do" — including when another session of the same project
1862
+ * mounted, settled or dropped something this session would otherwise render
1863
+ * from a stale row.
1864
+ */
1865
+ digest: string | undefined;
1866
+ scope: Pick<Scope, 'ctx' | 'dispose'> | undefined;
1867
+ /**
1868
+ * The project whose shared mounts this session currently holds; `undefined`
1869
+ * while it holds none. Every holder resolves the one home, whether its own key
1870
+ * joined the project's chain or the bridge carries the tools to it.
1871
+ */
1872
+ project: ProjectState | undefined;
1873
+ /**
1874
+ * The forwarding bridge this session holds when its key could not be parented
1875
+ * to its project (the harness bound that key first, and `dsh-scope` binds a
1876
+ * key once). `undefined` for a session whose own chain already resolves the
1877
+ * project's layer, which needs no bridge.
1878
+ */
1879
+ bridge: BridgeForwarders | undefined;
1880
+ /**
1881
+ * Whether {@link linkScopeParent} linked this session's key, so a detach knows
1882
+ * it owns the re-link and not another plugin that parented the same key.
1883
+ */
1884
+ parentLinked: boolean;
1885
+ /**
1886
+ * Layer-less scope key a released session is re-linked to. Without it a
1887
+ * session that let a project's servers go would keep resolving them from the
1888
+ * still-running shared layer — the one thing per-session mounting gave for
1889
+ * free, because disposing the session scope removed its whole chain.
1890
+ */
1891
+ detachedKey: object | undefined;
1892
+ rows: ServerRow[];
1893
+ issues: SnapshotIssue[];
1894
+ /**
1895
+ * `serverName` conflicts of the last reconciled pass: a profile-level
1896
+ * instance that already owns a name, or one name two project documents
1897
+ * declare. Always the truth of that pass — an empty list is the answer "no
1898
+ * conflicts", not an absent one.
1899
+ */
1900
+ conflicts: ServerConflict[];
1901
+ /** Last observed activity (turn start, step, turn end); `undefined` until then. */
1902
+ lastActivityAt: number | undefined;
1903
+ /** `true` while a turn runs, so idle release never fires in the middle of one. */
1904
+ busy: boolean;
1905
+ /**
1906
+ * Set when a turn starts while nothing is mounted, so the next pass mounts
1907
+ * the project even in `lazy` mode. Cleared by the pass that mounts it.
1908
+ */
1909
+ activationPending: boolean;
1910
+ /**
1911
+ * Session activation state (counter baseline + session-activated names).
1912
+ * `undefined` until the session's first scope is minted and seeds it; kept
1913
+ * across an idle release so the session keeps what it activated.
1914
+ */
1915
+ activation: ActivationState | undefined;
1916
+ /**
1917
+ * Number of the agent step this session is on, counted from `agent/pre-step`
1918
+ * and starting at `1` for the first step the hook sees. `0` means no step has
1919
+ * started yet, and then no offer carries a number.
1920
+ */
1921
+ step: number;
1922
+ /**
1923
+ * Step each session activation was recorded on, keyed by public name. Kept
1924
+ * next to {@link AgentState.activation} because the two outlive an idle
1925
+ * release together: the activation is what a row lists, and this is when it
1926
+ * was offered. Pruned with the activation it belongs to.
1927
+ */
1928
+ steps: Map<string, number>;
1929
+ /**
1930
+ * Disposer of the activation wiring installed on the current scope. Kept so a
1931
+ * scope teardown unregisters `mcp_search_tools` explicitly: the scope fiber
1932
+ * owns that registration with the real registry, but a test host may publish a
1933
+ * plain `tools` stub, and the tool must disappear either way.
1934
+ */
1935
+ activationDispose: (() => void) | undefined;
1936
+ /**
1937
+ * Disposer of the guidance-section wiring installed on the current scope. Kept
1938
+ * for the same reason as {@link AgentState.activationDispose}: the scope fiber
1939
+ * owns the registration with the real prompt registry, but a host that
1940
+ * publishes a plain `systemPrompt` stub has only this path.
1941
+ */
1942
+ guidanceDispose: (() => void) | undefined;
1943
+ /**
1944
+ * Context-driven offer window (BM25 task ranking + sticky names). Kept next
1945
+ * to `activation` so a re-minted scope of the same session resumes the offers
1946
+ * it was showing instead of starting over — the same reason the activation
1947
+ * state outlives an idle release.
1948
+ */
1949
+ auto: AutoOfferState | undefined;
1950
+ }
1951
+ /**
1952
+ * Owns every project-scoped mount, the config watchers, and the rescan timer.
1953
+ * One instance per plugin fiber; `attach()` binds it to the agent service.
1954
+ */
1955
+ export declare class ProjectMcpRuntime {
1956
+ private readonly ctx;
1957
+ private readonly config;
1958
+ private readonly options;
1959
+ private readonly states;
1960
+ /** Projects with a live shared scope, keyed by project root. */
1961
+ private readonly projects;
1962
+ private readonly documents;
1963
+ /** Cached credentials document, re-read only when mtime/size change. */
1964
+ private secrets;
1965
+ /**
1966
+ * Dotenv values per project document, re-read only when mtime/size change.
1967
+ * Every pass of every session resolves `${...}` references, so an uncached
1968
+ * read here would cost one stat plus parse per file per session per pass.
1969
+ */
1970
+ private readonly envFiles;
1971
+ private readonly watchers;
1972
+ /** Config directories currently watched per project root. */
1973
+ private readonly watchedDirs;
1974
+ private readonly watchedRoots;
1975
+ private timer;
1976
+ private debounce;
1977
+ private chain;
1978
+ /** The host's live-session registry, once `attach()` has bound one. */
1979
+ private listAgents;
1980
+ /** `undefined` until a recursive watch has been attempted. */
1981
+ private recursiveWatch;
1982
+ private ready;
1983
+ private disposed;
1984
+ /** Panels watching the picture through the status channel. */
1985
+ private readonly listeners;
1986
+ /** Changes announced so far; the picture a stream opens on is revision `0`. */
1987
+ private revision;
1988
+ /** JSON of the last announced picture, so an unchanged pass announces nothing. */
1989
+ private announced;
1990
+ /**
1991
+ * Disposer of the DSH-log subscriber this runtime installs on the notification
1992
+ * service in {@link ProjectMcpRuntime.attach}. One subscription per live
1993
+ * runtime, dropped in {@link ProjectMcpRuntime.disposeAll}, so a re-mount
1994
+ * cannot leave a second logger reading the same events.
1995
+ */
1996
+ private detachLog;
1997
+ /**
1998
+ * @param ctx - the plugin's own context (host/root scope).
1999
+ * @param config - resolved plugin configuration.
2000
+ * @param options - mount overrides (tests only).
2001
+ */
2002
+ constructor(ctx: Context, config: RuntimeConfig, options?: RuntimeOptions);
2003
+ /** Bind to the agent service: existing agents, lifecycle events, rescan timer. */
2004
+ attach(scope: AgentScopeLike): void;
2005
+ /**
2006
+ * Merge one live-edited config into the running one.
2007
+ *
2008
+ * A DSH ≥ 0.1.7 host serves the volatile config keys as a profile-backed
2009
+ * form and re-resolves them on `loader/volatile-update` instead of
2010
+ * restarting the entry. Only those keys are taken from `next` — every other
2011
+ * key (documents, markers, credentials, the watch switch) stays whatever the
2012
+ * entry booted with, because nothing here re-reads it safely at runtime.
2013
+ * All volatile keys are consumed at use time, so the merge alone moves the
2014
+ * behavior.
2015
+ *
2016
+ * The one exception is the safety-net tick: it is armed once in
2017
+ * {@link ProjectMcpRuntime.attach}, yet its need — `watch || idleTimeoutMs
2018
+ * > 0` — flips with a live edit of `idleTimeoutMs`, so it is re-armed or
2019
+ * cleared here. Arming is reserved to an attached runtime: before
2020
+ * `attach()` the merge alone is enough, because `attach()` arms from the
2021
+ * merged values; after disposal nothing may come back.
2022
+ *
2023
+ * @param next - the freshly resolved config; only the volatile keys are read.
2024
+ */
2025
+ applyLiveConfig(next: RuntimeConfig): void;
2026
+ /**
2027
+ * Current snapshot: projects with live agents, their rows, and watched roots.
2028
+ *
2029
+ * Each project carries both a merge and the per-session split. The merge is
2030
+ * deliberately not "first session wins": sessions of one project mount
2031
+ * independently, so the same server can be mounted for one and idle for
2032
+ * another, and the panel must not report a running server as idle (or hide a
2033
+ * failing one) just because the idle session was registered first.
2034
+ *
2035
+ * A session that mounted tools also carries what it offers the model right
2036
+ * now (see {@link sessionTools}); the row is derived per call, never stored,
2037
+ * so a panel that polls after an activation sees it.
2038
+ */
2039
+ snapshot(): McpSnapshot;
2040
+ /**
2041
+ * Watch the picture instead of asking for it: the listener is told the current
2042
+ * state at once, then once per change that actually changes something — a pass
2043
+ * that committed, a mount that appeared or connected, a release, a save, a
2044
+ * policy write. A rescan that found the same servers announces nothing, so an
2045
+ * open panel receives no traffic for a project nothing is happening in.
2046
+ * @param listener - told the revision and the whole snapshot it belongs to.
2047
+ * @returns a disposer that stops watching.
2048
+ */
2049
+ subscribe(listener: (change: SnapshotChange) => void): () => void;
2050
+ /**
2051
+ * Announce the picture if it differs from the last one announced.
2052
+ *
2053
+ * The comparison is what keeps the status channel quiet: a pass runs on every
2054
+ * watcher event and every rescan tick, and almost all of them re-derive the
2055
+ * same rows. With no listener attached nothing is built at all — a headless
2056
+ * host pays nothing for a channel nobody reads.
2057
+ */
2058
+ private notify;
2059
+ /**
2060
+ * One session's snapshot row, carrying its live tool presentation only when
2061
+ * the host has mounted tools for it, and how much of the project's log history
2062
+ * belongs to it when there is any.
2063
+ * @param state - the session's own runtime state.
2064
+ * @param projectRoot - the project the session works in.
2065
+ * @returns the row; `tools` stays absent for an unmounted session, and
2066
+ * `logCount` for a session that recorded nothing.
2067
+ */
2068
+ private sessionSnapshot;
2069
+ /**
2070
+ * What one session offers the model, measured from its live state at call
2071
+ * time.
2072
+ *
2073
+ * The mounted set is the whole visible MCP surface — this plugin's project
2074
+ * mounts plus the profile plane and any F-19 forwarders — the same surface
2075
+ * the activation wiring measures against the budget, so the counts cannot
2076
+ * describe a different catalog than the one the request is built from. Total
2077
+ * on purpose: a probe that fails leaves the row out and warns instead of
2078
+ * failing the snapshot.
2079
+ * @param state - the session's own runtime state.
2080
+ * @returns the presentation row, or `undefined` when nothing is mounted.
2081
+ */
2082
+ private sessionTools;
2083
+ /**
2084
+ * One tool's on-demand detail, answered for a row a panel opened.
2085
+ *
2086
+ * A read, never a rescan: the definition comes from the same mount home the
2087
+ * snapshot's session row was measured from, so a **deferred** name answers
2088
+ * exactly like an offered one — the home's catalog carries the whole mounted
2089
+ * surface, and only the request's own deferral decision leaves a name out of
2090
+ * it. That is also what makes the reason honest: `budget` is reported exactly
2091
+ * when the session's own row lists the name in `deferred`, and every figure on
2092
+ * it is a host measurement — {@link schemaChars} of this definition, the
2093
+ * session's `budgetChars` and its `visibleChars`. A number the host does not
2094
+ * have is omitted rather than guessed.
2095
+ *
2096
+ * The published fields are the schema's top-level `parameters.properties`
2097
+ * only: a nested object or array is drawn as its type and never expanded, and
2098
+ * a property's `default` is never published — the schema a model reads is the
2099
+ * definition's, and this record is a *view* of it, not a second copy with
2100
+ * defaults baked in.
2101
+ *
2102
+ * @param projectRoot - project root the panel read the row from.
2103
+ * @param sessionId - live agent id the row belongs to.
2104
+ * @param name - public registry name, as the panel drew it.
2105
+ * @returns the tool's facts, or the `not-found` refusal the route maps to 404.
2106
+ */
2107
+ toolFactsOf(projectRoot: string, sessionId: string, name: string): ToolFactsOutcome;
2108
+ /**
2109
+ * Why the budget left one definition out of this session's request: the host's
2110
+ * own numbers, each omitted when the row that carries it did not measure it.
2111
+ * @param state - the session whose row and budget are read.
2112
+ * @param schema - the definition the row does not offer.
2113
+ * @returns the `budget` reason, carrying only figures the host holds.
2114
+ */
2115
+ private budgetReason;
2116
+ /**
2117
+ * What this plugin currently mounts for one live agent: the project root the
2118
+ * agent resolved to and the server names it mounted there. `undefined` when
2119
+ * the agent is unknown or resolved to no project, so a tool call from it is
2120
+ * simply not counted.
2121
+ * @param agentId - agent (session) id a tool call ran for.
2122
+ */
2123
+ mountsFor(agentId: string): AgentMounts | undefined;
2124
+ /**
2125
+ * Pin or unpin one tool of one project.
2126
+ *
2127
+ * The project must be one this host currently has a live session in: the panel
2128
+ * only ever names a root it read from a snapshot, so anything else is a stale
2129
+ * click and is refused rather than stored for a project nothing would show. No
2130
+ * rescan follows — the policy is part of no declaring document — so the answer
2131
+ * carries the current snapshot with the fresh pin list.
2132
+ * @param request - project root, public tool name and the wanted pin state.
2133
+ * @returns the fresh snapshot, or the refusal code the route maps to a status.
2134
+ */
2135
+ setPin(request: PinRequest): PolicyOutcome;
2136
+ /**
2137
+ * Store one project's tool mode.
2138
+ *
2139
+ * The same two refusals as {@link setPin}, plus a mode no assembly knows: the
2140
+ * mode is read on every assembly, so a stored change applies to the next model
2141
+ * step without re-minting the session scope.
2142
+ * @param request - project root and the mode to store.
2143
+ * @returns the fresh snapshot, or the refusal code the route maps to a status.
2144
+ */
2145
+ setPolicy(request: PolicyRequest): PolicyOutcome;
2146
+ /**
2147
+ * Choose which declaration of one contested `serverName` this project shows.
2148
+ *
2149
+ * The same two refusals as {@link setPin}, plus an answer no build knows. The
2150
+ * choice is stored first and the project reconciled right away, because a
2151
+ * choice is a mount changing name: the row it produces must be the row the
2152
+ * registry ends up carrying, not one that waits for the next turn.
2153
+ *
2154
+ * Nothing is refused for a name the project does not conflict over: the store
2155
+ * keeps a choice for a name that is not contested yet, so a declaration that
2156
+ * comes back — or a profile entry that is added later — finds the answer the
2157
+ * user already gave.
2158
+ * @param request - project root, contested name and the declaration to show.
2159
+ * @returns the fresh snapshot, or the refusal code the route maps to a status.
2160
+ */
2161
+ setConflictChoice(request: ConflictRequest): PolicyOutcome;
2162
+ /**
2163
+ * The policy in force for one project root.
2164
+ *
2165
+ * Read at snapshot and assembly time — never captured — so a stored change is
2166
+ * visible to the next model step and to the next panel poll. A host built
2167
+ * without a store follows the shipped default for every project.
2168
+ * @param projectRoot - project root, or `undefined` before a session resolves one.
2169
+ * @returns the stored policy, or {@link DEFAULT_TOOL_POLICY} when there is none.
2170
+ */
2171
+ private policyFor;
2172
+ /**
2173
+ * Whether one project root has a live session on this host.
2174
+ * @param projectRoot - project root a policy request names.
2175
+ * @returns `true` when a bound session resolved to that root.
2176
+ */
2177
+ private projectKnown;
2178
+ /**
2179
+ * Write one edited entry back to the document that declares it.
2180
+ *
2181
+ * The checks run in the contract's order and every one of them must pass
2182
+ * before a byte is written: the row must still exist, its declaring document
2183
+ * must belong to the project or to the (consented, enabled) global tier, the
2184
+ * revision must be the one the editor read, and the resulting entry must pass
2185
+ * the same parse path the mount uses. The document is then replaced by
2186
+ * {@link writeDocument} (`.bak`, then temp file, then rename) and rescanned,
2187
+ * so the answer carries a fresh snapshot.
2188
+ * @param request - the entry body, its declaring document and the read revision.
2189
+ * @returns the fresh snapshot, or the refusal code the route maps to a status.
2190
+ */
2191
+ saveEntry(request: SaveRequest): Promise<SaveOutcome>;
2192
+ /**
2193
+ * Run one reconciliation pass and await it.
2194
+ *
2195
+ * The operator call: it requests every listed session — or, with a
2196
+ * `projectRoot`, only that project's — so a session whose declaration was
2197
+ * never mounted (or whose mount was dropped) may start here without a turn.
2198
+ * Every other pass — a turn, an event, the rescan tick — requests only the
2199
+ * sessions that asked. Scripted reconciliation uses this awaiting form; the
2200
+ * panel's `Sync` uses {@link syncSoon}.
2201
+ * @param projectRoot - restricts the pass to one project's sessions.
2202
+ */
2203
+ syncNow(projectRoot?: string): Promise<void>;
2204
+ /**
2205
+ * Ask for the same pass and return at once — the panel's `Sync`.
2206
+ *
2207
+ * Waiting for the pass is what turned a `Sync` on a project whose server was
2208
+ * still connecting into a hang: the HTTP answer, and with it the panel's busy
2209
+ * flag, stayed open for `connectTimeoutMs`. The pass runs in the background,
2210
+ * and the panel watches its outcome on the status channel.
2211
+ * @param projectRoot - restricts the pass to one project's sessions.
2212
+ */
2213
+ syncSoon(projectRoot?: string): void;
2214
+ /**
2215
+ * Queue the operator pass without awaiting it, containing a rejection the way
2216
+ * every other background pass does: by the time either operator route
2217
+ * answers, the pass is nobody's request to wait for.
2218
+ * @param projectRoot - restricts the pass to one project's sessions.
2219
+ */
2220
+ private kick;
2221
+ /**
2222
+ * The sessions one operator pass may mount: every listed one, or the sessions
2223
+ * of a single project when the call came from a surface that shows one. The
2224
+ * project is named, not resolved here: {@link syncAgent} matches it against
2225
+ * each session's own working directory, so the very first operator call for a
2226
+ * session reaches the project it named.
2227
+ * @param projectRoot - the project the caller named, when it named one.
2228
+ * @returns the request the pass takes.
2229
+ */
2230
+ private requestsFor;
2231
+ /** Queue one pass behind whatever is already running. */
2232
+ private enqueue;
2233
+ /**
2234
+ * Drop the mounts currently in an `error` state and ask for a pass that mounts
2235
+ * them again, so a server that was fixed outside the plugin is picked up
2236
+ * without editing its declaration. A stalled mount is restarted from scratch.
2237
+ *
2238
+ * The drop is awaited — it is local and quick, and the answer the route sends
2239
+ * back must already show those rows as unmounted rather than failed. The pass
2240
+ * is not: a server that boots slowly would otherwise hold the `POST retry`
2241
+ * answer open for `connectTimeoutMs`, which the panel showed as a hang. A
2242
+ * `projectRoot` keeps both the drop and the pass inside that one project, so
2243
+ * retrying a row never starts a server for another one.
2244
+ *
2245
+ * The drop is per project: one failed instance is shared by every session of
2246
+ * its project, so retrying it must not try to unmount it once per session.
2247
+ * @param projectRoot - restricts the drop and the pass to one project.
2248
+ */
2249
+ retry(projectRoot?: string): Promise<void>;
2250
+ /** Dispose every mount, scope, watcher and timer owned by this runtime. */
2251
+ disposeAll(): Promise<void>;
2252
+ private newState;
2253
+ private dropAgent;
2254
+ /**
2255
+ * Release the sessions the host registry no longer lists.
2256
+ *
2257
+ * A finished or abandoned session produces no further event — no
2258
+ * `agent/status`, no `idle` transition to clear the busy flag, nothing for
2259
+ * the idle sweep to time out from. The pass is the path that exists: whatever
2260
+ * the registry still lists is live, and anything else hands its servers back
2261
+ * here, even with the idle sweep disabled.
2262
+ */
2263
+ private releaseAbandoned;
2264
+ /**
2265
+ * Whether one session is running a turn right now.
2266
+ *
2267
+ * The host's own status wins where it publishes one: `busy` only ever
2268
+ * reflects the events this plugin happened to see, so a session whose `idle`
2269
+ * transition never arrives would pin its mounts forever behind a stale flag.
2270
+ * @param state - the session to judge.
2271
+ * @returns true while the session must keep its mounts unconditionally.
2272
+ */
2273
+ private working;
2274
+ /**
2275
+ * Forget everything one session presented. The session's project is gone with
2276
+ * the scope (or the session is over), so a baseline seeded from that project's
2277
+ * counters must not leak into a different one. An idle release goes through
2278
+ * `releaseMounts`, not here.
2279
+ *
2280
+ * The hold on the old project's shared servers is given back here too: a
2281
+ * session that moves to another project — or disappears — must not keep the
2282
+ * project it left running for nobody.
2283
+ * @param state - the session state to clear.
2284
+ */
2285
+ private disposeState;
2286
+ /**
2287
+ * Take one session's hold on a project: link its scope key to the project's
2288
+ * so the shared layer resolves for it, or install the forwarding bridge when
2289
+ * that link is impossible, then mint its own scope and install the session
2290
+ * wiring on it. Idempotent while the hold is unchanged.
2291
+ *
2292
+ * The link comes first because it is what makes the project's already-running
2293
+ * servers visible to this session from its first request on. A key the
2294
+ * harness already parented cannot be linked again — `dsh-scope` binds a key
2295
+ * once, and the agent-preset roster binds every composed agent to its
2296
+ * standing scope before the agent is published — so that session holds the
2297
+ * SAME project home and gets a forwarding bridge instead: thin definitions in
2298
+ * its own layer whose calls run the project's one instance (`src/bridge.ts`).
2299
+ * One process per project is the whole point; the alternative was one process
2300
+ * per session, which is what the panel showed in the web GUI.
2301
+ * @param state - the session taking the hold.
2302
+ * @param project - the project whose mounts it shares.
2303
+ * @returns the home the session now holds.
2304
+ */
2305
+ private holdProject;
2306
+ /**
2307
+ * Give one session's hold back. Its own scope and wiring go away, its scope
2308
+ * key is unlinked from the project so the shared servers stop resolving for
2309
+ * it, and the project's instance is released exactly when this was the last
2310
+ * holder — a session that goes idle or leaves while another one still works
2311
+ * must not stop the servers that one is using.
2312
+ * @param state - the session releasing its hold.
2313
+ * @param reason - why the hold is going back; every instance this drops is
2314
+ * logged with it, so the log says why a server stopped, not only that it did.
2315
+ */
2316
+ private detach;
2317
+ /** Drop the session scope and the wiring installed on it. Idempotent. */
2318
+ private disposeSessionScope;
2319
+ /**
2320
+ * Whether any live session still holds one project's shared mounts.
2321
+ * @param project - the project to look for.
2322
+ * @returns `true` while at least one session keeps the instance alive.
2323
+ */
2324
+ private hasHolders;
2325
+ /**
2326
+ * Release one project's shared servers and the scope that owns them.
2327
+ *
2328
+ * Runs when the project's last holder lets go, so a shared instance goes away
2329
+ * on exactly the trigger a per-session one did: the project's last session
2330
+ * releasing it (idle release, request, disposal, a move to another project, or
2331
+ * a declaration that mounts nothing any more). Idempotent.
2332
+ * @param project - the project to tear down.
2333
+ */
2334
+ private releaseProject;
2335
+ /**
2336
+ * Forget the project records no live session is bound to any more. A record
2337
+ * with mounts or a scope is never dropped: either one means someone still
2338
+ * holds the project.
2339
+ */
2340
+ private sweepProjects;
2341
+ /** Whether any live session resolved its working directory to one root. */
2342
+ private hasRootSessions;
2343
+ /**
2344
+ * The project record one root's sessions share, created with its first holder
2345
+ * and forgotten when its last one lets go.
2346
+ * @param projectRoot - resolved project root.
2347
+ * @returns the live record.
2348
+ */
2349
+ private ensureProject;
2350
+ /**
2351
+ * The home one session mounts in: the project it holds, bridged or joined.
2352
+ * `undefined` while it holds nothing.
2353
+ * @param state - the session to read.
2354
+ * @returns the session's mount home, or `undefined` when it holds none.
2355
+ */
2356
+ private homeOf;
2357
+ /**
2358
+ * The mounts one session renders right now: its own home's when it has one for
2359
+ * this root, otherwise the project's shared set, so a session that holds
2360
+ * nothing still notices another session's mounts and re-renders its rows.
2361
+ * @param state - the session to read.
2362
+ * @param projectRoot - the project root the pass is reconciling.
2363
+ * @returns the mount map whose changes this session's digest tracks.
2364
+ */
2365
+ private visibleMounts;
2366
+ /**
2367
+ * The live mounts one session currently holds. Empty for a session that holds
2368
+ * nothing: the servers run for their project, and only a holder shares them.
2369
+ * @param state - the session to read.
2370
+ * @returns the shared mount map, or a shared empty one.
2371
+ */
2372
+ private mountsOf;
2373
+ /**
2374
+ * The `serverName` every one of the session's mounts registers under.
2375
+ *
2376
+ * The registry — and every name it publishes — is keyed by this, not by the
2377
+ * declared name: a shadowed declaration registers as its local alias, and a
2378
+ * lookup by the contested name would read as "this project mounts nothing".
2379
+ * @param state - the session to read.
2380
+ * @returns the runtime names, one per live mount.
2381
+ */
2382
+ private runtimeNamesOf;
2383
+ /**
2384
+ * Unregister everything the current scope's session wiring installed. The
2385
+ * scope fiber disposes the same registrations with the real services, while a
2386
+ * host that publishes plain `systemPrompt`/`tools` stubs has only this path.
2387
+ * Idempotent.
2388
+ */
2389
+ private releaseWiring;
2390
+ /**
2391
+ * Unregister the guidance section of the current scope, if one is installed.
2392
+ * Released exactly where the scope is — an idle release and agent disposal —
2393
+ * so no section ever describes mounts that are gone.
2394
+ */
2395
+ private releaseGuidance;
2396
+ /**
2397
+ * Unregister the activation wiring of the current scope. Idempotent: the
2398
+ * scope fiber disposes the same registrations with the real registry, while a
2399
+ * host that publishes a plain `tools` stub has only this path.
2400
+ */
2401
+ private releaseActivation;
2402
+ /**
2403
+ * Ask for a pass. A pending pass is kept instead of being pushed back: the
2404
+ * rescan tick is often shorter than the debounce, and restarting the timer on
2405
+ * every tick would starve reconciliation forever. Bursts of watcher events
2406
+ * still collapse into the one queued pass, and each pass re-reads the
2407
+ * documents through the digest, so a late event costs one cheap pass.
2408
+ */
2409
+ private schedule;
2410
+ /**
2411
+ * Turn boundary. `running` is the moment a session becomes active, which is
2412
+ * what `lazy` waits for; `idle` closes the busy window that idle release
2413
+ * watches. A plain notification, so it never delays a turn.
2414
+ */
2415
+ private onStatus;
2416
+ /**
2417
+ * Before every step of a turn: keep this session's project mounted, waiting
2418
+ * for a pending activation so that the step's request already sees the
2419
+ * project's tools. The waterfall always continues — a project MCP server is
2420
+ * never a reason to hold up an agent step.
2421
+ */
2422
+ private onPreStep;
2423
+ /** Record activity and, with nothing mounted, ask for an activation pass. */
2424
+ private touch;
2425
+ /**
2426
+ * Wait (bounded) for the activation pass a turn asked for.
2427
+ *
2428
+ * The pass carries no operator request on purpose: the caller's
2429
+ * `activationPending` is what entitles this session to mount, and leaving the
2430
+ * request empty is what keeps the pass from starting servers in every other
2431
+ * project whose sessions happen to be live.
2432
+ */
2433
+ private awaitActivation;
2434
+ /**
2435
+ * Reconcile every known session once, then the sweep and the watchers.
2436
+ * @param requests - the sessions that may mount without their own turn asking.
2437
+ */
2438
+ private runPass;
2439
+ /**
2440
+ * Release the mounts of sessions that have been quiet for `idleTimeoutMs`.
2441
+ * Their rows stay visible as `idle`, so the project's declaration remains
2442
+ * discoverable while not a single child process is running for it.
2443
+ */
2444
+ private evictIdle;
2445
+ /**
2446
+ * Give one session's servers back now, or every mounted session's when no id
2447
+ * is given. Drives the panel's "release" action; the rows stay as `idle` and
2448
+ * the next turn mounts them again. A session that releases the last hold on a
2449
+ * project takes the shared instance down with it, and one that releases while
2450
+ * another session of the project holds leaves it running for that session.
2451
+ */
2452
+ release(agentId?: string): Promise<void>;
2453
+ /**
2454
+ * Give one session's hold back, keeping its rows as `idle`.
2455
+ *
2456
+ * The shared servers themselves follow the last holder: this detaches the
2457
+ * session (its scope, wiring and parent link) and releases the project only
2458
+ * when no other session holds it, so releasing one session of a project that
2459
+ * another session is still working in leaves that session's servers running.
2460
+ * @param state - the session releasing.
2461
+ * @param describe - reason for its rows, given the number of servers it held.
2462
+ */
2463
+ private releaseMounts;
2464
+ /**
2465
+ * Re-read one agent's project and reconcile its mounts.
2466
+ * @param state - the session to reconcile.
2467
+ * @param operatorRequested - an operator pass named this exact session.
2468
+ */
2469
+ syncAgent(state: AgentState, requests?: PassRequests): Promise<void>;
2470
+ /**
2471
+ * Start one declared server in the session's mount home and record the mount,
2472
+ * which every session that home serves then resolves.
2473
+ *
2474
+ * Exactly one `info` line is written per created process — never on a rescan
2475
+ * that re-derives the same mount, and never when another session of the
2476
+ * project attaches to a shared instance that is already running — so an
2477
+ * operator can tell which session caused a server to start, in which project,
2478
+ * and what asked for it.
2479
+ *
2480
+ * The registration is the whole of what this pass does here: the fiber's
2481
+ * activation is *watched*, never awaited, so a server that never answers
2482
+ * costs the pass — and with it every turn waiting on that pass — nothing.
2483
+ * The mount is recorded before the wait, so a later pass finds it in place
2484
+ * and mounts nothing a second time; the outcome reaches the row through
2485
+ * {@link observeActivation} on failure and through {@link refreshStatuses}
2486
+ * on success.
2487
+ * @param state - the session whose pass creates the instance.
2488
+ * @param home - the scope the instance belongs to: the project's shared one,
2489
+ * or the session's own when it could not join the project's chain.
2490
+ * @param name - declared `serverName`.
2491
+ * @param entry - the parsed declaration to mount.
2492
+ * @param trigger - why this pass was allowed to start it.
2493
+ * @param alias - local name to register under, when a profile instance owns
2494
+ * the declared one and the user chose to see the project's copy too.
2495
+ */
2496
+ private mount;
2497
+ /**
2498
+ * Publish one lifecycle event, and announce it.
2499
+ *
2500
+ * The plugin's five lifecycle facts — mounting, `is up`, a stall, a failed
2501
+ * mount, unmounting — leave the runtime through this one method and no other,
2502
+ * and the snapshot announcement follows every one of them, as it did when each
2503
+ * site kept the three writes in step by hand. What the DSH log prints and what
2504
+ * the ring holds are the subscribers' business now: the runtime only says what
2505
+ * happened (`src/notifications.ts`).
2506
+ * @param event - the fact, already carrying its level, session and server.
2507
+ */
2508
+ private logLifecycle;
2509
+ /**
2510
+ * Watch one mount's activation in the background, so the registering pass
2511
+ * never waits for it.
2512
+ *
2513
+ * A failure is the one outcome the pass used to report itself, and it is
2514
+ * written exactly as it was when it did: the row turns `error`, `failed`
2515
+ * keeps {@link refreshStatuses} from polling a dead fiber, and the detail is
2516
+ * {@link failureDetail}. A success and a timeout write nothing — a mount
2517
+ * whose tools became visible is turned `active` by the status scan of the
2518
+ * next pass, which logs the `is up` line, and a mount that is merely slow is
2519
+ * the watchdog's stall to report.
2520
+ *
2521
+ * Nothing awaits the returned promise, so it must never reject: `waitFor`
2522
+ * already answers a rejected fiber with `{ kind: 'failed' }`, and the final
2523
+ * `catch` is the backstop for the recorder itself.
2524
+ * @param home - the home the mount was recorded in, read to see it is current.
2525
+ * @param mount - the mount whose activation this watches.
2526
+ * @param label - the wait label, as `waitFor` names it in the debug line.
2527
+ * @param fiber - the fiber whose activation this watches.
2528
+ */
2529
+ private observeActivation;
2530
+ /**
2531
+ * The watched wait itself: one activation to its outcome, then the failure
2532
+ * written if it had one.
2533
+ * @param home - the home the mount was recorded in.
2534
+ * @param mount - the mount whose activation this waits for.
2535
+ * @param label - the wait label, as `waitFor` names it in the debug line.
2536
+ * @param fiber - the fiber whose activation this waits for.
2537
+ */
2538
+ private settleActivation;
2539
+ /**
2540
+ * Re-read one home's mounts for every session that holds it, then tell the
2541
+ * panels.
2542
+ *
2543
+ * Called from behind a pass — a mount settles after its pass has returned —
2544
+ * so for a deployment without a rescan timer this is the only moment that
2545
+ * moves a row off `connecting`. Idempotent: the transition log fires on a
2546
+ * change, so a second call for the same mount writes nothing.
2547
+ * @param home - the home whose instances settled.
2548
+ */
2549
+ private announceHome;
2550
+ /**
2551
+ * Record a mount that could not be activated: the row's `error`, the detail
2552
+ * an operator reads, and the one warning line. Shared by the synchronous
2553
+ * registration failures and the watched activations above, so both report
2554
+ * the same three facts in the same words.
2555
+ * @param home - the home the failed instance belongs to.
2556
+ * @param mount - the mount to mark failed.
2557
+ * @param error - what the fiber or the registration failed with.
2558
+ */
2559
+ private recordMountFailure;
2560
+ /**
2561
+ * The session-scope context the bridge registers through: the minted scope's
2562
+ * context carries the session's scope tag, so a registration made through it
2563
+ * lands in exactly this session's layer.
2564
+ */
2565
+ private bridgeContextOf;
2566
+ /** The registry surface the bridge reads; defaults to the plugin's own. */
2567
+ private bridgeRegistry;
2568
+ /**
2569
+ * Install the forwarding bridge on one session: thin definitions in the
2570
+ * session's own layer over the project's live tools.
2571
+ *
2572
+ * Idempotent while the session keeps its project. The `tools/change`
2573
+ * subscription is what keeps the bridge level with a server that publishes
2574
+ * its tools long after the pass that registered the mount returned — the
2575
+ * session's layer is brought up to date before the next turn reads it.
2576
+ * A failure is contained: the session keeps its hold on the project's servers
2577
+ * and gets no tools from them until the next pass retries the sync.
2578
+ * @param state - the session taking the bridge.
2579
+ * @param project - the project whose tools are forwarded.
2580
+ */
2581
+ private installBridge;
2582
+ /**
2583
+ * Bring one session's forwarders level with the project's live tools.
2584
+ *
2585
+ * The pass itself — including the re-entry its own registrations force on it
2586
+ * through `tools/change` — belongs to the session's {@link ForwardBatch}; this
2587
+ * is where a failure is contained and reported. A failed pass leaves the
2588
+ * session with no forwarder until the next pass retries (`namesIn` stays
2589
+ * unset), and never takes the session's hold on the project down.
2590
+ * @param state - the session whose bridge to sync.
2591
+ */
2592
+ private syncBridge;
2593
+ /** The project scope's visible schemas, as {@link projectToolNames} reads them. */
2594
+ private bridgeSchemas;
2595
+ /** Drop one session's bridge: its forwarders and its subscription. Idempotent. */
2596
+ private dropBridge;
2597
+ /**
2598
+ * The project's shared scope, minted with its first mount. One scope per
2599
+ * project is what makes mcp-client's `serverName` reservation per project
2600
+ * rather than per session, and it is disposed when the project's last holder
2601
+ * lets go, so the instance lifetime matches a per-session mount's.
2602
+ * @param project - the project to mount into.
2603
+ * @returns the scope, reused when the project already has one.
2604
+ */
2605
+ private ensureProjectScope;
2606
+ /**
2607
+ * Wait for one fiber operation, bounded by `connectTimeoutMs`. A server that
2608
+ * never answers must not hold a pass (or a project's teardown) open forever;
2609
+ * the fiber stays alive and later passes keep watching it.
2610
+ */
2611
+ private waitFor;
2612
+ /**
2613
+ * Whether every mount has settled, so a rescan can return without work. A
2614
+ * stalled mount keeps the pass alive on purpose: only a fresh status scan can
2615
+ * notice that the client's background retry finally connected.
2616
+ */
2617
+ private settled;
2618
+ /**
2619
+ * Mint one scope through the injected factory, or through the module itself.
2620
+ * The parent link of a session key is established by {@link holdProject} before
2621
+ * this runs and deliberately not passed as `createScope`'s own `parent`
2622
+ * option: binding twice on one key throws, and the retained binding is what
2623
+ * makes a release and a project change re-linkable.
2624
+ * @param key - session key or project key the scope's registrations own.
2625
+ * @returns the minted scope.
2626
+ */
2627
+ private mintScope;
2628
+ /**
2629
+ * Mint the session scope on first use and install the session wiring on it:
2630
+ * the project-MCP guidance section and, when activation is on, the wiring
2631
+ * that lets a project's MCP tools be *found* (`mcp_search_tools`) and put
2632
+ * back into an assembly a presentation plugin filtered.
2633
+ *
2634
+ * Both are installed once per scope and both read the project's live state, so
2635
+ * a rescan that changes the mounted set changes what they say without
2636
+ * re-registering anything. `detach` disposes the scope and releases the wiring
2637
+ * explicitly, and the next attach installs a fresh one over the surviving
2638
+ * session state.
2639
+ *
2640
+ * A failed mint is contained: the session keeps its hold on the shared mounts
2641
+ * (they are registered on the project scope, which is unaffected) and only
2642
+ * loses its own wiring, instead of failing the pass.
2643
+ */
2644
+ private ensureSessionScope;
2645
+ /**
2646
+ * The session's activation state, seeded from its project's counters on first
2647
+ * use. Later scopes of the same session keep it; only a project change or a
2648
+ * teardown drops it.
2649
+ */
2650
+ private seedActivation;
2651
+ /**
2652
+ * The schemas this plugin may offer this session: exactly the tools whose
2653
+ * public name belongs to a server it mounted for this agent's project. A
2654
+ * profile-level or other-project tool is never a candidate, and the prefix is
2655
+ * never parsed blindly — the runtime's own mount records decide.
2656
+ */
2657
+ private activationCandidates;
2658
+ /**
2659
+ * The schemas the session's own mount home publishes, read through the home's
2660
+ * scope key rather than the session's.
2661
+ *
2662
+ * The two are the same catalog by construction: a session that joined the
2663
+ * project's chain resolves the project's layer, and a session that could not
2664
+ * gets exactly those tools forwarded into its own layer. Reading the home's
2665
+ * view is what keeps this probe independent of the forwarding timing — a
2666
+ * server is up as soon as its tools are registered on the project scope, and
2667
+ * a bridge sync that has not run yet must not read as "not up".
2668
+ * @param state - the session whose home is probed.
2669
+ * @returns the visible schemas of its home, or none while it holds nothing.
2670
+ */
2671
+ private mountedSchemas;
2672
+ /**
2673
+ * The visible catalog of one mount home, read through the home's scope key.
2674
+ *
2675
+ * The single read both callers share: the activation probe asks for the whole
2676
+ * catalog, and the on-demand detail route asks it for one definition — reading
2677
+ * through the same key is what makes a deferred name answer exactly like an
2678
+ * offered one, because the home's catalog carries the whole mounted surface
2679
+ * and the deferral decision only lives in the request.
2680
+ *
2681
+ * @param home - the mount home whose registrations are read.
2682
+ * @param agentId - the session the read is attributed to, for the warning.
2683
+ * @returns the home's schemas, or none when the read fails.
2684
+ */
2685
+ private schemasOf;
2686
+ /**
2687
+ * Every MCP schema the session's own scope chain resolves beyond this
2688
+ * plugin's project mounts: the profile plane and any F-19 forwarders. Read
2689
+ * through the session's key rather than the home's, so the deferral budget
2690
+ * and the discovery tool measure the whole surface the request actually
2691
+ * carries. Only `mcp__`-prefixed names enter, and the discovery tool is left
2692
+ * out by value — not by prefix — so the activation wiring can offer it on its
2693
+ * own. The per-server usage counters stay on the project plane: this probe
2694
+ * reads the catalog, never the counters.
2695
+ *
2696
+ * @param state - the session whose visible surface is probed.
2697
+ * @returns the visible MCP schemas, or none when the read fails.
2698
+ */
2699
+ private visibleSchemas;
2700
+ /**
2701
+ * The MCP tool names this session must never be offered: everything another
2702
+ * project mounted in this process publishes. The union is read through each
2703
+ * other project's own scope key — not the session's — so a name the host
2704
+ * defect leaked into the session's chain is caught here by provenance rather
2705
+ * than by prefix. Conservative, so a name the session may legitimately see is
2706
+ * never marked foreign: the set subtracts the session's own project's runtime
2707
+ * names and every profile-level server name (a profile entry is none of this
2708
+ * plugin's business even when another project declares the same name).
2709
+ * @param state - the session whose request is being assembled.
2710
+ * @returns the foreign tool names, or none when the read fails.
2711
+ */
2712
+ private foreignNamesOf;
2713
+ /**
2714
+ * The live text of the session's guidance section.
2715
+ *
2716
+ * It reads the mount records and the registry at every assembly, so a rescan
2717
+ * that mounted or dropped a server — and a search that activated a tool — are
2718
+ * reflected without re-registering the section. Total: any failure returns the
2719
+ * empty string, because a section that throws would fail the model request
2720
+ * that asked for the assembly.
2721
+ */
2722
+ private guidanceText;
2723
+ /**
2724
+ * Record a call against the session's activation state: it refreshes the
2725
+ * freshness of a session-activated tool, and it is the evidence a later
2726
+ * compaction keeps that activation by. It rides the same `tools/result`
2727
+ * subscription the counters use, so no second observer exists.
2728
+ * @param agentId - calling agent, when the call was agent-scoped.
2729
+ * @param toolName - public registry name of the call.
2730
+ */
2731
+ noteToolUse(agentId: string | undefined, toolName: string): void;
2732
+ /** Drop the session-activated tools that outlived `toolIdleMs` without a call. */
2733
+ private pruneActivation;
2734
+ /**
2735
+ * Drop the step records whose activation the session no longer holds.
2736
+ *
2737
+ * Called wherever activations end — the idle sweep and a compaction — so a
2738
+ * record never outlives the offer it was made for, and a name the session
2739
+ * still offers keeps the step its offer happened on.
2740
+ * @param state - the session whose records are reconciled.
2741
+ */
2742
+ private pruneStepRecords;
2743
+ private unmount;
2744
+ /**
2745
+ * The line that closes a mount's life, the pair of the `mounting` line.
2746
+ *
2747
+ * The reason is the part a reader cannot infer from the log's order: an edit,
2748
+ * an idle release, an operator retry and a session teardown all unmount, and
2749
+ * only some of them are followed by a mount of the same server. The run time
2750
+ * tells a server that never came up from one that served and was replaced.
2751
+ * @param home - the home the instance lived in.
2752
+ * @param mount - the instance going away.
2753
+ * @param reason - why it is going away: the operator's sentence and its wire
2754
+ * code (F-48), nested two-level into the `unmounting` event as `reasonCode`.
2755
+ */
2756
+ private logUnmount;
2757
+ /**
2758
+ * Bring every foreign holder of one home level with its live tools.
2759
+ *
2760
+ * The mount and unmount sites call this because they are the moments the
2761
+ * project's tool set actually changes: a session's own pass can run before the
2762
+ * server it shares has published anything (its own mount is only registered
2763
+ * after the hold), and this is what fills its forwarders in behind it. The
2764
+ * `tools/change` subscription and the read-path sync cover the same event on
2765
+ * a real registry; a third trigger costs nothing, because an unchanged name
2766
+ * set short-circuits.
2767
+ * @param home - the home whose tools changed.
2768
+ */
2769
+ private syncBridgesOf;
2770
+ private disposeFiber;
2771
+ /**
2772
+ * Refresh `active`/`connecting` from the tools actually visible to the agent,
2773
+ * and turn a mount that never produced a tool into a detailed `error` row.
2774
+ * The watchdog is strictly read-only: it never disposes a slow server, and a
2775
+ * mount that connects later returns to `active` on its own.
2776
+ */
2777
+ private refreshStatuses;
2778
+ /**
2779
+ * The session's rows with their live mount state applied.
2780
+ *
2781
+ * Read-time, not stored: a mount that appears, connects or fails between two
2782
+ * passes changes what a panel must show, while the row belongs to the pass
2783
+ * that last re-derived it. Decorating here is what lets the status channel
2784
+ * report a mount the moment the pass creates it, rather than when that pass
2785
+ * finally returns.
2786
+ * @param state - the session whose rows to read.
2787
+ * @returns one row per declaration, in document order.
2788
+ */
2789
+ private liveRows;
2790
+ /** Mount failures of this pass, published as first-class snapshot issues. */
2791
+ private mountDiagnostics;
2792
+ private hasTools;
2793
+ /**
2794
+ * Global documents of this deployment, lowest priority first. Read before a
2795
+ * project's own documents, so a project declaration always wins.
2796
+ */
2797
+ private globalFiles;
2798
+ /**
2799
+ * Every document one project is configured to read, in priority order — the
2800
+ * order they are read in, which is what the panel's `priority n/total` counts.
2801
+ */
2802
+ private readFiles;
2803
+ private readProject;
2804
+ /**
2805
+ * Everything the editor needs about one declaring document: its revision and
2806
+ * write tier, plus the entry body of each server that parsed.
2807
+ */
2808
+ private documentInfo;
2809
+ private readDocument;
2810
+ private resolveContext;
2811
+ /**
2812
+ * The project's own dotenv values, plus the identity of the files they came
2813
+ * from. Documents are merged lowest priority first, so `<project>/.dsh/.env`
2814
+ * overrides the plain `<project>/.env`; each file is re-read only when its
2815
+ * mtime/size changes, and a file that is gone leaves both the map and the
2816
+ * stamp (so deleting `.env` un-resolves its references on the next pass).
2817
+ */
2818
+ private readProjectEnv;
2819
+ /**
2820
+ * Credentials, re-read only when the document changes. Every pass of every
2821
+ * session resolves `${input:NAME}` references, so an uncached read here cost
2822
+ * one synchronous stat plus YAML parse per session per pass. The stamp is the
2823
+ * same identity the document cache compares.
2824
+ */
2825
+ private readSecrets;
2826
+ private profileServerNames;
2827
+ /**
2828
+ * The other loaded plugin that owns the assembled tool list, if the profile
2829
+ * has one.
2830
+ *
2831
+ * Read from the same `loader.entries()` this plugin already consults for the
2832
+ * reserved `serverName`s, for the same reason: the profile is where a second
2833
+ * owner is mounted, and a running entry is the only kind that shapes a
2834
+ * request. An entry named like a known presentation plugin but not active is
2835
+ * mounted-and-stopped, which shapes nothing, so it is reported no more than an
2836
+ * absent one is.
2837
+ *
2838
+ * @returns the owner, or `undefined` when this plugin assembles alone.
2839
+ */
2840
+ private presentationOwner;
2841
+ /**
2842
+ * Keep one watcher set per project with live agents. Only the project's own
2843
+ * document directories are watched recursively: an unrelated file storm
2844
+ * (install caches, build output, git metadata) never reaches this plugin, so
2845
+ * it costs no events and no passes. A flat watch on the project root notices
2846
+ * a config directory appearing or disappearing, and the rescan timer is the
2847
+ * safety net for anything else.
2848
+ */
2849
+ private syncWatchers;
2850
+ private closeWatchers;
2851
+ /** Directories (and document files) worth watching for one root. */
2852
+ private watchTargets;
2853
+ private watchProject;
2854
+ }
2855
+ //#endregion
2856
+ //#region src/policy.d.ts
2857
+ /** Current on-disk document version; another version is ignored, not migrated. */
2858
+ export declare const POLICY_VERSION = 1;
2859
+ /** Policy document name under `$DSH_HOME`, next to the usage counters. */
2860
+ export declare const POLICY_FILE_NAME = "dsh-project-mcp-policy.json";
2861
+ /** Every mode a request may store, in the order the type declares them. */
2862
+ export declare const TOOL_MODES: readonly ToolMode[];
2863
+ /** Policy of every project ever configured, keyed by project root. */
2864
+ type PolicyState = Record<string, ToolPolicy>;
2865
+ /** The durable policy document as written to disk. */
2866
+ interface PolicyDocument {
2867
+ /** Document version; a reader that does not know it starts clean. */
2868
+ version: typeof POLICY_VERSION;
2869
+ /** Policy of every project the user configured. */
2870
+ projects: PolicyState;
2871
+ }
2872
+ /** The logger surface the store uses; a Cordis logger satisfies it. */
2873
+ interface PolicyLogger {
2874
+ /** Non-fatal report; the store never throws at its caller. */
2875
+ warn(message: string): void;
2876
+ }
2877
+ /** Construction options for {@link PolicyStore}; production uses the defaults. */
2878
+ interface PolicyStoreOptions {
2879
+ /** Absolute document path; defaults to `$DSH_HOME/dsh-project-mcp-policy.json`. */
2880
+ file?: string;
2881
+ /** Debounce before a policy change reaches disk. */
2882
+ flushMs?: number;
2883
+ /** Sink for a corrupt document or a failed write. */
2884
+ logger?: PolicyLogger;
2885
+ }
2886
+ /**
2887
+ * Whether a value is one of the modes this plugin stores.
2888
+ *
2889
+ * The routes read an untrusted JSON body, so the check belongs here rather than
2890
+ * in the type system: a body that names an unknown mode is refused instead of
2891
+ * being stored as a mode no assembly would know what to do with.
2892
+ *
2893
+ * @param value - parsed request or document value.
2894
+ * @returns `true` when the value is a {@link ToolMode}.
2895
+ */
2896
+ export declare function isToolMode(value: unknown): value is ToolMode;
2897
+ /**
2898
+ * The policy in force for one project.
2899
+ *
2900
+ * Pure: it reads the state only. An absent project is the shipped default rather
2901
+ * than an error, which is what makes a fresh install behave exactly like the
2902
+ * plugin before this document existed.
2903
+ *
2904
+ * @param state - policies before the read.
2905
+ * @param projectRoot - project root the policy belongs to.
2906
+ * @returns the stored policy, or {@link DEFAULT_TOOL_POLICY} when there is none.
2907
+ */
2908
+ export declare function policyFor(state: PolicyState, projectRoot: string): ToolPolicy;
2909
+ /**
2910
+ * Store one project's mode, keeping its pins.
2911
+ *
2912
+ * Pure and idempotent: storing the mode already in force returns the input state
2913
+ * unchanged, so a panel that resubmits a switch does not schedule a write.
2914
+ *
2915
+ * @param state - policies before the change.
2916
+ * @param projectRoot - project root the mode applies to.
2917
+ * @param mode - the mode to store.
2918
+ * @returns a new state, or the input when the mode did not change.
2919
+ */
2920
+ export declare function withMode(state: PolicyState, projectRoot: string, mode: ToolMode): PolicyState;
2921
+ /**
2922
+ * Pin or unpin one name of one project.
2923
+ *
2924
+ * Pins keep the order the user pinned them in — a pin is appended, an unpin
2925
+ * removes exactly that name — because the panel lists them in that order and a
2926
+ * re-pin after an unpin must not silently jump to the front. A name is never
2927
+ * validated against the project's mounts here: a pin of a tool the project does
2928
+ * not mount yet is kept, so a declaration that comes back finds its pin again.
2929
+ *
2930
+ * @param state - policies before the change.
2931
+ * @param projectRoot - project root the pin belongs to.
2932
+ * @param tool - public registry name, eg `mcp__tglider__workspace`.
2933
+ * @param pinned - `true` pins it, `false` unpins it.
2934
+ * @returns a new state, or the input when the list did not change.
2935
+ */
2936
+ export declare function withPin(state: PolicyState, projectRoot: string, tool: string, pinned: boolean): PolicyState;
2937
+ /**
2938
+ * Parse one durable policy document.
2939
+ *
2940
+ * Anything this version cannot trust — malformed JSON, a foreign shape, or
2941
+ * another version — yields `undefined` so the caller starts from the shipped
2942
+ * default instead of throwing. A project entry is sanitized field by field: an
2943
+ * unknown mode falls back to `disclosure` and a pin list keeps only non-empty
2944
+ * deduplicated strings, so a hand-edited document cannot poison a request.
2945
+ *
2946
+ * @param text - raw document contents.
2947
+ * @returns the policies, or `undefined` when the document is not usable.
2948
+ */
2949
+ export declare function parsePolicyDocument(text: string): PolicyState | undefined;
2950
+ /**
2951
+ * The durable policy: one versioned document under `$DSH_HOME`, loaded once when
2952
+ * the plugin applies and written atomically on a debounce.
2953
+ *
2954
+ * Every failure mode is non-fatal by design, exactly like the counters. A
2955
+ * missing, unreadable, foreign or older-version document starts from the shipped
2956
+ * default, and a write that fails is logged and forgotten, because a panel click
2957
+ * must never fail on a policy that could not be stored.
2958
+ */
2959
+ export declare class PolicyStore {
2960
+ private state;
2961
+ private timer;
2962
+ private dirty;
2963
+ private disposed;
2964
+ private readonly file;
2965
+ private readonly flushMs;
2966
+ private readonly logger;
2967
+ /** @param options - document path, debounce and log sink. */
2968
+ constructor(options?: PolicyStoreOptions);
2969
+ /** Policy of one project root; the shipped default when it has none. */
2970
+ forProject(projectRoot: string): ToolPolicy;
2971
+ /** Store one project's mode and schedule the debounced write. */
2972
+ setMode(projectRoot: string, mode: ToolMode): ToolPolicy;
2973
+ /** Pin or unpin one name of one project and schedule the debounced write. */
2974
+ setPin(projectRoot: string, tool: string, pinned: boolean): ToolPolicy;
2975
+ /**
2976
+ * Store which of two conflicting declarations one name shows and schedule the
2977
+ * debounced write.
2978
+ *
2979
+ * Durable on purpose: the answer is what the user decided about their project,
2980
+ * not what one session happened to mount, so it survives the restart that
2981
+ * would otherwise bring the profile's instance back unopposed.
2982
+ */
2983
+ setConflictChoice(projectRoot: string, server: string, choice: ConflictChoice): ToolPolicy;
2984
+ /** Write the policy atomically now. Best effort: it never throws. */
2985
+ flush(): void;
2986
+ /**
2987
+ * Cancel the pending write, flush what is dirty, and stop storing. Safe to
2988
+ * call more than once; the plugin fiber calls it on disposal.
2989
+ */
2990
+ dispose(): void;
2991
+ /** Adopt a state a pure change produced, and schedule the write when it moved. */
2992
+ private commit;
2993
+ private load;
2994
+ }
2995
+ //#endregion
2996
+ //#region src/discovery.d.ts
2997
+ /**
2998
+ * Resolve one configured document spec to an absolute path.
2999
+ *
3000
+ * A spec is read the way a shell reads it, in this order:
3001
+ *
3002
+ * - `~/x` (and a bare `~`) → `$HOME/x`;
3003
+ * - `$DSH_HOME/x` or `${DSH_HOME}/x` → the deployment's own home;
3004
+ * - an absolute path → itself;
3005
+ * - anything else → `base/x`, so a local document stays inside the project and
3006
+ * a global one stays inside `$HOME`.
3007
+ *
3008
+ * @param spec - one entry of `localFiles` or `globalFiles`.
3009
+ * @param base - directory a relative spec is read from.
3010
+ * @param env - environment used to resolve `$DSH_HOME`.
3011
+ * @returns the absolute document path.
3012
+ */
3013
+ export declare function expandConfigPath(spec: string, base: string, env?: Record<string, string | undefined>): string;
3014
+ /**
3015
+ * Project documents to read for one project root, in increasing priority — a
3016
+ * later document overrides an earlier entry of the same `serverName`.
3017
+ * @param projectRoot - absolute project root.
3018
+ * @param files - configured project-relative specs, lowest priority first.
3019
+ * @param env - environment used to resolve `$DSH_HOME`.
3020
+ * @returns absolute paths, lowest priority first.
3021
+ */
3022
+ export declare function localConfigPaths(projectRoot: string, files?: readonly string[], env?: Record<string, string | undefined>): string[];
3023
+ /**
3024
+ * Global documents of one deployment, in increasing priority. They are read
3025
+ * before a project's own documents, so a project declaration always wins.
3026
+ * @param files - configured specs, lowest priority first.
3027
+ * @param env - environment used to resolve `$DSH_HOME`.
3028
+ * @returns absolute paths, lowest priority first.
3029
+ */
3030
+ export declare function globalConfigPaths(files?: readonly string[], env?: Record<string, string | undefined>): string[];
3031
+ /**
3032
+ * Walk upward from `cwd` to the first directory carrying a project marker.
3033
+ * @param cwd - absolute session working directory.
3034
+ * @param markers - directory/file marker names.
3035
+ * @param fileMarkers - file suffixes that also mark a project root.
3036
+ * @returns the absolute project root, or `undefined` when no marker is found.
3037
+ */
3038
+ export declare function findProjectRoot(cwd: string, markers?: readonly string[], fileMarkers?: readonly string[]): string | undefined;
3039
+ /**
3040
+ * Directories that hold this project's MCP documents. Used by the flat-watch
3041
+ * fallback when the runtime cannot watch a tree recursively.
3042
+ * @param projectRoot - absolute project root.
3043
+ * @param files - configured project-relative specs, lowest priority first.
3044
+ * @param env - environment used to resolve `$DSH_HOME`.
3045
+ * @returns existing directories, project root first, deduplicated.
3046
+ */
3047
+ export declare function configDirectories(projectRoot: string, files?: readonly string[], env?: Record<string, string | undefined>): string[];
3048
+ //#endregion
3049
+ //#region src/parse.d.ts
3050
+ /** Severity of a parse diagnostic. */
3051
+ type IssueLevel = 'error' | 'warning';
3052
+ /** One diagnostic produced while reading a document. */
3053
+ interface ParseIssue {
3054
+ /** Absolute path of the document (or a pseudo-path for in-memory input). */
3055
+ source: string;
3056
+ /** Server key the diagnostic belongs to, when it is entry-scoped. */
3057
+ server?: string;
3058
+ /** Whether the entry is unusable (`error`) or merely notable (`warning`). */
3059
+ level: IssueLevel;
3060
+ /** Human-readable description. */
3061
+ message: string;
3062
+ /**
3063
+ * Stable wire code of `message` (`projectMcp.host` namespace), for
3064
+ * client-side translation. Additive: `message` keeps its byte-identical
3065
+ * English and stays the fallback, and behavioural matches key on this field
3066
+ * — never on the prose, which the client may have translated.
3067
+ */
3068
+ code?: string;
3069
+ /** Flat params of {@link ParseIssue.code}, stringified at emission. */
3070
+ params?: Record<string, string>;
3071
+ }
3072
+ /** One parsed `mcpServers` entry: exactly one of `config` / `error` is set. */
3073
+ interface ParsedEntry {
3074
+ /** Key in `mcpServers` (or the sanitized form of it). */
3075
+ name: string;
3076
+ /** `false` only for an explicit `enabled: false` / `disabled: true`. */
3077
+ enabled: boolean;
3078
+ /** Absolute path of the document the entry came from. */
3079
+ source: string;
3080
+ /** mcp-client config, ready to mount. */
3081
+ config?: Config$1;
3082
+ /** Why the entry cannot be mounted. */
3083
+ error?: string;
3084
+ /**
3085
+ * Stable wire code of `error` (`projectMcp.host` namespace) — the path by
3086
+ * which a parse failure becomes a translated `row.detail` on the client.
3087
+ */
3088
+ errorCode?: string;
3089
+ /** Flat params of {@link ParsedEntry.errorCode}, stringified at emission. */
3090
+ errorParams?: Record<string, string>;
3091
+ }
3092
+ /** External values needed to expand `${...}` references. */
3093
+ interface ResolveContext {
3094
+ /** Ambient environment (`process.env`). */
3095
+ env: Record<string, string | undefined>;
3096
+ /** Project-local dotenv values (`<project>/.env`, then `<project>/.dsh/.env`). */
3097
+ dotenv: Record<string, string>;
3098
+ /** Plugin-level `inputs` config: explicit `${input:NAME}` values. */
3099
+ inputs: Record<string, string>;
3100
+ /** Values read from the DSH credentials file. */
3101
+ secrets: Record<string, string>;
3102
+ /**
3103
+ * Identity of the three value sources above, so a caller that caches whole
3104
+ * parsed documents can tell "the same values answered this parse" from "the
3105
+ * files moved". Opaque here: the parser never reads it.
3106
+ */
3107
+ stamp?: string;
3108
+ /** Project root used as the default `cwd` of stdio servers. */
3109
+ projectRoot: string;
3110
+ /** Timeout applied to every generated config. */
3111
+ toolCallTimeoutMs: number;
3112
+ /** Whether a failed initial connection should reject the mount. */
3113
+ failOnStartupError: boolean;
3114
+ }
3115
+ /** Result of parsing one document. */
3116
+ interface ParsedDocument {
3117
+ /** Entries in document order. */
3118
+ entries: ParsedEntry[];
3119
+ /** Diagnostics for the document itself and for individual entries. */
3120
+ issues: ParseIssue[];
3121
+ /** `false` when the file could not be read or held no server map. */
3122
+ ok: boolean;
3123
+ }
3124
+ /**
3125
+ * Parse the text of one MCP document.
3126
+ * @param text - raw file content.
3127
+ * @param source - absolute path used for diagnostics and for entry `source`.
3128
+ * @param ctx - values used to expand references and to fill config defaults.
3129
+ * @returns parsed entries plus diagnostics; `ok` reports whether a server map was found.
3130
+ */
3131
+ export declare function parseDocument(text: string, source: string, ctx: ResolveContext): ParsedDocument;
3132
+ /**
3133
+ * Merge per-document entry lists in priority order; a later document overrides
3134
+ * an earlier entry with the same `serverName`, keeping the position where that
3135
+ * name first appeared.
3136
+ * @param groups - entry lists from lowest to highest priority.
3137
+ * @returns merged entries plus the names that were overridden.
3138
+ */
3139
+ export declare function mergeEntries(groups: ParsedEntry[][]): {
3140
+ entries: ParsedEntry[];
3141
+ overridden: string[];
3142
+ };
3143
+ /** Parse a YAML-ish credentials file into a flat string map. */
3144
+ export declare function parseCredentials(text: string): Record<string, string>;
3145
+ //#endregion
3146
+ //#region src/guidance.d.ts
3147
+ /** `true` unless a deployment turns the guidance section off. */
3148
+ export declare const DEFAULT_GUIDANCE_ENABLED = true;
3149
+ /**
3150
+ * Section name. At equal orders sections sort by code-unit name, and `-`
3151
+ * (0x2D) precedes `:` (0x3A), so this name — exactly like mcp-resources'
3152
+ * `mcp-resource-servers` — sorts ahead of every `mcp:<server>` instruction
3153
+ * block mcp-client publishes at the same order.
3154
+ */
3155
+ export declare const GUIDANCE_SECTION_NAME = "mcp-project-guidance";
3156
+ /** Hard cap on the section text; {@link buildGuidance} never returns more. */
3157
+ export declare const MAX_GUIDANCE_CHARS = 1200;
3158
+ /** Server bullets rendered at most, before the rest is summarized. */
3159
+ export declare const MAX_GUIDANCE_SERVERS = 8;
3160
+ /** Deferred tool names the on-demand inventory line shows before `+N more`. */
3161
+ export declare const MAX_GUIDANCE_HIDDEN_NAMES = 12;
3162
+ /** Longest purpose text kept in one server bullet. */
3163
+ export declare const MAX_GUIDANCE_PURPOSE = 80;
3164
+ /** One mounted server, as far as the guidance section describes it. */
3165
+ interface GuidanceServer {
3166
+ /** `serverName` of the mount. */
3167
+ readonly name: string;
3168
+ /** Transport, when the mount has one. */
3169
+ readonly transport?: 'stdio' | 'streamable-http';
3170
+ /** Live mount state. */
3171
+ readonly status: ServerStatus;
3172
+ /** Tool names the server currently publishes, in any order. */
3173
+ readonly tools?: readonly string[];
3174
+ /** Optional one-line purpose, shown after the server name. */
3175
+ readonly purpose?: string;
3176
+ }
3177
+ /**
3178
+ * Plain input of {@link buildGuidance}. Every field is optional so a caller
3179
+ * that predates this feature (or a test) can pass a bare object; the defaults
3180
+ * describe "no project, no servers".
3181
+ */
3182
+ interface GuidanceInput {
3183
+ /** `~`-collapsed project label; defaults to `this project`. */
3184
+ readonly project?: string;
3185
+ /** Mounted servers, in any order. */
3186
+ readonly servers?: readonly GuidanceServer[];
3187
+ /** Tool names offered directly in the request right now. */
3188
+ readonly offered?: readonly string[];
3189
+ /** Tool names reachable only through `mcp_search_tools` right now. */
3190
+ readonly deferred?: readonly string[];
3191
+ /**
3192
+ * The counter-seeded hot tools, most-called first. They are offered directly
3193
+ * from the first step on; naming them keeps the model from searching for
3194
+ * what it already has.
3195
+ */
3196
+ readonly mostUsed?: readonly string[];
3197
+ /** Whether the on-demand search surface is on; defaults to the activation default. */
3198
+ readonly activationEnabled?: boolean;
3199
+ }
3200
+ /**
3201
+ * Build the project-MCP guidance section.
3202
+ *
3203
+ * Deterministic and total: server bullets follow code-unit name order, the
3204
+ * deferred surface is listed as one flat, sorted, deduped names line, and the
3205
+ * result never exceeds {@link MAX_GUIDANCE_CHARS} — when it would, trailing
3206
+ * server bullets are replaced by an `and N more server(s)` line, the on-demand
3207
+ * paragraph and the names line are reserved their room first, and a final cut
3208
+ * falls back to the last complete line. Equal input always yields equal
3209
+ * output, and `''` means there is nothing worth saying.
3210
+ *
3211
+ * @param input - project label, mounted servers and the offered/deferred split.
3212
+ * @returns markdown for one prompt section, or `''`.
3213
+ */
3214
+ export declare function buildGuidance(input: GuidanceInput): string;
3215
+ /**
3216
+ * `~`-collapsed display label for a project root.
3217
+ *
3218
+ * The session prompt must never carry an absolute path or a local machine
3219
+ * identifier, so the label is the home-relative form when the root lives under
3220
+ * `home` and the directory name otherwise. `home` is passed in rather than read
3221
+ * from the environment, which keeps the helper pure and testable.
3222
+ *
3223
+ * @param projectRoot - absolute project root, or any path-shaped string.
3224
+ * @param home - home directory to collapse to `~`, when known.
3225
+ * @returns a relative `~/…` label, the directory name, or `this project`.
3226
+ */
3227
+ export declare function projectLabel(projectRoot: string, home?: string): string;
3228
+ /** The prompt-section fields this module registers (structural view). */
3229
+ interface GuidanceSectionLike {
3230
+ /** Unique section name. */
3231
+ readonly name: string;
3232
+ /** Numeric sort order. */
3233
+ readonly order: number;
3234
+ /** `false` preserves literal text; this section carries no variables. */
3235
+ readonly interpolate?: boolean;
3236
+ /** Text, or a provider evaluated at each assembly. */
3237
+ readonly text: string | (() => string);
3238
+ }
3239
+ /** The `systemPrompt` slice the wiring reads (structural view). */
3240
+ interface GuidancePromptLike {
3241
+ /**
3242
+ * Register one ordered section in the calling scope.
3243
+ * @param section - the section to register.
3244
+ * @returns the registration's effect disposer.
3245
+ */
3246
+ section(section: GuidanceSectionLike): unknown;
3247
+ /**
3248
+ * Resolve a centrally owned placement.
3249
+ * @param name - stable placement name.
3250
+ * @returns the numeric sort order.
3251
+ */
3252
+ getSectionOrder(name: 'MCP_SERVERS'): number;
3253
+ }
3254
+ /** The injected scope carrying `systemPrompt`. */
3255
+ interface GuidancePromptScopeLike {
3256
+ /** The prompt registry. */
3257
+ readonly systemPrompt: GuidancePromptLike;
3258
+ }
3259
+ /**
3260
+ * The agent-scoped context slice the guidance wiring touches. Described
3261
+ * structurally so the wiring is testable without a live harness.
3262
+ */
3263
+ interface GuidanceContextLike {
3264
+ /**
3265
+ * Start a callback once the injected services exist; the injected scope owns
3266
+ * what the callback registers.
3267
+ * @param deps - service names the callback requires.
3268
+ * @param callback - receives the injected scope.
3269
+ * @returns a disposer for the callback's own fiber, when the runtime gives one.
3270
+ */
3271
+ inject(deps: readonly string[], callback: (inner: GuidancePromptScopeLike) => unknown): unknown;
3272
+ }
3273
+ /** Wiring options for {@link installGuidance}. */
3274
+ interface GuidanceWiringOptions {
3275
+ /** Agent-scoped context; the section lives here. */
3276
+ readonly ctx: GuidanceContextLike;
3277
+ /** Live section text; called at every assembly, so it may read changing state. */
3278
+ readonly text: () => string;
3279
+ /** Section name override; defaults to {@link GUIDANCE_SECTION_NAME}. */
3280
+ readonly name?: string;
3281
+ /** Sink for a contained failure of this plugin's own work. */
3282
+ readonly onError?: (error: unknown) => void;
3283
+ }
3284
+ /**
3285
+ * Register the guidance section on one agent scope.
3286
+ *
3287
+ * The section goes in through `ctx.inject(['systemPrompt'], …)`, so the scope
3288
+ * fiber owns it and a scope disposal unregisters it with the real registry.
3289
+ * The returned disposer is the explicit path for a host that publishes a plain
3290
+ * `systemPrompt` stub — the runtime keeps it and releases it exactly when it
3291
+ * releases the scope (idle release and agent disposal), so no section outlives
3292
+ * its mounts. It is idempotent.
3293
+ *
3294
+ * @param options - scope, live text provider and an optional failure sink.
3295
+ * @returns the disposer that unregisters everything installed here.
3296
+ */
3297
+ export declare function installGuidance(options: GuidanceWiringOptions): () => void;
3298
+ //#endregion
3299
+ //#region src/usage.d.ts
3300
+ /** Current on-disk document version; another version is ignored, not migrated. */
3301
+ export declare const USAGE_VERSION = 1;
3302
+ /** Counter document name under `$DSH_HOME`. */
3303
+ export declare const USAGE_FILE_NAME = "dsh-project-mcp-usage.json";
3304
+ /** Counters keyed by project root, then by `serverName`. */
3305
+ type UsageState = Record<string, Record<string, ServerUsage>>;
3306
+ /** The durable counter document as written to disk. */
3307
+ interface UsageDocument {
3308
+ /** Document version; a reader that does not know it starts clean. */
3309
+ version: typeof USAGE_VERSION;
3310
+ /** Counters of every project ever seen. */
3311
+ projects: UsageState;
3312
+ }
3313
+ /** One registry call, before it is attributed to a mounted server. */
3314
+ interface UsageCall {
3315
+ /** Project root the calling agent resolved to. */
3316
+ projectRoot: string;
3317
+ /** Server names this plugin currently mounts for that project. */
3318
+ servers: ReadonlySet<string>;
3319
+ /**
3320
+ * Public tool name delivered by `tools/result`, ie `mcp__<serverName>__<name>`.
3321
+ * A name the registry had to truncate to the function-name budget keeps this
3322
+ * prefix, so the server is still identifiable.
3323
+ */
3324
+ toolName: string;
3325
+ /** `true` when the settled result carried an error. */
3326
+ isError: boolean;
3327
+ /** Epoch milliseconds of the call. */
3328
+ at: number;
3329
+ /**
3330
+ * Session the call belongs to: the id of the agent that made it.
3331
+ *
3332
+ * The host resolves an agent from the call's own event, and every other
3333
+ * surface of this plugin already calls that id the session id (a `LogEvent`,
3334
+ * a `SessionSnapshot`). Counting is therefore attributable without a second
3335
+ * lookup, which is what lets the panel answer "and how much of this is mine?"
3336
+ * (F-34).
3337
+ */
3338
+ sessionId: string;
3339
+ }
3340
+ /** One counted call, attributed to a project and a server this plugin mounted. */
3341
+ interface UsageEvent {
3342
+ /** Project root the calling agent resolved to. */
3343
+ projectRoot: string;
3344
+ /** `serverName` this plugin mounted for that project. */
3345
+ serverName: string;
3346
+ /**
3347
+ * Tool name as declared by the server, ie without the `mcp__<serverName>__`
3348
+ * prefix. A name the registry truncated to its function-name budget cannot be
3349
+ * reversed, so its key is the public suffix the registry published.
3350
+ */
3351
+ tool: string;
3352
+ /** `true` when the settled result carried an error. */
3353
+ isError: boolean;
3354
+ /** Epoch milliseconds of the call. */
3355
+ at: number;
3356
+ /** Session (agent) id this call is counted under, besides the project total. */
3357
+ sessionId: string;
3358
+ }
3359
+ /** The `tools/result` execution view this module reads. */
3360
+ interface ToolResultEventLike {
3361
+ /** Public tool name, `mcp__<serverName>__<name>`. */
3362
+ readonly name: string;
3363
+ /** Agent the call ran for; absent on a host-level call, which is not counted. */
3364
+ readonly agent?: {
3365
+ readonly id: string;
3366
+ } | undefined;
3367
+ }
3368
+ /** The settled `tools/result` outcome view this module reads. */
3369
+ interface ToolResultLike {
3370
+ /** `true` when the call settled as an error. */
3371
+ readonly isError: boolean;
3372
+ }
3373
+ /** Everything {@link observeToolResults} needs, injected so it is testable. */
3374
+ interface ToolResultObserverOptions {
3375
+ /** Register the `tools/result` listener; returns its disposer. */
3376
+ on(name: 'tools/result', handler: (exec: ToolResultEventLike, result: ToolResultLike) => undefined): (() => void) | undefined;
3377
+ /** Resolve the project and the mounted servers of the agent that made a call. */
3378
+ mountsFor(agentId: string): {
3379
+ projectRoot: string;
3380
+ servers: ReadonlySet<string>;
3381
+ } | undefined;
3382
+ /** Durable store the attributed calls are recorded in. */
3383
+ store: Pick<UsageStore, 'record'>;
3384
+ /** Clock override; defaults to `Date.now`. */
3385
+ now?: () => number;
3386
+ }
3387
+ /** The logger surface the store uses; a Cordis logger satisfies it. */
3388
+ interface UsageLogger {
3389
+ /** Non-fatal report; the store never throws at its caller. */
3390
+ warn(message: string): void;
3391
+ }
3392
+ /** Construction options for {@link UsageStore}; production uses the defaults. */
3393
+ interface UsageStoreOptions {
3394
+ /** Absolute document path; defaults to `$DSH_HOME/dsh-project-mcp-usage.json`. */
3395
+ file?: string;
3396
+ /** Debounce before a recorded call reaches disk. */
3397
+ flushMs?: number;
3398
+ /** Sink for a corrupt document or a failed write. */
3399
+ logger?: UsageLogger;
3400
+ }
3401
+ /**
3402
+ * Attribute one registry tool name to a server this plugin mounted.
3403
+ *
3404
+ * The prefix is never parsed blindly: only mounted names are candidates, and
3405
+ * the longest match wins, so a mounted `alpha_` is never shadowed by a mounted
3406
+ * `alpha` when both publish tools into one scope.
3407
+ *
3408
+ * @param toolName - public registry name, `mcp__<serverName>__<name>`.
3409
+ * @param servers - names this plugin mounted for the calling agent's project.
3410
+ * @returns the matched `serverName`, or `undefined` for a foreign tool.
3411
+ */
3412
+ export declare function matchServer(toolName: string, servers: ReadonlySet<string>): string | undefined;
3413
+ /**
3414
+ * Attribute one registry call, or `undefined` when no server this plugin
3415
+ * mounted for the project claims the name.
3416
+ * @param call - the raw `tools/result` view plus the caller's mounts.
3417
+ * @returns the counted event, ready for {@link recordUsage}.
3418
+ */
3419
+ export declare function usageEventFor(call: UsageCall): UsageEvent | undefined;
3420
+ /**
3421
+ * Count one call into the state.
3422
+ *
3423
+ * Pure: it reads and returns counters only, touching no filesystem, clock or
3424
+ * logger, so the model is testable on its own.
3425
+ *
3426
+ * @param state - counters before the call.
3427
+ * @param event - one attributed call.
3428
+ * @returns a new state carrying the increment; `lastUsedAt` moves and is set
3429
+ * only on a success, while a failure keeps the previous stamp.
3430
+ */
3431
+ export declare function recordUsage(state: UsageState, event: UsageEvent): UsageState;
3432
+ /**
3433
+ * Subscribe the durable counters to `tools/result`.
3434
+ *
3435
+ * Counting is per event, never deduplicated against a parent: a programmatic
3436
+ * sub-dispatch is its own call with its own result, while the enclosing
3437
+ * `run_code` carries a name no server claims, so each MCP call is counted
3438
+ * exactly once on either path.
3439
+ *
3440
+ * @param options - registry subscription, agent resolver, store and clock.
3441
+ * @returns the disposer that unregisters the listener.
3442
+ */
3443
+ export declare function observeToolResults(options: ToolResultObserverOptions): () => void;
3444
+ /**
3445
+ * The durable counters: one versioned document under `$DSH_HOME`, loaded once
3446
+ * when the plugin applies and written atomically on a debounce.
3447
+ *
3448
+ * Every failure mode is non-fatal by design. A missing, unreadable, foreign or
3449
+ * older-version document starts clean, and a write that fails is logged and
3450
+ * forgotten, because a tool call must never fail on a counter that could not
3451
+ * be stored.
3452
+ */
3453
+ export declare class UsageStore {
3454
+ private state;
3455
+ private timer;
3456
+ private dirty;
3457
+ private disposed;
3458
+ private readonly file;
3459
+ private readonly flushMs;
3460
+ private readonly logger;
3461
+ /** @param options - document path, debounce and log sink. */
3462
+ constructor(options?: UsageStoreOptions);
3463
+ /** Counters of one project root, or `undefined` when it has none yet. */
3464
+ forProject(projectRoot: string): Record<string, ServerUsage> | undefined;
3465
+ /** Count one attributed call and schedule the debounced write. */
3466
+ record(event: UsageEvent): void;
3467
+ /** Write the counters atomically now. Best effort: it never throws. */
3468
+ flush(): void;
3469
+ /**
3470
+ * Cancel the pending write, flush what is dirty, and stop counting. Safe to
3471
+ * call more than once; the plugin fiber calls it on disposal.
3472
+ */
3473
+ dispose(): void;
3474
+ private load;
3475
+ }
3476
+ /**
3477
+ * Parse one durable counter document.
3478
+ *
3479
+ * Anything this version cannot trust — malformed JSON, a foreign shape, or
3480
+ * another version — yields `undefined` so the caller starts clean instead of
3481
+ * throwing, and each counter is validated so a hand-edited document cannot
3482
+ * poison later arithmetic.
3483
+ *
3484
+ * @param text - raw document contents.
3485
+ * @returns the counters, or `undefined` when the document is not usable.
3486
+ */
3487
+ export declare function parseUsageDocument(text: string): UsageState | undefined;
3488
+ //#endregion
3489
+ //#region src/ui.d.ts
3490
+ /** The subset of the DSH web server this plugin registers on. */
3491
+ interface WebServerLike {
3492
+ /** Register one route and return its disposer, in whatever shape the server uses. */
3493
+ register(route: {
3494
+ kind: 'prefix';
3495
+ path: string;
3496
+ handler: RouteHandler;
3497
+ }): unknown;
3498
+ }
3499
+ /** Node HTTP handler signature the web server expects. */
3500
+ type RouteHandler = (req: IncomingMessage, res: ServerResponse) => Promise<void>;
3501
+ /**
3502
+ * The status channel: one open `GET events` response per panel, and a frame
3503
+ * whenever the picture changes.
3504
+ *
3505
+ * Server-Sent Events rather than polling: DSH's own web server hands a route the
3506
+ * raw response ("owns the full response lifecycle, may hold the response open,
3507
+ * e.g. SSE") and exempts `text/event-stream` from its gzip filter, and the
3508
+ * browser's `EventSource` reconnects on its own. The subscription is only held
3509
+ * while somebody is listening, and the heartbeat only runs with a stream open.
3510
+ */
3511
+ interface EventStream {
3512
+ /** Serve one `GET events`: the response stays open until the client leaves. */
3513
+ serve(req: IncomingMessage, res: ServerResponse): void;
3514
+ /** Close every open stream and stop listening; the route's disposer calls it. */
3515
+ dispose(): void;
3516
+ }
3517
+ /**
3518
+ * Build the route handler for {@link ROUTE_PREFIX}.
3519
+ *
3520
+ * Both operator actions — `Sync` and `Retry` — answer as soon as they are
3521
+ * accepted, never once the servers they touch have settled: the pass they queue
3522
+ * runs in the background, and the panel reads the outcome from the status
3523
+ * channel. A response held open for a mount that is still connecting is exactly
3524
+ * the hang this route no longer produces.
3525
+ *
3526
+ * @param service - the runtime's published service.
3527
+ * @param events - the status channel to serve; built from the service when omitted.
3528
+ * @returns a handler for `GET snapshot|events|logs`, `POST sync|retry|release|save`.
3529
+ */
3530
+ export declare function createRouteHandler(service: ProjectMcpService, events?: EventStream): RouteHandler;
3531
+ /**
3532
+ * Register the panel routes on the DSH web server.
3533
+ * @param webServer - the injected web server service.
3534
+ * @param service - the runtime's published service.
3535
+ * @returns the disposer: it closes the open status streams, then the routes.
3536
+ */
3537
+ export declare function registerRoutes(webServer: WebServerLike, service: ProjectMcpService): () => void;
3538
+ /**
3539
+ * Run one registration's disposer, whichever shape the web server hands back:
3540
+ * Cordis only ever calls a disposer *function* for an effect, and the server may
3541
+ * return a `{ dispose() }` object instead.
3542
+ * @param registration - the value `registerRoutes` returned.
3543
+ */
3544
+ export declare function disposeRegistration(registration: unknown): void;
3545
+ //#endregion
3546
+ //#region src/index.d.ts
3547
+ /**
3548
+ * Plugin config: everything two deployments may want to set differently.
3549
+ *
3550
+ * Live editing: on DSH ≥ 0.1.7 the keys of {@link VOLATILE_CONFIG_KEYS} arrive
3551
+ * not as plain values but as volatile refs (`{ get(): T }`, see
3552
+ * {@link VolatileLike}) that the host re-points on every profile edit and
3553
+ * re-reads on `loader/volatile-update`. Every read of those keys goes through
3554
+ * {@link liveValue}, which accepts both shapes, so a plain object — yaml
3555
+ * config on an older host, and every test fixture — keeps working unchanged.
3556
+ */
3557
+ export interface Config {
3558
+ /** Master switch; `false` mounts nothing and reads nothing. */
3559
+ enabled?: boolean;
3560
+ /**
3561
+ * Project-relative MCP documents to read, lowest priority first — a later
3562
+ * document overrides an earlier entry of the same `serverName`. A spec is
3563
+ * relative to the project root, or absolute, or `~/…` / `$DSH_HOME/…`.
3564
+ * Default: `['.dsh/mcp.json']`.
3565
+ */
3566
+ localFiles?: string[];
3567
+ /**
3568
+ * Global MCP documents read before a project's own, lowest priority first.
3569
+ * A relative spec resolves against `$HOME`; `~`, `$DSH_HOME` and absolute
3570
+ * paths work as in {@link localFiles}. Empty — the default — reads none, so
3571
+ * a project never inherits a server it did not declare.
3572
+ *
3573
+ * A boolean is accepted as a **migration guard only**, for a config written
3574
+ * when this key was the switch "also read `~/.dsh/mcp.json` and
3575
+ * `~/.kimi-code/mcp.json`": `true` reads `~/.dsh/mcp.json`, `false` reads
3576
+ * nothing. Set a list instead.
3577
+ */
3578
+ globalFiles?: string[] | boolean;
3579
+ /** Read `<project>/.env` and `<project>/.dsh/.env` for `${...}` values. */
3580
+ envFiles?: boolean;
3581
+ /** Values for `${input:NAME}` references, consulted before env and credentials. */
3582
+ inputs?: Record<string, string>;
3583
+ /** Directory names that terminate the upward project-root walk. */
3584
+ projectMarkers?: string[];
3585
+ /** File suffixes that also terminate the upward project-root walk. */
3586
+ fileMarkers?: string[];
3587
+ /** Timeout for every generated mcp-client config. */
3588
+ toolCallTimeoutMs?: number;
3589
+ /** Whether a failed initial MCP connection should fail the mount. */
3590
+ failOnStartupError?: boolean;
3591
+ /** Report a mount that produced no tool within this window as an error row; `0` disables. */
3592
+ connectTimeoutMs?: number;
3593
+ /** Mount a session's project on its first turn instead of at session creation. */
3594
+ lazy?: boolean;
3595
+ /** Release a session's mounts after this much inactivity; `0` disables. */
3596
+ idleTimeoutMs?: number;
3597
+ /** How long the first step of a turn may wait for a pending mount; `0` never waits. */
3598
+ activationWaitMs?: number;
3599
+ /** Profile-level `serverName` reservations win; the project row becomes `conflict`. */
3600
+ profileWins?: boolean;
3601
+ /**
3602
+ * Local namespace a project entry mounts under when the profile already owns
3603
+ * its `serverName` and the user chose to see this project's copy as well,
3604
+ * at most five characters (`[A-Za-z0-9_-]`, {@link isValidLocalPrefix}).
3605
+ * Empty — the default — derives one from the project's own folder, so a
3606
+ * conflict has an answer without a setting. Only the local answer reads it:
3607
+ * the choice that mounts the entry under its declared name needs no prefix.
3608
+ */
3609
+ localPrefix?: string;
3610
+ /** Watch project config documents for edits and re-sync. */
3611
+ watch?: boolean;
3612
+ /** Debounce applied to watcher and lifecycle events (ms). */
3613
+ debounceMs?: number;
3614
+ /** Safety-net rescan interval (ms). */
3615
+ rescanIntervalMs?: number;
3616
+ /** Credentials document consulted for `${input:NAME}` values. */
3617
+ credentialsFile?: string;
3618
+ /**
3619
+ * Offer the session's MCP tools through `mcp_search_tools` + activation, and
3620
+ * put the active ones back into each assembled request. `false` restores the
3621
+ * plain registry presentation: every mounted tool is always listed.
3622
+ */
3623
+ activationEnabled?: boolean;
3624
+ /** Tools the durable counters may seed into the always-offered baseline; `0` seeds none. */
3625
+ activationSeeded?: number;
3626
+ /** Calls one tool needs in the counters before it is seeded into the baseline. */
3627
+ activationMinCalls?: number;
3628
+ /** Drop a session-activated tool after this long without a call; `0` disables. */
3629
+ toolIdleMs?: number;
3630
+ /**
3631
+ * Publish one short project-MCP guidance section in the session's system
3632
+ * prompt, ahead of the per-server `mcp:<server>` instruction blocks, so the
3633
+ * model knows the rest of the project's tools can be requested. `false`
3634
+ * registers no section at all.
3635
+ */
3636
+ guidanceEnabled?: boolean;
3637
+ /**
3638
+ * Cap on the names the context-driven tier offers at once; `0` disables the
3639
+ * tier. Optional so a config object that predates this feature keeps the
3640
+ * shipped default.
3641
+ */
3642
+ activationAutoLimit?: number;
3643
+ /** Extra advances one context-driven offer survives after leaving the ranking. */
3644
+ activationAutoStickySteps?: number;
3645
+ /**
3646
+ * Serialized size of a session's MCP surface, in characters, above which its
3647
+ * tools are offered on demand instead of being listed; `0` defers every
3648
+ * surface, however small.
3649
+ */
3650
+ activationToolBudgetChars?: number;
3651
+ /**
3652
+ * Permit the panel to write the documents of the `globalFiles` list. `false`
3653
+ * keeps them read-only; a write also needs an explicit per-write consent, so
3654
+ * both gates must be open. Default `false`.
3655
+ */
3656
+ allowGlobalWrite?: boolean;
3657
+ }
3658
+ /**
3659
+ * The volatile-ref shape a DSH ≥ 0.1.7 host hands a volatile config field: a
3660
+ * stable reference whose `get()` reads the current, live-edited value.
3661
+ * Declared locally so no cordis version is needed to name it; an older host
3662
+ * passes the plain value instead, which {@link liveValue} also accepts.
3663
+ */
3664
+ interface VolatileLike<T> {
3665
+ get(): T;
3666
+ }
3667
+ declare module '@deepseek-ai/cordis' {
3668
+ interface Events {
3669
+ /**
3670
+ * Volatile config values were committed into the running fiber without a
3671
+ * remount; dispatched to the owning fiber only.
3672
+ * @param paths - changed config paths as key arrays.
3673
+ */
3674
+ 'loader/volatile-update'(paths: readonly (readonly string[])[]): void;
3675
+ }
3676
+ }
3677
+ /**
3678
+ * Read one config field that may be a live-edited volatile ref.
3679
+ * @param field - plain value, or a {@link VolatileLike} ref wrapping it.
3680
+ * @returns the current value, whichever shape arrived.
3681
+ */
3682
+ export declare function liveValue<T>(field: T | VolatileLike<T> | undefined): T | undefined;
3683
+ /**
3684
+ * The {@link Config} keys a DSH ≥ 0.1.7 host may live-edit without restarting
3685
+ * the entry: all of them are read at use time, so merging them into the
3686
+ * running config is safe. Every other key is structural or boot-time
3687
+ * (documents, markers, credentials, the watch switch) and stays yaml-only.
3688
+ */
3689
+ export declare const VOLATILE_CONFIG_KEYS: readonly (keyof RuntimeConfig)[];
3690
+ /** Validated Loader schema for {@link Config}. */
3691
+ export declare const Config: z<Config>;
3692
+ /** Cordis plugin name used by loader diagnostics. */
3693
+ export declare const name = "project-mcp";
3694
+ /** Services required before project MCP servers can be mounted. */
3695
+ export declare const inject: string[];
3696
+ /** Service name under which the runtime publishes its snapshot. */
3697
+ export declare const SERVICE_NAME = "projectMcp";
3698
+ /** Read-only handle published as the `projectMcp` service. */
3699
+ export interface ProjectMcpService {
3700
+ /** Current rows per project with live sessions, merged and split per session. */
3701
+ snapshot(): McpSnapshot;
3702
+ /**
3703
+ * Run one reconciliation pass immediately and await it, as the operator call:
3704
+ * it may start a session's declared servers without that session having
3705
+ * started a turn. Every other pass — a turn, an event, the rescan tick —
3706
+ * mounts only the sessions whose own working directory asked for their
3707
+ * project.
3708
+ * @param projectRoot - restricts the pass to one project's sessions.
3709
+ */
3710
+ syncNow(projectRoot?: string): Promise<void>;
3711
+ /**
3712
+ * Ask for the same pass and answer at once, without waiting for it: the
3713
+ * panel's `Sync`. Scripted reconciliation awaits {@link ProjectMcpService.syncNow}.
3714
+ * @param projectRoot - restricts the pass to one project's sessions.
3715
+ */
3716
+ syncSoon(projectRoot?: string): void;
3717
+ /**
3718
+ * Drop the failed mounts and re-mount them (after fixing their cause). Answers
3719
+ * as soon as they are dropped; the pass that mounts them again runs in the
3720
+ * background, because waiting for it is what made the panel's `Retry` look
3721
+ * hung while a server was still connecting.
3722
+ * @param projectRoot - restricts the drop and the pass to one project.
3723
+ */
3724
+ retry(projectRoot?: string): Promise<void>;
3725
+ /**
3726
+ * Watch the picture instead of asking for it: the listener is told the current
3727
+ * state at once, then once per change that changes something. Backs the
3728
+ * panel's status channel, so an open panel polls nothing.
3729
+ * @param listener - told the revision and the whole snapshot it belongs to.
3730
+ * @returns a disposer that stops watching.
3731
+ */
3732
+ subscribe(listener: (change: SnapshotChange) => void): () => void;
3733
+ /** Give one session's servers back now, or every mounted session's when no id is given. */
3734
+ release(agentId?: string): Promise<void>;
3735
+ /**
3736
+ * Read one tool's detail for a row a panel opened: its model-facing
3737
+ * description, the fields its schema accepts, and the reason this session's
3738
+ * request does not carry it. Answered on demand instead of riding the
3739
+ * snapshot, because descriptions and schemas are the expensive part and this
3740
+ * is read once per opened row.
3741
+ * @param projectRoot - project root the panel read the row from.
3742
+ * @param sessionId - live agent id the row belongs to.
3743
+ * @param name - public registry name, as the panel drew it.
3744
+ * @returns the tool's facts, or the coded refusal the route maps to a status.
3745
+ */
3746
+ toolFacts(projectRoot: string, sessionId: string, name: string): ToolFactsOutcome;
3747
+ /**
3748
+ * Write one edited entry back to the document that declares it.
3749
+ * @param request - entry body, declaring document and the revision it was read at.
3750
+ * @returns the fresh snapshot, or the coded refusal the route maps to a status.
3751
+ */
3752
+ save(request: SaveRequest): Promise<SaveOutcome>;
3753
+ /**
3754
+ * Pin or unpin one tool of one project. Durable, and never a rescan: the policy
3755
+ * is not part of any declaring document.
3756
+ * @param request - project root, public tool name and the wanted pin state.
3757
+ * @returns the fresh snapshot, or the coded refusal the route maps to a status.
3758
+ */
3759
+ setPin(request: PinRequest): PolicyOutcome;
3760
+ /**
3761
+ * Store one project's tool mode (`disclosure` | `direct` | `off`).
3762
+ * @param request - project root and the mode to store.
3763
+ * @returns the fresh snapshot, or the coded refusal the route maps to a status.
3764
+ */
3765
+ setPolicy(request: PolicyRequest): PolicyOutcome;
3766
+ /**
3767
+ * Choose which declaration of one contested `serverName` this project shows.
3768
+ * Durable, and followed by a reconcile: the choice is what moves the entry
3769
+ * between a conflict report and a mount under its local name.
3770
+ * @param request - project root, contested name and the declaration to show.
3771
+ * @returns the fresh snapshot, or the coded refusal the route maps to a status.
3772
+ */
3773
+ setConflictChoice(request: ConflictRequest): PolicyOutcome;
3774
+ }
3775
+ /**
3776
+ * Mount project-declared MCP servers per session scope.
3777
+ * @param ctx - host context of the plugin entry.
3778
+ * @param config - validated plugin configuration.
3779
+ */
3780
+ export declare function apply(ctx: Context, config: Config): Promise<void>;
3781
+ /** Resolve the plugin config into the runtime's fully-defaulted shape. */
3782
+ export declare function resolveConfig(config: Config): RuntimeConfig;
3783
+ //#endregion
3784
+ export type { ActivationContextLike, ActivationState, ActivationWiringOptions, AgentLike, AgentMounts, AgentScopeLike, AssembleListener, AssemblyLike, GuidanceContextLike, GuidanceInput, GuidancePromptLike, GuidancePromptScopeLike, GuidanceSectionLike, GuidanceServer, GuidanceWiringOptions, ListenerLike, McpSnapshot, MountDecision, MountTrigger, PolicyDocument, PolicyLogger, PolicyOutcome, PolicySource, PolicyState, PolicyStoreOptions, ProjectSnapshot, RouteHandler, RuntimeConfig, RuntimeOptions, SaveOutcome, SearchToolOptions, SeedOptions, ServerRow, ServerStatus, ServerUsage, SessionEventLike, SessionSnapshot, SnapshotChange, SnapshotIssue, TextBlockLike, ToolDefinitionLike, ToolFactsOutcome, ToolResultEventLike, ToolResultLike, ToolResultObserverOptions, ToolSchemaLike, UsageCall, UsageDocument, UsageEvent, UsageLogger, UsageSource, UsageState, UsageStoreOptions, WebServerLike };
3785
+ //# sourceMappingURL=index.d.ts.map