dsh-project-mcp 0.4.2 → 0.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["compareNames","isRecord","MAX_SERVER_NAME_LENGTH","errorText","stringArray","stringRecord","DEFAULT_FLUSH_MS","isRecord","errorText","errorText","isRecord","isRecord","errorText"],"sources":["../src/types.ts","../src/activation.ts","../src/parse.ts","../src/discovery.ts","../src/guidance.ts","../src/naming.ts","../src/policy.ts","../src/bridge.ts","../src/logs.ts","../src/notifications.ts","../src/usage.ts","../src/write.ts","../src/runtime.ts","../src/shared.ts","../src/ui.ts","../src/index.ts"],"sourcesContent":["/**\n * Shared row/snapshot vocabulary for `dsh-project-mcp`.\n *\n * The host half publishes a {@link ProjectSnapshot} through the `projectMcp`\n * service so a future Web UI (or a test) can read what is mounted without\n * importing the runtime.\n *\n * @module dsh-project-mcp/types\n */\n\n/**\n * Type-only, and imported for its effect on the ambient types rather than for\n * anything this module uses: `@deepseek-ai/dsh-tools` declares `Context.tools`\n * and the `tools/change` / `tools/result` events as module augmentation of\n * `@deepseek-ai/cordis`, and TypeScript applies an augmentation only when the\n * augmenting module is part of the compilation. Nothing of the package reaches\n * the runtime — the import is erased by the compiler, and the plugin still\n * takes the service off the context it is handed instead of importing the\n * module.\n */\nimport type {} from '@deepseek-ai/dsh-tools'\n\n/** Runtime state of one project-declared MCP server. */\nexport type ServerStatus =\n /** Mounted and its tools are visible in the owning scope. */\n | 'active'\n /** Mounted; activation or the initial connection has not settled yet. */\n | 'connecting'\n /**\n * Declared, parsed, and not mounted: either `lazy` has not seen this\n * session's first turn yet, or the session went idle and its mounts were\n * released (`idleTimeoutMs`). The next turn mounts it again.\n */\n | 'idle'\n /** Declared with `enabled: false` — never mounted. */\n | 'disabled'\n /** The same `serverName` is reserved by a live profile-level instance. */\n | 'conflict'\n /** The entry or its mount failed; `detail` carries the reason. */\n | 'error'\n\n/** One server row of a project snapshot. */\nexport interface ServerRow {\n /** `serverName` (the `mcpServers` key, sanitized). */\n name: string\n /** Current lifecycle state. */\n status: ServerStatus\n /** Project root the entry was read from. */\n projectRoot: string\n /** Absolute path of the declaring document. */\n source?: string\n /** `stdio` or `streamable-http`, when the entry parsed. */\n transport?: 'stdio' | 'streamable-http'\n /**\n * Failure, stall or conflict explanation. Redacted on purpose: it names the\n * command but never its arguments, and an HTTP endpoint keeps its path but\n * drops the query string, because both can carry credentials.\n */\n detail?: string\n /**\n * Stable wire code of `detail` (`projectMcp.host` namespace), for\n * client-side translation. Optional and additive, exactly like\n * {@link blockedCode}: the prose field keeps its byte-identical English and\n * stays the fallback, so a client and a host of different builds degrade\n * rather than break.\n */\n detailCode?: string\n /**\n * Flat params of {@link detailCode}; a name ending in `Code` is itself a\n * wire code the client resolves two-level.\n */\n detailParams?: Record<string, string>\n /**\n * Parsed body of the entry, for the editor. Absent when the entry did not\n * parse — there is nothing to edit then.\n */\n entry?: EntrySnapshot\n /** Where this row may be written back, when it may be written at all. */\n writeScope?: WriteScope\n /** One line saying why writing is unavailable; always set for `readonly`. */\n writeBlockedReason?: string\n /**\n * Stable wire code of `writeBlockedReason` (`projectMcp.host` namespace),\n * for client-side translation. Optional and additive: the prose field keeps\n * its byte-identical English and stays the fallback, so a client and a host\n * of different builds degrade rather than break.\n */\n blockedCode?: string\n /**\n * Flat params of {@link blockedCode}; a name ending in `Code` is itself a\n * wire code the client resolves two-level.\n */\n blockedParams?: Record<string, string>\n /**\n * Opaque content revision of the declaring document at snapshot time. A save\n * must carry the revision it was built from: a mismatch means the document\n * changed underneath the editor, and the write is refused rather than merged.\n */\n documentRevision?: string\n}\n\n/**\n * How one `env` or `headers` entry is known to the host.\n *\n * A value can come from the declaring document, be answered outside it (the\n * project's own `.env` or the credentials file), or be withheld because it is a\n * credential. {@link EntryField.masked} is the field\n * that changes how a write treats it: a masked key submitted without a `value` is\n * kept exactly as the document declares it, so an editor that cannot see a secret\n * can never erase or replace one.\n */\nexport interface EntryField {\n /** Key exactly as declared. */\n readonly key: string\n /** Literal value; absent when the host withholds it. */\n readonly value?: string\n /** `true` when `value` is absent because the value is a secret. */\n readonly masked?: true\n /**\n * `true` when the key is answered outside the document — by the project's\n * `.env` or by the credentials file. The name predates the project dotenv\n * sources; the meaning the write path reads is \"never write this value back\".\n */\n readonly fromCredentials?: true\n}\n\n/**\n * One server entry as the host parsed it, for an editor.\n *\n * Every field is what the declaring document holds — a resolved default is never\n * folded in, because a save replaces the declaration, not the runtime config.\n */\nexport interface EntrySnapshot {\n /** Transport the entry declares. */\n readonly transport: 'stdio' | 'streamable-http'\n /** `stdio`: the program to run. */\n readonly command?: string\n /** `stdio`: its arguments, verbatim. */\n readonly args?: readonly string[]\n /** `stdio`: working directory, when the entry declares one. */\n readonly cwd?: string\n /** `stdio`: declared environment, secrets masked. */\n readonly env?: readonly EntryField[]\n /** `streamable-http`: the endpoint, with a credential-bearing query dropped. */\n readonly url?: string\n /** `streamable-http`: declared headers, secrets masked. */\n readonly headers?: readonly EntryField[]\n /** `false` when the declaration disables the server; absent means enabled. */\n readonly enabled?: boolean\n /** Declared connect timeout in milliseconds, when the entry sets one. */\n readonly connectTimeoutMs?: number\n /**\n * Keys the editor does not present, kept in their declared order and written\n * back untouched. A save replaces the entry wholesale, so dropping them would\n * delete configuration the panel never showed.\n */\n readonly extra?: Readonly<Record<string, unknown>>\n}\n\n/**\n * Whether one row's declaring document may be rewritten.\n *\n * - `project` — one of the deployment's project documents (`localFiles`,\n * `<project>/.dsh/mcp.json` out of the box);\n * - `global` — one of its global documents (`globalFiles`), written only with an\n * explicit per-write consent;\n * - `readonly` — the profile, `<DSH_HOME>` or a bundled document: never written.\n */\nexport type WriteScope = 'project' | 'global' | 'readonly'\n\n/**\n * One document a project is configured to read.\n *\n * The list a project publishes is exactly its read order — global documents\n * first, then the project's own — so the panel's priority number is an index\n * into it and never a table of hardcoded file names.\n */\nexport interface ConfiguredFile {\n /** Absolute path of the document. */\n readonly path: string\n /**\n * `global` — read for every project, before its own documents; `project` —\n * read from the project root.\n */\n readonly scope: 'global' | 'project'\n}\n\n/** Diagnostics surfaced alongside the rows. */\nexport interface SnapshotIssue {\n /** Absolute path of the declaring document. */\n source: string\n /** Server the diagnostic belongs to, when entry-scoped. */\n server?: string\n /** `error` or `warning`. */\n level: 'error' | 'warning'\n /** Human-readable text. */\n message: string\n /**\n * Stable wire code of `message` (`projectMcp.host` namespace), for\n * client-side translation. Optional and additive: `message` keeps its\n * byte-identical English and stays the fallback. Behavioural matches key on\n * this field — never on the prose, which the client may have translated.\n */\n code?: string\n /**\n * Flat params of {@link SnapshotIssue.code}; a name ending in `Code` is\n * itself a wire code the client resolves two-level.\n */\n params?: Record<string, string>\n}\n\n/**\n * One session's own view of the project it works in.\n *\n * Sessions of one project are independent: each mounts its own servers, and one\n * may have them running while another has not started a turn yet. The panel\n * needs that split, because a project-level merge alone cannot say *which*\n * session holds a mount.\n */\nexport interface SessionSnapshot {\n /** Agent (session) id. */\n id: string\n /** Rows for this session alone, in document order. */\n rows: ServerRow[]\n /** Diagnostics this session surfaced. */\n issues: SnapshotIssue[]\n /** What this session offers the model, when the host has mounted for it. */\n tools?: SessionTools\n /**\n * How many events of the project's ring belong to this session. Absent for a\n * session that produced none, so the tab's log badge reads a real `0`.\n */\n logCount?: number\n /**\n * `serverName` conflicts this session last reconciled: a profile-level\n * instance that already owns a name, or one name two project documents\n * declare. Published even when empty, so a reader can tell \"this session\n * reported none\" from a host that does not report conflicts at all.\n */\n conflicts?: readonly ServerConflict[]\n}\n\n/** One tool a session offers the model, and what put it in the request. */\nexport interface OfferedTool {\n /** Public registry name, eg `mcp__tglider__workspace`. */\n readonly name: string\n /**\n * The tier that offered it: `session` activated on demand through the search\n * tool, `context` ranked from the task text of the current conversation. The\n * counter-seeded baseline is not this shape — it is a plain name list in\n * {@link SessionTools.baseline}.\n */\n readonly via: 'session' | 'context'\n /**\n * Epoch milliseconds of the last offer or call. Absent for the context tier,\n * whose live state stamps an advance rather than a clock reading.\n */\n readonly at?: number\n /**\n * Number of the agent step (from `1`) the tool was offered at, or `undefined`\n * for a host that does not count steps. A panel that reads no number draws no\n * step tag at all rather than a made-up one.\n */\n readonly step?: number\n}\n\n/**\n * One accepted field of a tool's `parameters` schema, as the panel lists it.\n *\n * A field is listed from the definition the host already holds, so its type and\n * its `required` flag are the schema's own and neither is inferred from the\n * tool's name. Nesting stops at the top level: an object or array field is drawn\n * as its type, not expanded, because the panel lists what a call takes rather\n * than mirroring a schema. Schema `default` values are deliberately not part of\n * this shape — a default can carry a value the tool did not mean to publish.\n */\nexport interface ToolField {\n /** Property name, as the schema declares it. */\n readonly name: string\n /** JSON Schema `type` of the field, or `any` when the schema names none. */\n readonly type: string\n /** `true` when the schema's own `required` array names this property. */\n readonly required: boolean\n /** The property's own `description`, when the schema publishes one. */\n readonly description?: string\n}\n\n/**\n * Why one name is not in this session's request, in the host's own terms.\n *\n * The decision belongs to the host and the panel does not recompute it, so the\n * reason travels as data and its copy lives in the client's dictionaries. Every\n * figure here is a host measurement — the definition's own serialized size, the\n * session's budget, what the offered set already carries — so a reason line\n * invents no number. That is the same discipline as contract C2's step tag.\n */\nexport interface ToolReason {\n /**\n * Which decision left the name out. `budget` is the disclosure mode pushing it\n * past {@link ToolReason.budget}: the whole mounted surface is registered, and\n * this definition did not fit the request.\n */\n readonly kind: 'budget'\n /** Serialized size of this definition, in characters — the host's own figure. */\n readonly chars?: number\n /** The session's tool budget in characters, when the host budgeted one. */\n readonly budget?: number\n /** Characters the offered set already carries, when the host measured them. */\n readonly used?: number\n}\n\n/**\n * One tool's detail, answered on demand for a row the reader opened.\n *\n * The panel fetches this instead of carrying it in the snapshot: the snapshot\n * travels on every change frame and every poll, while a description and a schema\n * are read once per opened row. The text is model-facing and arrives as data —\n * it is never copied into a dictionary, is not translated, and is drawn as the\n * host published it.\n */\nexport interface ToolFacts {\n /** Public registry name this record answers about. */\n readonly name: string\n /** The definition's model-facing description, when the host holds one. */\n readonly description?: string\n /** Accepted fields, in schema order; empty when the tool declares none. */\n readonly fields: readonly ToolField[]\n /** Why the name is not offered, when it is not. Absent for an offered name. */\n readonly reason?: ToolReason\n}\n\n/**\n * Another loaded plugin that owns the assembled tool list.\n *\n * The plugin and such an owner cannot shape one request together: the outer\n * listener of whoever assembles last rewrites `assembly.tools`, so the plugin's\n * own deferral would be re-applied over an already-trimmed list. The host\n * reports the owner instead of silently composing with it, and a panel prints\n * the coexistence note only when this record is published.\n */\nexport interface PresentationOwner {\n /** Loader entry name, for example `dsh-progressive-tools`. */\n readonly name: string\n /** One line saying why coexisting in one request is impossible. */\n readonly note: string\n /**\n * The `projectMcp.host` code of {@link note} (F-48): the client translates\n * by it and falls back to `note`'s English, byte-identical, when the code is\n * absent or unknown. No params — the note is one fixed sentence.\n */\n readonly noteCode?: string\n}\n\n/**\n * One `serverName` two declarations fight over.\n *\n * `profile` is the profile-level `mcp-client` instance that already owns the\n * name: the project entry mounts only through the local alias the user chose,\n * and never under the contested name itself. `duplicate` is one name declared by\n * more than one project document: the highest-priority document wins and the\n * others are ignored.\n */\nexport interface ServerConflict {\n /** `serverName` the declarations share. */\n readonly server: string\n /** `profile` — a profile-level instance owns the name; `duplicate` — two documents. */\n readonly kind: 'profile' | 'duplicate'\n /** Declaring documents, the winner first. */\n readonly sources: readonly string[]\n /** One line: who wins, and why. */\n readonly message: string\n /**\n * The `projectMcp.host` code of {@link message} (F-48): the client translates\n * by it and falls back to `message`'s English, byte-identical, when the code\n * is absent (a host older than the field) or unknown to its dictionaries.\n */\n readonly code?: string\n /**\n * Flat params of {@link code}; numbers stringify at emission. A name ending\n * in `Code` is itself a wire code, resolved two-level through the same\n * namespace and substituted under the plain name.\n */\n readonly params?: Record<string, string>\n /**\n * The local name this project's entry mounts under when the user chose\n * `local`, as `mcp__<alias>__<tool>` in the model's own list. Published on a\n * `profile` conflict even while the choice is still the profile's, so the\n * panel can offer the alias it would use rather than inventing one.\n */\n readonly alias?: string\n /**\n * What the project's policy says about this name. Absent on a `duplicate`,\n * which no choice resolves, and on a host older than this field.\n */\n readonly choice?: ConflictChoice\n}\n\n/**\n * What one live session currently offers the model.\n *\n * Measured from the session's own state, not from the project: two sessions of\n * one project differ as soon as one of them has called a tool, and the panel's\n * promise is to show what *this* session's model sees.\n */\nexport interface SessionTools {\n /** Live agent (session) id this row describes. */\n readonly sessionId: string\n /**\n * Names offered because the durable counters proved them hot, plus the pins;\n * empty in `off`, which offers none of the project's tools.\n */\n readonly baseline: readonly string[]\n /** Names this session activated on demand, oldest first; empty in `off`. */\n readonly activated: readonly OfferedTool[]\n /** Names the task context offered, oldest first; empty in `off`. */\n readonly context: readonly OfferedTool[]\n /**\n * Names mounted for the project but not offered by this plugin, sorted. In\n * `disclosure` these are the names the budget pushed out of the request; in\n * `direct` the list is empty, because nothing is filtered; in `off` it is the\n * whole mounted surface, because a project that is switched off is offered not\n * at all. Its length is exactly the count a panel shows as hidden — and such a\n * panel has to read {@link ToolPolicy.mode} first, since tools another\n * presentation plugin leaves in the request are not this one's offers.\n */\n readonly deferred: readonly string[]\n /** Tools mounted for the project in total. */\n readonly mounted: number\n /** Serialized size of the mounted surface, in characters. */\n readonly surfaceChars: number\n /**\n * Serialized size of the offered set — {@link SessionTools.baseline} plus the\n * `activated` and `context` names — in characters. Absent from a host that\n * does not split the surface, and then a panel prints no request estimate\n * rather than inventing one.\n */\n readonly visibleChars?: number\n /**\n * Serialized size of {@link SessionTools.deferred}, in characters: exactly the\n * part of the mounted surface this plugin leaves out of the request. `0` when\n * nothing is deferred, so a panel that found this field may divide it by four\n * for a token estimate.\n */\n readonly deferredChars?: number\n /**\n * Configured deferral budget in characters. `0` means there is no threshold at\n * all: every surface counts as over budget, so tools are deferred however small\n * the project is. Read {@link SessionTools.deferring} rather than comparing this\n * with {@link SessionTools.surfaceChars} — the host owns the rule.\n */\n readonly budgetChars: number\n /**\n * `true` while the surface is over the budget, so tools really are deferred.\n * Only `disclosure` can defer: `direct` filters nothing and `off` offers\n * nothing, so both report `false` however large the mounted surface is.\n */\n readonly deferring: boolean\n}\n\n/** How one project's MCP tools are offered to the model. */\nexport type ToolMode =\n /** Offer the baseline and the on-demand tiers (the shipped behaviour). */\n | 'disclosure'\n /** Never defer: every mounted tool is listed in every request. */\n | 'direct'\n /** Do not offer this project's MCP tools at all. */\n | 'off'\n\n/**\n * How one `serverName` a project shares with a live profile instance is shown.\n *\n * The profile's instance owns the name in every scope, so the two declarations\n * cannot both mount under it. `profile` keeps the profile's tools exactly as\n * they are and leaves the project's entry unmounted; `local` mounts the\n * project's entry under a local namespace (see `src/naming.ts`) so both toolsets\n * reach the model — the only difference being the names they carry; `native`\n * mounts the project's entry under the name it declares, which is the nearer\n * declaration in this project's own sessions and so shadows the profile's tools\n * of that name there, while every other project keeps seeing the profile's.\n */\nexport type ConflictChoice =\n /** The profile instance keeps the name; the project entry does not mount. */\n | 'profile'\n /** The project entry mounts under its local alias, next to the profile's. */\n | 'local'\n /** The project entry mounts under the declared name, shadowing the profile's in this project. */\n | 'native'\n\n/**\n * One project's tool policy.\n *\n * The mode decides whether tools are deferred, the pins are the names the user\n * insists on — a pinned tool is offered from the first step of every request, is\n * never dropped by idle pruning or by a compaction, and is not counted against\n * the deferral budget's reading of what is hidden — and the aliases remember, per\n * conflicting `serverName`, which of the two declarations the user chose to see.\n */\nexport interface ToolPolicy {\n /** Mode in force. */\n readonly mode: ToolMode\n /**\n * Public registry names pinned for this project, in the order the user pinned\n * them. A name the project no longer mounts is kept: the declaration may come\n * back, and a pin that silently disappeared would be a surprise.\n */\n readonly pins: readonly string[]\n /**\n * Choice per contested `serverName`. Optional so every fixture, host and\n * stored document written before this field existed keeps meaning exactly\n * what it meant: a name that is absent is one the user never chose about,\n * and the shipped answer is the profile's instance. The store publishes an\n * empty map rather than dropping the field, so a reader may treat `undefined`\n * and `{}` alike.\n */\n readonly aliases?: Readonly<Record<string, ConflictChoice>>\n}\n\n/** The policy every project follows until one is configured. */\nexport const DEFAULT_TOOL_POLICY: ToolPolicy = { mode: 'disclosure', pins: [], aliases: {} }\n\n/**\n * How much one MCP server of one project has been used.\n *\n * Counted on the host from the tool registry's own events, so it is exact rather\n * than sampled, and keyed by project root: sessions come and go, the numbers\n * stay, which is what makes them usable for later decisions about a project.\n */\nexport interface ServerUsage {\n /** Calls dispatched through the registry, successful or not. */\n calls: number\n /** Calls whose result carried an error. */\n errors: number\n /** ISO timestamp of the most recent call. */\n lastUsedAt?: string\n /**\n * Per tool counts, keyed by the tool name as declared by the server, i.e.\n * without the `mcp__<serverName>__` prefix the registry publishes it under.\n */\n tools: Record<string, number>\n /**\n * The same readings split by session, keyed by the session (agent) id the\n * panel already uses everywhere else.\n *\n * Additive since F-34: a document written before this field existed is read as\n * it is — `USAGE_VERSION` does not move, because a reader that meets an unknown\n * version refuses the whole document and every counter would start from zero.\n * Absent means \"counted before the split\", never \"no calls\".\n */\n sessions?: Record<string, SessionUsage>\n}\n\n/**\n * One session's share of a server's counters.\n *\n * A server is mounted for a project and a project's sessions share it, so the\n * project total says what the project used while this says what *this* session\n * did; the two differ exactly when other sessions of the project called the\n * server, which is the case a panel scoped to one session could not show.\n */\nexport interface SessionUsage {\n /** Calls this session dispatched through the registry. */\n calls: number\n /** Of those, the ones whose result carried an error. */\n errors: number\n /** ISO timestamp of this session's most recent call. */\n lastUsedAt?: string\n /** This session's counts, keyed by the tool name as the server declares it. */\n tools: Record<string, number>\n}\n\n/**\n * How serious one plugin event is, as the Logs tab colours it.\n *\n * Four levels, mapped from the lifecycle line the host already writes: `info`\n * for a mount being registered, `up` for one whose tools became visible, `warn`\n * for a stall or a release, `error` for a failed mount and the unmount that\n * follows it. They are the labels the tab draws, not a host severity scale.\n */\nexport type LogLevel =\n /** The instance is being registered (`project-mcp: mounting …`). */\n | 'info'\n /** The instance's tools are visible (`… is up …`). */\n | 'up'\n /** A stall, a repeated pass, or a release the operator did not ask for. */\n | 'warn'\n /** The mount failed, or a failed mount is being torn down. */\n | 'error'\n\n/**\n * One lifecycle event, as the Logs tab lists it.\n *\n * The plugin's own events only — a mount, a start, a stop, a failure — mirroring\n * the lines the host writes to the DSH log, so the two readers see the same\n * facts. Events live in a per-project ring (`src/logs.ts`); the newest ones ride\n * in the snapshot, the rest are paged over the route.\n */\nexport interface LogEvent {\n /** When the event happened, epoch ms. */\n readonly at: number\n /** How serious it is, as the tab colours it. */\n readonly level: LogLevel\n /** Project root the event belongs to; the ring is keyed by it. */\n readonly projectRoot: string\n /**\n * Session the event is attributed to. Set exactly when the lifecycle line it\n * mirrors names one — `mounting`, `is up`, a stall — and absent on a\n * project-level event such as a shared instance's unmount.\n */\n readonly sessionId?: string\n /** `serverName` the event is about; absent for an event with no server. */\n readonly server?: string\n /** One line, without a newline: one event is one row of the tab. */\n readonly message: string\n /**\n * The three facts an error carries — the failure, the endpoint, the declaring\n * document — and no advice: the server row already offers the retry.\n */\n readonly detail?: string\n /**\n * Wire code of {@link LogEvent.message} (F-48), into the `projectMcp.host`\n * namespace. Optional: a host older than the field sends prose only, and the\n * client falls back to {@link LogEvent.message}.\n */\n readonly code?: string\n /** Flat params of {@link LogEvent.code}; numbers are stringified at emission. */\n readonly params?: Record<string, string>\n /** Wire code of {@link LogEvent.detail}, the same additive companion. */\n readonly detailCode?: string\n /** Flat params of {@link LogEvent.detailCode}. */\n readonly detailParams?: Record<string, string>\n}\n\n/** Everything one project contributes to the live runtime. */\nexport interface ProjectSnapshot {\n /** Project root the agents below resolved to. */\n projectRoot: string\n /**\n * Documents this project is configured to read, in priority order — global\n * ones first, then the project's own. Published even when empty, so a panel\n * can tell \"this deployment reads nothing\" from a host that does not report\n * its documents at all. Absent only from a snapshot a host older than this\n * field produced, and then a reader falls back to the shipped names rather\n * than inventing a priority.\n */\n files?: readonly ConfiguredFile[]\n /**\n * The tool policy in force for this project. Absent only from a snapshot a host\n * older than the policy store produced; a reader treats that as the shipped\n * default, {@link DEFAULT_TOOL_POLICY}.\n */\n policy?: ToolPolicy\n /** Live agent (session) ids currently bound to this project. */\n sessionIds: string[]\n /**\n * Merged rows for every declared server, in document order. When sessions\n * disagree about one server, the more actionable state wins, so a mounted or\n * broken server is never hidden behind a session that has not turned yet.\n */\n rows: ServerRow[]\n /** Parse and lifecycle diagnostics, deduplicated across the sessions. */\n issues: SnapshotIssue[]\n /** The same data split per session, in session-registration order. */\n sessions: SessionSnapshot[]\n /**\n * Usage counters keyed by `serverName`, remembered across sessions. Absent\n * while the host half has counted nothing for this project yet.\n */\n usage?: Record<string, ServerUsage>\n /**\n * Another loaded plugin that owns the assembled tool list, when the profile\n * has one. Absent means this plugin is the only owner — a panel that reads no\n * record draws no coexistence notice.\n */\n presentation?: PresentationOwner\n /**\n * Real `serverName` conflicts of this project: a profile-level instance that\n * already owns a name, or one name two project documents declare. The list is\n * always published — an empty one is the honest answer \"no conflicts\", which\n * is what lets a panel report that instead of offering a disabled button.\n */\n conflicts?: readonly ServerConflict[]\n /**\n * The newest events of this project's ring, oldest first, at most the page\n * size (50). Absent for a project that has recorded nothing, so a tab draws\n * its empty state rather than an empty list.\n */\n logs?: readonly LogEvent[]\n /**\n * How many events the project's ring holds right now, `0…200`. Absent exactly\n * when {@link ProjectSnapshot.logs} is: no events, nothing to count.\n */\n logCount?: number\n}\n\n/** Whole-plugin snapshot: one entry per project with live agents. */\nexport interface McpSnapshot {\n /** `true` while the agents service has been observed. */\n ready: boolean\n /** Projects with at least one live agent. */\n projects: ProjectSnapshot[]\n /**\n * Documents this deployment is configured to read, exactly as the config\n * spells them — `local` relative to a project root, `global` relative to\n * `$HOME` (or absolute). Published for the surfaces that must speak about the\n * deployment itself, with no project at hand: the empty state names what would\n * be read instead of a file name baked into the client. Absent from a snapshot\n * a host older than this field produced.\n */\n sources?: { readonly local: readonly string[]; readonly global: readonly string[] }\n /** Absolute paths currently watched for config edits. */\n watchedFiles: string[]\n}\n\n/**\n * One pushed picture: what the status channel sends.\n *\n * The snapshot travels whole rather than as a delta, so a frame that arrives\n * after a gap is still a complete answer — the panel can apply it without\n * asking for anything back. `revision` counts the changes the host has announced\n * and is what a late or repeated frame is judged by.\n */\nexport interface SnapshotChange {\n /** Monotonic change counter, starting at `0` for the picture a stream opens on. */\n revision: number\n /** The whole picture at that revision. */\n snapshot: McpSnapshot\n}\n","/**\n * Session-scoped activation of the MCP tools a project mounts.\n *\n * A project can declare a large MCP surface, and a model request must not carry\n * every tool the project owns. This module keeps the *presentation* list small\n * without touching the registry:\n *\n * - the usage counters seed a **baseline** of tools the project has called — one\n * call is enough ({@link seedFromUsage}) — and they are offered directly from\n * the first step on;\n * - the newest task text ranks the project's mounted tools with BM25, and the\n * best matches are offered through a **sticky window** that holds one offered\n * set across the session's steps ({@link advanceAutoOffer});\n * - the rest are discovered through the `mcp_search_tools` tool this module\n * registers in the agent scope, which **activates** the matches for the next\n * step ({@link activate});\n * - a compaction ends the session's activations that no call backs, while the\n * ones the model really called and the counter baseline stay\n * ({@link onCompaction}); idle pruning ({@link pruneIdle}) stays available\n * through a positive `toolIdleMs`, and the shipped `0` leaves it off, so the\n * compaction boundary is the one place that shrinks the offered set;\n * - the agent's own `system-prompt/assemble` listener puts the active schemas\n * back into the assembled request ({@link withActiveTools}).\n *\n * Everything the registry owns stays untouched: no tool is unregistered and no\n * restriction is installed (`ctx.tools.restrict()` cannot hide a scope-local\n * registration anyway — exactly where mcp-client registers its tools). The\n * listener only *adds* schemas to an assembly it did not author, and it is\n * contained: a failure of this plugin's own work returns the continuation's\n * value unchanged.\n *\n * The module is import-free of `@deepseek-ai/dsh-tools` on purpose: that peer is\n * not installed in every deployment, so the registry, definition and schema\n * surfaces are described by the minimal structural types below.\n *\n * @module dsh-project-mcp/activation\n */\n\nimport { DEFAULT_TOOL_POLICY } from './types.ts'\nimport type { OfferedTool, ServerUsage, SessionTools, ToolPolicy } from './types.ts'\n\n/** `true` while the session may offer MCP tools through search + activation. */\nexport const DEFAULT_ACTIVATION_ENABLED = true\n\n/**\n * Tools seeded into the baseline from the durable counters. A project with a\n * few dozen mounted tools calls more than a handful of them, so the cap sits\n * above the narrow window that used to evict a tool the project really uses.\n */\nexport const DEFAULT_ACTIVATION_SEEDED = 16\n\n/**\n * Calls one tool needs in the counters before it is seeded. One call is enough:\n * a tool the project actually uses enters the durable baseline the first time it\n * is called, so the baseline grows from real usage instead of waiting for the\n * counters to reach an arbitrary threshold.\n */\nexport const DEFAULT_ACTIVATION_MIN_CALLS = 1\n\n/**\n * How long a session-activated tool survives without a call (`0` disables).\n *\n * The shipped `0` keeps a searched tool offered for the rest of the session:\n * dropping it mid-session shrinks the request and rewrites the prompt prefix,\n * which invalidates the provider's prefix cache, so time-based removal stays an\n * explicit opt-in.\n */\nexport const DEFAULT_TOOL_IDLE_MS = 0\n\n/** Matches one `mcp_search_tools` call activates when it omits `limit`. */\nexport const DEFAULT_SEARCH_LIMIT = 8\n\n/** Hard cap on matches one `mcp_search_tools` call may activate. */\nexport const MAX_SEARCH_LIMIT = 50\n\n/**\n * Distinct query words one `mcp_search_tools` call scores at most. A query\n * longer than that is a sentence, and its tail words add noise rather than\n * signal — the first words are the ones the model chose first.\n */\nexport const MAX_SEARCH_TOKENS = 8\n\n/** Registry name of the discovery tool this module registers. */\nexport const SEARCH_TOOL_NAME = 'mcp_search_tools'\n\n/** Empty foreign set: what the containment reads when nothing is wired or foreign. */\nconst NO_FOREIGN: ReadonlySet<string> = new Set<string>()\n\n/**\n * Tools the context-driven tier may offer at once when `activationAutoLimit` is\n * unset; `0` disables the tier.\n */\nexport const DEFAULT_AUTO_ACTIVATION_LIMIT = 12\n\n/** Hard cap on the context-driven tier, however the config asks for more. */\nexport const MAX_AUTO_ACTIVATION_LIMIT = 50\n\n/**\n * Extra user messages a context-driven offer survives after the one that ranked\n * it; `0` keeps only that message. The offering set is recomputed when the task\n * context moves, so this is what holds one tool list across several steps.\n *\n * The shipped window spans a whole session: dropping an offer mid-session\n * rewrites the prompt prefix and invalidates the provider's prefix cache, so the\n * context tier grows and only resets at a compaction.\n */\nexport const DEFAULT_AUTO_ACTIVATION_STICKY_STEPS = 100\n\n/** Hard cap on the sticky window, however the config asks for more. */\nexport const MAX_AUTO_ACTIVATION_STICKY_STEPS = 1000\n\n/**\n * Serialized size of the MCP surface a session may offer directly before this\n * module defers anything, in characters. Roughly four characters per token, so\n * the default is about 10K tokens: below it the request would carry every\n * mounted tool anyway, and rewriting the prompt prefix to hide a few of them\n * buys nothing and costs the model its cache. `0` disables the gate and defers\n * the whole surface however small it is.\n */\nexport const DEFAULT_TOOL_BUDGET_CHARS = 40_000\n\n/** BM25 term-frequency saturation. */\nexport const BM25_K1 = 1.2\n\n/** BM25 document-length normalization. */\nexport const BM25_B = 0.75\n\n/**\n * Weight one tool-name hit carries over the same hit in the description. A name\n * hit is what a tool *is*, so it outranks a description that merely mentions the\n * term — without the weight a name repeated in a short description and a\n * description-only hit score nearly the same.\n */\nexport const BM25_NAME_WEIGHT = 1.5\n\n/**\n * Raw BM25 score a tool needs before the context-driven tier may offer it.\n *\n * The floor is what keeps a tool whose name or description shares one incidental\n * word with the task text out of the offered list. A term that stands out in the\n * corpus is worth roughly 1.4 for its first occurrence, one that is merely\n * frequent is worth under 0.3, and a term every tool shares is worth nothing —\n * so the floor sits above the ambient noise a plural or a common verb produces\n * and below a genuine match. Activation through `mcp_search_tools` stays\n * available for anything the floor rejects, and `activationAutoLimit: 0` turns\n * the tier off outright.\n */\nexport const MIN_AUTO_SCORE = 0.6\n\n/** Maximum task-context characters one advance considers (the newest tail wins). */\nexport const MAX_AUTO_QUERY_CHARS = 2_000\n\n/** Maximum tool names the recent-call history carries between advances. */\nexport const MAX_AUTO_RECENT_CALLS = 16\n\n/**\n * Minimal structural view of one model-facing tool schema.\n *\n * It is the exact element type of `system-prompt/assemble`'s `tools` list and of\n * `ctx.tools.schemas()`, described locally because `@deepseek-ai/dsh-tools` is a\n * peer this plugin does not import.\n */\nexport interface ToolSchemaLike {\n /** Public registry name, eg `mcp__alpha__run`. */\n readonly name: string\n /** Model-facing description. */\n readonly description: string\n /** JSON Schema object arguments. */\n readonly parameters: Record<string, unknown>\n}\n\n/** One text block of the model-facing content vocabulary. */\nexport interface TextBlockLike {\n /** Always `text`; the only block this module renders. */\n readonly type: 'text'\n /** Human-readable text. */\n readonly text: string\n}\n\n/**\n * Minimal structural view of a tool definition as `ctx.tools.register` accepts\n * it. Only the fields this module writes are declared.\n */\nexport interface ToolDefinitionLike {\n /** Registry name presented to the model. */\n readonly name: string\n /** Model-facing description. */\n readonly description: string\n /** JSON Schema object arguments. */\n readonly parameters: Record<string, unknown>\n /** Canonical output contract: a schema to validate and a content renderer. */\n readonly output: {\n /** Enforced JSON Schema of the canonical value `execute` returns. */\n readonly schema: Record<string, unknown>\n /**\n * Project the canonical value onto model-facing content.\n * @param args - parsed call arguments.\n * @param value - the validated canonical value.\n * @returns the content blocks the model sees.\n */\n render(args: unknown, value: unknown): readonly TextBlockLike[]\n }\n /**\n * Run one accepted call.\n * @param args - parsed call arguments.\n * @param context - execution identity; unused here.\n * @returns the canonical value declared by `output.schema`.\n */\n execute(args: unknown, context: unknown): Promise<unknown>\n}\n\n/** One listener as `ctx.on` accepts it (method syntax keeps parameters bivariant). */\nexport type ListenerLike = (...args: never[]) => unknown\n\n/**\n * The agent-scoped context slices this module touches. Described structurally so\n * the wiring is testable without a live harness.\n */\nexport interface ActivationContextLike {\n /**\n * Register an event listener through the scope; the scope owns its disposal.\n * @param name - event name.\n * @param listener - listener called with the event's dispatch arguments.\n * @param options - `prepend` places the listener outermost in a waterfall.\n * @returns the disposer, or anything the runtime returns for one.\n */\n on(name: string, listener: ListenerLike, options?: { prepend?: boolean }): unknown\n /** The tool registry, through the scope so registrations stay scope-local. */\n readonly tools: {\n /**\n * Register a tool in the calling scope.\n * @param definition - schema and execution.\n * @returns the exact disposer that unregisters the tool.\n */\n register(definition: ToolDefinitionLike): () => void\n }\n}\n\n/** The subset of one prompt assembly this module reads and returns. */\nexport interface AssemblyLike {\n /** Model-facing tool schemas, already in canonical order. */\n tools: ToolSchemaLike[]\n}\n\n/** Handler of the `system-prompt/assemble` waterfall this module installs. */\nexport type AssembleListener = (\n assembly: AssemblyLike,\n context: unknown,\n next: () => Promise<AssemblyLike>,\n) => Promise<AssemblyLike>\n\n/**\n * The fields the wiring reads from one appended session event: enough to catch\n * a `compaction/end` and to recover the task text of a committed `user/message`.\n */\nexport interface SessionEventLike {\n /** Session event type, eg `compaction/end`. */\n readonly type?: unknown\n /** Event payload, present on every committed event (`event.data`). */\n readonly data?: unknown\n}\n\n/**\n * One session's activation state.\n *\n * `baseline` is the counter-seeded set and outlives a compaction; `active` holds\n * the names this session activated through search or the context tier, each with\n * the epoch milliseconds of its last touch, and is what idle pruning and\n * compaction trim. `used` records the calls the session made for this plugin's\n * own namespace — the evidence a compaction keeps an activation by, because a\n * tool the model called is one the session really uses. It is cumulative for the\n * session and never bounded, so the compaction boundary shrinks the offers no\n * call backs and never shrinks a used tool again.\n *\n * Every field is read-only because every transition returns a new state.\n */\nexport interface ActivationState {\n /** Public names the durable counters proved hot; always offered. */\n readonly baseline: ReadonlySet<string>\n /** Session-activated public names mapped to their last touch. */\n readonly active: ReadonlyMap<string, number>\n /**\n * `mcp__` names this session called at least once and the durable baseline\n * does not already keep. Read by nothing but {@link onCompaction}, and\n * cumulative for the session: it is deliberately never bounded, so with the\n * shipped `DEFAULT_TOOL_IDLE_MS` of `0` nothing else removes a name and a tool\n * the session used stays offered for the rest of the session, across every\n * further compaction.\n */\n readonly used: ReadonlySet<string>\n}\n\n/**\n * Build one session's state.\n * @param baseline - counter-seeded public names; defaults to none.\n * @returns an empty active set and an empty used record over that baseline.\n */\nexport function createActivationState(baseline: Iterable<string> = []): ActivationState {\n return { baseline: new Set(baseline), active: new Map(), used: new Set() }\n}\n\n/** How {@link seedFromUsage} reads the durable counters. */\nexport interface SeedOptions {\n /** Maximum names seeded; `0` seeds none. */\n readonly count: number\n /** Calls one tool needs before it is seeded. */\n readonly minCalls: number\n}\n\n/**\n * Seed the baseline from a project's durable counters.\n *\n * The counters key tools by the name the server declares them under and servers\n * by `serverName`, so the public registry name is the `mcp__<server>` prefix plus\n * the tool key — the same reconstruction the counter's own attribution relies\n * on. A name the registry had to truncate cannot be reversed this way; such a\n * tool is simply not seeded, which is why the search tool stays the discovery\n * path of record.\n *\n * @param usage - counters of one project, or `undefined` when none were recorded.\n * @param options - seed cap and per-tool minimum.\n * @returns the baseline names, most-called first (name order breaks ties).\n */\nexport function seedFromUsage(\n usage: Record<string, ServerUsage> | undefined,\n options: SeedOptions,\n): Set<string> {\n const baseline = new Set<string>()\n if (usage === undefined || options.count <= 0) return baseline\n const candidates: { name: string; calls: number }[] = []\n for (const [server, serverUsage] of Object.entries(usage)) {\n for (const [tool, calls] of Object.entries(serverUsage.tools)) {\n if (calls < options.minCalls) continue\n candidates.push({ name: `mcp__${server}__${tool}`, calls })\n }\n }\n candidates.sort((left, right) => right.calls - left.calls || compareNames(left.name, right.name))\n for (const candidate of candidates.slice(0, options.count)) baseline.add(candidate.name)\n return baseline\n}\n\n/**\n * Activate names for this session, idempotently.\n *\n * A baseline name is skipped: it is already offered, so tracking it in the\n * session set would only make a compaction look like it changed something.\n *\n * @param state - activation state before the activation.\n * @param names - public names activated (already filtered to this plugin's mounts).\n * @param at - epoch milliseconds of the activation.\n * @returns the updated state, or the input when nothing changed.\n */\nexport function activate(\n state: ActivationState,\n names: Iterable<string>,\n at: number,\n): ActivationState {\n let active: Map<string, number> | undefined\n for (const name of names) {\n if (state.baseline.has(name)) continue\n if (state.active.get(name) === at) continue\n active ??= new Map(state.active)\n active.set(name, at)\n }\n return active === undefined ? state : { baseline: state.baseline, active, used: state.used }\n}\n\n/**\n * Record a call — the freshness of a session-activated tool and the evidence a\n * compaction keeps it by.\n *\n * `active` is refreshed exactly as before: a call is what keeps a\n * session-activated tool offered. `used` records the call itself, but only for\n * this plugin's own namespace: the core tools (`read`, `bash`, …) ride the same\n * `tools/result` hook, and they are no part of a session's MCP activation state.\n * A baseline name is not recorded either — the durable baseline already keeps it\n * offered, so recording the call would only make a compaction look like it\n * changed something.\n *\n * @param state - activation state before the call.\n * @param name - public name of the called tool.\n * @param at - epoch milliseconds of the call.\n * @returns the updated state, or the input when nothing changed.\n */\nexport function noteUse(state: ActivationState, name: string, at: number): ActivationState {\n const previous = state.active.get(name)\n const refresh = previous !== undefined && previous !== at\n // `used` post-dates the interface: a state an embedder built before the field\n // existed reads as a session that has used nothing, so the read is optional\n // and the write coalesces an empty record instead of throwing.\n const already = state.used?.has(name) === true\n const record = name.startsWith('mcp__') && !state.baseline.has(name) && !already\n if (!refresh && !record) return state\n const active = refresh ? new Map(state.active) : undefined\n active?.set(name, at)\n const used = record ? new Set(state.used ?? []) : undefined\n used?.add(name)\n return {\n baseline: state.baseline,\n active: active ?? state.active,\n used: used ?? state.used ?? new Set(),\n }\n}\n\n/**\n * Drop the session-activated tools that have not been called for `idleMs`.\n * The baseline is never pruned: it comes from the durable counters, not from the\n * session. `idleMs <= 0` disables pruning.\n *\n * A positive `idleMs` is an explicit opt-in to *forgetting*: an evicted name\n * leaves the used record with the offer it was about, so the sweep is final —\n * a later compaction cannot read the call back and resurrect what time already\n * dropped. A name the model needs again is activated again through search. The\n * names still inside the window keep their record, and a sweep that evicts\n * nothing returns its input.\n *\n * @param state - activation state at `now`.\n * @param now - epoch milliseconds of the sweep.\n * @param idleMs - age at which a tool falls out.\n * @returns the updated state, or the input when nothing was stale.\n */\nexport function pruneIdle(state: ActivationState, now: number, idleMs: number): ActivationState {\n if (idleMs <= 0 || state.active.size === 0) return state\n let active: Map<string, number> | undefined\n let used: Set<string> | undefined\n for (const [name, at] of state.active) {\n if (now - at < idleMs) continue\n active ??= new Map(state.active)\n active.delete(name)\n // `used` post-dates the interface, so a legacy state simply has no record to\n // forget; a record that is there is copied before it is dropped.\n if (state.used?.has(name) !== true) continue\n used ??= new Set(state.used ?? [])\n used.delete(name)\n }\n return active === undefined\n ? state\n : { baseline: state.baseline, active, used: used ?? state.used ?? new Set() }\n}\n\n/**\n * End the session's activations that no call backs, at the compaction boundary.\n *\n * A compaction rewrites the conversation, so the provider's prompt prefix is\n * recomputed anyway: this is the one boundary where dropping a tool costs no\n * cache, which is why idle time is off by default and why this is the only place\n * the offered set shrinks. Only the part the session never used goes — an offer\n * from a context match or a search that the model did not act on. A tool this\n * session did call is one it really uses, so it stays active, stamped with its\n * last touch; evicting it would charge a re-discovery step for a tool the\n * session demonstrably needs. A used name that was never activated falls back to\n * the compaction's own clock. The counter baseline is never pruned.\n *\n * The used record is cumulative for the session and deliberately never bounded:\n * with the shipped `DEFAULT_TOOL_IDLE_MS` of `0` nothing else removes a name, so\n * a tool the session used stays offered for the rest of the session, across every\n * further compaction. This boundary shrinks the offers no call backs — it never\n * shrinks one the session used again.\n *\n * @param state - activation state before the compaction.\n * @param at - epoch milliseconds of the compaction.\n * @returns the updated state, or the input when nothing was active or used, or\n * when the rebuild is equivalent to what is already there — a caller compares\n * by identity to tell a real change from a boundary that changed nothing.\n */\nexport function onCompaction(state: ActivationState, at: number): ActivationState {\n // `used` post-dates the interface: a state an embedder built before the field\n // existed reads as a session that has used nothing.\n const used = state.used ?? new Set<string>()\n if (state.active.size === 0 && used.size === 0) return state\n const active = new Map<string, number>()\n for (const name of used) active.set(name, state.active.get(name) ?? at)\n // A second compaction with no new call rebuilds exactly the map already there,\n // and an equal-but-different object would read as a change to every caller\n // that compares by identity. Same names and same stamps: the input comes back.\n if (active.size === state.active.size) {\n let equivalent = true\n for (const [name, stamp] of active) {\n if (state.active.get(name) !== stamp) {\n equivalent = false\n break\n }\n }\n if (equivalent) return state\n }\n return { baseline: state.baseline, active, used: state.used ?? new Set() }\n}\n\n/**\n * Every name this session currently offers: the baseline plus the session's own\n * activations.\n * @param state - current activation state.\n * @returns the union; the baseline itself when nothing is session-activated.\n */\nexport function presentedNames(state: ActivationState): ReadonlySet<string> {\n if (state.active.size === 0) return state.baseline\n return new Set([...state.baseline, ...state.active.keys()])\n}\n\n/**\n * Serialized size of a tool surface, in characters.\n *\n * Counts what a request actually carries per schema — name, description and the\n * JSON form of the parameters — so the number is comparable with\n * {@link DEFAULT_TOOL_BUDGET_CHARS}. Total: a `parameters` value that cannot be\n * serialized (a cycle) contributes nothing instead of throwing.\n *\n * @param schemas - the schemas a session may offer.\n * @returns the summed character count.\n */\nexport function surfaceChars(schemas: readonly ToolSchemaLike[]): number {\n let total = 0\n for (const schema of schemas) total += schemaChars(schema)\n return total\n}\n\n/**\n * Serialized size of one tool schema, in characters: the same measurement\n * {@link surfaceChars} sums, so a caller that splits a surface into two halves\n * counts each half by one rule.\n *\n * Exported for the same reason {@link surfaceChars} is: the on-demand tool\n * detail route answers the *size of one definition* as a host measurement, and\n * a reason line that recomputed it would risk a different number than the\n * budget decision it explains.\n *\n * @param schema - one schema a session may offer.\n * @returns its character count.\n */\nexport function schemaChars(schema: ToolSchemaLike): number {\n return schema.name.length + schema.description.length + serializedLength(schema.parameters)\n}\n\n/**\n * Whether one mounted surface is over the deferral budget.\n *\n * This is exactly the gate {@link installActivation} applies before it defers\n * anything, so a reader that reports the decision cannot drift from the\n * listener that makes it: a surface that fits the budget exactly is carried\n * whole, and a budget of `0` disables the comparison so every surface is over\n * it.\n *\n * @param chars - serialized surface size, as {@link surfaceChars} measures it.\n * @param budgetChars - configured budget in characters.\n * @returns `true` when the surface must be handed over on demand.\n */\nexport function overToolBudget(chars: number, budgetChars: number): boolean {\n return budgetChars <= 0 || chars > budgetChars\n}\n\n/**\n * The model-facing schema of a definition this module built itself, so its own\n * tool can be offered from the assembly listener rather than through the\n * registry alone.\n *\n * @param definition - a registry-ready tool definition.\n * @returns the three fields an assembly carries for it.\n */\nfunction schemaOf(definition: ToolDefinitionLike): ToolSchemaLike {\n return {\n name: definition.name,\n description: definition.description,\n parameters: definition.parameters,\n }\n}\n\n/** `JSON.stringify` length of one value, or `0` when it cannot be serialized. */\nfunction serializedLength(value: unknown): number {\n try {\n return JSON.stringify(value)?.length ?? 0\n } catch {\n return 0\n }\n}\n\n/**\n * Merge the session's active schemas into an already assembled tool list.\n *\n * Total and side-effect free: it copies the base list, never removes or reorders\n * an entry that is already there, and only appends an active schema that the\n * base does not already carry and that `available` actually publishes (a stale\n * baseline name of a server that is no longer mounted is silently skipped).\n * Missing schemas are inserted at their sorted position, so with the canonical\n * (lexicographic) base order DSH produces the result stays sorted; a deployment\n * with a custom `toolOrder` keeps its existing entries exactly where they were.\n *\n * @param baseTools - the assembly's tool list as the inner listeners left it.\n * @param available - live schemas this plugin may offer for the session.\n * @param activeNames - baseline plus session-activated public names.\n * @returns a new list; equal input yields an equal list.\n */\nexport function withActiveTools(\n baseTools: readonly ToolSchemaLike[],\n available: readonly ToolSchemaLike[],\n activeNames: ReadonlySet<string>,\n): ToolSchemaLike[] {\n const result = [...baseTools]\n if (activeNames.size === 0 || available.length === 0) return result\n const present = new Set(result.map((tool) => tool.name))\n const byName = new Map<string, ToolSchemaLike>()\n for (const tool of available) {\n if (!byName.has(tool.name)) byName.set(tool.name, tool)\n }\n const missing: ToolSchemaLike[] = []\n for (const name of activeNames) {\n if (present.has(name)) continue\n const tool = byName.get(name)\n if (tool === undefined) continue\n present.add(name)\n missing.push(tool)\n }\n missing.sort((left, right) => compareNames(left.name, right.name))\n for (const tool of missing) {\n const index = result.findIndex((existing) => compareNames(existing.name, tool.name) > 0)\n if (index === -1) result.push(tool)\n else result.splice(index, 0, tool)\n }\n return result\n}\n\n/**\n * The task context one auto-offer decision reads: the newest user-role text the\n * session committed, plus the tools it called since the last decision.\n *\n * A called name is context, never activation. Only names inside `available`\n * — the tools this plugin mounted for the session — can enter the window, so a\n * call to a profile-level or other-project tool cannot smuggle a foreign schema\n * into the request.\n */\nexport interface AutoOfferInput {\n /** Newest committed user message text; `''` when the session has none yet. */\n readonly userText: string\n /**\n * Tool names called since the last decision, call order preserved. Repeating\n * the list is safe: a name already inside the window keeps its stamp.\n */\n readonly recentCalls?: readonly string[]\n}\n\n/** How the context-driven tier ranks, caps, and holds one decision. */\nexport interface AutoOfferOptions {\n /** Maximum names one decision may offer; `0` disables the tier. */\n readonly limit?: number\n /**\n * Extra user messages a name survives after the one that ranked it. One\n * decision runs per new task text, so this is the sticky window width.\n */\n readonly stickySteps?: number\n /** Raw BM25 score a tool needs before it may be offered. */\n readonly minScore?: number\n}\n\n/**\n * The context-driven tier's state: a sticky window over the BM25 ranking of the\n * session's available tools.\n *\n * `window` maps a name to the decision that put it there, so a later decision\n * can count how long the name has been offered without renumbering anything.\n * {@link autoPresentedNames} reads the offered set back out. The state is\n * immutable; a decision that changes nothing returns its input object.\n */\nexport interface AutoOfferState {\n /** Name -> decision stamp of every name still inside the sticky window. */\n readonly window: ReadonlyMap<string, number>\n}\n\n/**\n * One empty context-driven state.\n * @returns a state whose window is empty.\n */\nexport function createAutoOfferState(): AutoOfferState {\n return { window: new Map() }\n}\n\n/**\n * Split free text into lowercase search tokens.\n *\n * Separators, punctuation and case boundaries all delimit a token, so `runSQL`,\n * `run_sql`, `run-sql` and `mcp__alpha__run` all yield `run`/`sql`/`mcp`/\n * `alpha` as separate terms instead of one opaque blob. A token must hold at\n * least one letter or digit, which drops the punctuation-only pieces.\n *\n * @param text - raw name, description, or task text.\n * @returns the tokens in source order, duplicates kept (BM25 needs term counts).\n */\nexport function tokenize(text: string): string[] {\n const tokens: string[] = []\n for (const chunk of text.split(/[^\\p{L}\\p{N}]+/u)) {\n if (chunk === '') continue\n for (const piece of chunk.split(/(?<=\\p{Ll})(?=\\p{Lu})|(?<=\\p{Lu})(?=\\p{Lu}\\p{Ll})/u)) {\n if (piece === '') continue\n const token = piece.toLowerCase()\n if (/[\\p{L}\\p{N}]/u.test(token)) tokens.push(token)\n }\n }\n return tokens\n}\n\n/**\n * Rank the available schemas against one task text with BM25.\n *\n * The corpus is each tool's name plus its description; the query is the task\n * text tokenized the same way. The name is repeated so a name hit outweighs a\n * description hit, and the name breaks score ties, so one corpus and query\n * always produce the same list. Candidates below `minScore` are dropped.\n *\n * @param schemas - live schemas this plugin may offer for the session.\n * @param query - task text to rank against.\n * @param limit - maximum names to return.\n * @param minScore - raw BM25 score a candidate needs.\n * @returns the top names, best first, deterministically ordered.\n */\nexport function rankToolsByQuery(\n schemas: readonly ToolSchemaLike[],\n query: string,\n limit: number,\n minScore: number,\n): string[] {\n const queryTokens = [...new Set(tokenize(query))]\n if (queryTokens.length === 0 || limit <= 0 || schemas.length === 0) return []\n\n const documents: {\n tool: ToolSchemaLike\n nameTokens: string[]\n descriptionTokens: string[]\n }[] = []\n const nameFrequency = new Map<string, number>()\n const descriptionFrequency = new Map<string, number>()\n let nameLength = 0\n let descriptionLength = 0\n for (const tool of schemas) {\n const description = typeof tool.description === 'string' ? tool.description : ''\n const nameTokens = tokenize(tool.name)\n const descriptionTokens = tokenize(description)\n documents.push({ tool, nameTokens, descriptionTokens })\n nameLength += nameTokens.length\n descriptionLength += descriptionTokens.length\n for (const token of new Set(nameTokens)) nameFrequency.set(token, (nameFrequency.get(token) ?? 0) + 1)\n for (const token of new Set(descriptionTokens)) {\n descriptionFrequency.set(token, (descriptionFrequency.get(token) ?? 0) + 1)\n }\n }\n const averageNameLength = Math.max(nameLength / documents.length, 1)\n const averageDescriptionLength = Math.max(descriptionLength / documents.length, 1)\n\n /** One field's BM25 contribution for one query term, matching the term count. */\n const fieldScore = (\n frequency: number,\n tokens: number,\n documentFrequency: number,\n averageLength: number,\n ): number => {\n const inverse = Math.log(\n 1 + (documents.length - documentFrequency + 0.5) / (documentFrequency + 0.5),\n )\n const saturation =\n (frequency * (BM25_K1 + 1)) /\n (frequency + BM25_K1 * (1 - BM25_B + (BM25_B * tokens) / averageLength))\n return inverse * saturation\n }\n\n const ranked: { name: string; score: number }[] = []\n for (const document of documents) {\n const nameCounts = countTokens(document.nameTokens)\n const descriptionCounts = countTokens(document.descriptionTokens)\n let score = 0\n for (const token of queryTokens) {\n if (nameCounts.has(token)) {\n score +=\n BM25_NAME_WEIGHT *\n fieldScore(\n nameCounts.get(token) ?? 0,\n document.nameTokens.length,\n nameFrequency.get(token) ?? 0,\n averageNameLength,\n )\n }\n if (descriptionCounts.has(token)) {\n score += fieldScore(\n descriptionCounts.get(token) ?? 0,\n document.descriptionTokens.length,\n descriptionFrequency.get(token) ?? 0,\n averageDescriptionLength,\n )\n }\n }\n if (score < minScore) continue\n ranked.push({ name: document.tool.name, score })\n }\n ranked.sort((left, right) => right.score - left.score || compareNames(left.name, right.name))\n return ranked.slice(0, limit).map((candidate) => candidate.name)\n}\n\n/** Term counts of one field, keyed by token. */\nfunction countTokens(tokens: readonly string[]): Map<string, number> {\n const counts = new Map<string, number>()\n for (const token of tokens) counts.set(token, (counts.get(token) ?? 0) + 1)\n return counts\n}\n\n/**\n * Read the newest user-role text out of one committed session event.\n *\n * Only text blocks enter the task context: an image or file block carries no\n * words to rank against, and an event that is not a `user/message` is not task\n * text at all.\n *\n * Neither is a synthetic `user/message`. The same event type carries every\n * plugin-authored context injection — runtime context snapshots, agent\n * instructions, skill catalogues, cron notices — and they are distinguished\n * only by `source.kind` (`plugin` against a human prompt's `user`). Ranking a\n * tool offer against a context snapshot rather than against the task is worse\n * than ranking against nothing, so only a `user` source is accepted. A\n * deployment that injects its own task text as a `plugin` message therefore\n * ranks on the last human turn instead of that injection.\n *\n * @param event - one event as the `session/event` listener receives it.\n * @returns the message text, or `''` when this event carries none.\n */\nexport function readUserMessage(event: SessionEventLike): string {\n if (event?.type !== 'user/message' || !isRecord(event.data)) return ''\n const source = event.data.source\n if (!isRecord(source) || source.kind !== 'user') return ''\n const content = event.data.content\n if (!Array.isArray(content)) return ''\n const parts: string[] = []\n for (const block of content) {\n if (!isRecord(block) || block.type !== 'text') continue\n if (typeof block.text === 'string') parts.push(block.text)\n }\n return parts.join('\\n').trim()\n}\n\n/**\n * Reset the context-driven tier: a compaction rewrote the conversation the\n * offers belonged to, so nothing sticky survives it.\n *\n * @param state - state before the compaction.\n * @returns an empty state, or the input when it was already empty.\n */\nexport function resetAutoOffer(state: AutoOfferState): AutoOfferState {\n if (state.window.size === 0) return state\n return createAutoOfferState()\n}\n\n/**\n * Bound one task text to the newest {@link MAX_AUTO_QUERY_CHARS} characters.\n *\n * The tail is the part that matters — a long message states its request last —\n * and the bound keeps one very long paste from turning every later ranking pass\n * into a scan of the whole message.\n *\n * @param text - committed user message text.\n * @returns the text unchanged when it is already short enough.\n */\nexport function boundTaskText(text: string): string {\n return text.length <= MAX_AUTO_QUERY_CHARS ? text : text.slice(text.length - MAX_AUTO_QUERY_CHARS)\n}\n\n/**\n * Advance the context-driven tier by one input: recompute the BM25 ranking and\n * merge it into the sticky window.\n *\n * A name survives for the advance that offered it plus `stickySteps` later\n * advances, instead of falling out the moment its score dips — that is what\n * keeps one tool list across the steps of a turn. An input that offers nothing\n * clears the window: there is nothing to be sticky about. Nothing here reads a\n * clock; the caller decides what one advance is, so the model stays\n * deterministic and testable.\n *\n * @param previous - state before this input.\n * @param input - the session's newest task text and recent calls.\n * @param available - live schemas this plugin may offer for the session.\n * @param options - ranking and window configuration.\n * @returns the next state, or the input state when nothing changed.\n */\nexport function advanceAutoOffer(\n previous: AutoOfferState,\n input: AutoOfferInput,\n available: readonly ToolSchemaLike[],\n options: AutoOfferOptions = {},\n): AutoOfferState {\n const limit = autoOfferLimit(options.limit)\n const stickySteps = autoOfferStickySteps(options.stickySteps)\n const ranked = rankToolsByQuery(available, input.userText, limit, options.minScore ?? MIN_AUTO_SCORE)\n const previousAdvance = currentAdvance(previous)\n\n // A called name is context, never activation: only a tool this plugin\n // mounted for the session may enter the window, so a call to a profile-level\n // or other-project tool cannot smuggle a foreign schema into the request.\n const mounted = new Set(available.map((schema) => schema.name))\n const calls: string[] = []\n for (const name of input.recentCalls ?? []) {\n if (name !== '' && mounted.has(name) && !calls.includes(name)) calls.push(name)\n }\n if (ranked.length === 0 && calls.length === 0) {\n const empty = createAutoOfferState()\n return sameAutoOffer(previous, empty) ? previous : empty\n }\n\n const advance = previousAdvance + 1\n // The stamp of the oldest advance still offered. A name entered at advance\n // `E` is offered at `E` itself plus the next `stickySteps` advances, so this\n // advance still shows `advance - stickySteps` and drops anything older.\n const firstKeptAdvance = Math.max(advance - stickySteps, 0)\n const window = new Map<string, number>()\n for (const [name, stamp] of previous.window) {\n if (name === AUTO_ADVANCE_KEY || stamp < firstKeptAdvance) continue\n window.set(name, stamp)\n }\n // A name the window already carries keeps the stamp its offer was made with,\n // so being called never shortens an offer; a fresh one is stamped current.\n for (const name of ranked) window.set(name, advance)\n for (const name of calls) {\n if (!window.has(name)) window.set(name, advance)\n }\n window.set(AUTO_ADVANCE_KEY, advance)\n\n const next: AutoOfferState = { window }\n return sameAutoOffer(previous, next) ? previous : next\n}\n\n\n\n/**\n * Reserved window key that records the advance the state has reached. A real\n * tool name can never collide with it: registry names are non-empty, and this\n * key is empty. {@link autoPresentedNames} skips it.\n */\nconst AUTO_ADVANCE_KEY = ''\n\n/** The advance one state has reached; `0` for a state that never advanced. */\nfunction currentAdvance(state: AutoOfferState): number {\n return state.window.get(AUTO_ADVANCE_KEY) ?? 0\n}\n\n/**\n * Every name the context-driven tier currently offers.\n * @param state - current context-driven state.\n * @returns the offered names, in code-unit order.\n */\nexport function autoPresentedNames(state: AutoOfferState): ReadonlySet<string> {\n const names = new Set<string>()\n for (const name of state.window.keys()) {\n if (name !== AUTO_ADVANCE_KEY) names.add(name)\n }\n return new Set([...names].sort(compareNames))\n}\n\n/**\n * Every name the context-driven tier currently offers, oldest offer first.\n *\n * The window stamps are advances, not clock readings: this state deliberately\n * holds no wall-clock time, so the order is recency in *decisions*. A caller\n * that needs a timestamp cannot read one from here.\n *\n * @param state - current context-driven state.\n * @returns the offered names, ordered by the advance that offered each.\n */\nexport function autoOffers(state: AutoOfferState): readonly string[] {\n const entries: { name: string; advance: number }[] = []\n for (const [name, advance] of state.window) {\n if (name === AUTO_ADVANCE_KEY) continue\n entries.push({ name, advance })\n }\n entries.sort((left, right) => left.advance - right.advance || compareNames(left.name, right.name))\n return entries.map((entry) => entry.name)\n}\n\n/**\n * Whether two context-driven states offer the same names.\n *\n * Only the presented names are compared, never the advance stamp and never the\n * per-name window stamps, so an advance that changes nothing hands back the\n * previous state without ticking the advance counter: the sticky window ages by\n * changes of the offered set, not by input count. This was reviewed as a\n * possible stickiness off-by-one and cannot produce a wrong offered set — a\n * stall can only hold names the ranking has just chosen again, and it ends at\n * the first advance whose set differs — so do not re-chase an age here before\n * reading `advanceAutoOffer`.\n */\nfunction sameAutoOffer(left: AutoOfferState, right: AutoOfferState): boolean {\n const leftNames = autoPresentedNames(left)\n const rightNames = autoPresentedNames(right)\n if (leftNames.size !== rightNames.size) return false\n for (const name of leftNames) {\n if (!rightNames.has(name)) return false\n }\n return true\n}\n\n/**\n * Read the offered-set cap, clamped to the supported range.\n * @param value - configured cap, or `undefined` for the shipped default.\n * @returns the effective cap; `0` disables the context-driven tier.\n */\nexport function autoOfferLimit(value: number | undefined): number {\n return Math.min(Math.max(value ?? DEFAULT_AUTO_ACTIVATION_LIMIT, 0), MAX_AUTO_ACTIVATION_LIMIT)\n}\n\n/**\n * Read the sticky-window configuration, clamped to the supported range.\n * @param value - configured extra advances, or `undefined` for the shipped default.\n * @returns the effective extra advances; `0` keeps only the current advance.\n */\nexport function autoOfferStickySteps(value: number | undefined): number {\n return Math.min(\n Math.max(value ?? DEFAULT_AUTO_ACTIVATION_STICKY_STEPS, 0),\n MAX_AUTO_ACTIVATION_STICKY_STEPS,\n )\n}\n\n/**\n * One live session's presentation inputs, read where the session's state lives.\n *\n * Every field is a snapshot-time read: `mounted` is the registry probe the\n * activation wiring itself consumes, and both states are the session's own, so\n * a caller that derives a row again after an activation sees it — nothing here\n * is a copy a later path updates.\n */\nexport interface SessionToolInput {\n /** Live agent (session) id the row describes. */\n readonly sessionId: string\n /** Schemas this plugin mounted for the session, as the registry lists them now. */\n readonly mounted: readonly ToolSchemaLike[]\n /** Activation state of the session; absent before its first seed. */\n readonly activation: ActivationState | undefined\n /** Context-driven window of the session; absent before its first advance. */\n readonly auto: AutoOfferState | undefined\n /** `false` when activation is off, so every mounted tool stays in the request. */\n readonly activationEnabled: boolean\n /** Deferral budget in characters; defaults to {@link DEFAULT_TOOL_BUDGET_CHARS}. */\n readonly budgetChars?: number\n /**\n * Tool policy of the session's project; absent means the shipped default,\n * {@link DEFAULT_TOOL_POLICY}. Read at call time like every other field here,\n * so the row follows a pin or a mode change as soon as it is stored.\n */\n readonly policy?: ToolPolicy\n /**\n * Step each session activation was recorded on, keyed by public name, and the\n * step this row is being read on. Both are optional and independent: `steps`\n * stamps the `activated` tier with the step its offer happened on, while\n * `step` stamps the context tier with the step the request belongs to. Absent\n * means the caller counts no steps, and then no tier carries a number — the\n * panel draws no step tag rather than a zero.\n */\n readonly steps?: ReadonlyMap<string, number>\n /** Step this row is read on; see {@link SessionToolInput.steps}. */\n readonly step?: number\n}\n\n/**\n * Derive what one session offers the model right now from its live state.\n *\n * The row is a *measurement*, not a decision: `mounted` counts the schemas the\n * caller probed, and `deferred` is exactly the part of that surface the request\n * does not carry, so `deferred.length` is the panel's \"hidden\" number and the\n * tier lists name why the rest is there. Nothing is cached: the same inputs\n * read after an activation list it.\n *\n * Names of tiers that the session no longer mounts are dropped, because the\n * row describes what is offered, not what once was. The context tier carries no\n * `at`: the live window stamps an advance, not a wall-clock time.\n *\n * The project's policy is read here too, and it decides all three fields. In\n * `disclosure` the row offers the counter baseline and the pins and hides the\n * part of the mounted surface the budget pushed out of the request. `direct`\n * filters nothing, so it hides nothing: `deferring` is `false` and `deferred` is\n * empty however large the surface is. `off` offers none of the project's tools,\n * so every tier of this row is empty and the whole mounted surface is `deferred`\n * — the row reports what *this* plugin contributes, and a project the user\n * switched off contributes nothing, whether or not another presentation plugin\n * leaves the tools visible to the model. Pinned names join the counter baseline,\n * so in `disclosure` and `direct` they are offered from the first step of every\n * request and are never counted as hidden, whatever the counters and the budget\n * say.\n *\n * @param input - live mount, activation, context, config and policy of one session.\n * @returns the presentation row, or `undefined` when the session mounts no tool\n * (a session the host has not turned has nothing to report, and an empty row\n * would claim it offers nothing rather than that its surface is absent).\n */\nexport function toolsFor(input: SessionToolInput): SessionTools | undefined {\n const mounted = input.mounted\n if (mounted.length === 0) return undefined\n const mountedNames = new Set(mounted.map((schema) => schema.name))\n const chars = surfaceChars(mounted)\n const budgetChars = input.budgetChars ?? DEFAULT_TOOL_BUDGET_CHARS\n const policy = input.policy ?? DEFAULT_TOOL_POLICY\n // Nothing is hidden while the surface fits: the activation listener leaves the\n // assembly untouched then, so a name a tier would have offered is in the\n // request anyway. Only a surface the gate defers can hide anything — and only\n // `disclosure` defers by size at all: `direct` filters nothing and `off`\n // offers nothing.\n const deferring =\n policy.mode === 'disclosure' && input.activationEnabled && overToolBudget(chars, budgetChars)\n // `off` offers none of the project's tools, so no tier of this row offers one\n // either. The pins stay in the policy and the session keeps its activations —\n // the mode is read again on the next assembly, so switching back finds them —\n // but a row that promises nothing is what makes the whole mounted surface\n // `deferred` below.\n const offersNothing = policy.mode === 'off'\n\n // A pin is the user's own always-offered name, so it belongs to the baseline\n // next to the counter-seeded ones. A pinned name the project no longer mounts\n // is not part of this row — but stays pinned in the policy store, so the\n // declaration coming back finds it again.\n const baselineNames = new Set<string>(input.activation?.baseline ?? [])\n for (const pin of policy.pins) baselineNames.add(pin)\n const baseline = offersNothing\n ? []\n : [...baselineNames].filter((name) => mountedNames.has(name)).sort(compareNames)\n // The step an activation was recorded on, when the caller counted one; `0`\n // (or no map at all) is \"this host does not count steps\", and a tier must then\n // carry no number rather than a zero a panel would draw as a step tag.\n const stepOf = (name: string): number | undefined => {\n const step = input.steps?.get(name)\n return step === undefined || step <= 0 ? undefined : step\n }\n const activated: OfferedTool[] = offersNothing\n ? []\n : [...(input.activation?.active ?? [])]\n .filter(([name]) => mountedNames.has(name))\n .sort(\n ([leftName, leftAt], [rightName, rightAt]) =>\n leftAt - rightAt || compareNames(leftName, rightName),\n )\n .map(([name, at]): OfferedTool => {\n const step = stepOf(name)\n return { name, via: 'session', at, ...(step === undefined ? {} : { step }) }\n })\n // The context tier is a live window, not a record of offers made: the stamp it\n // carries is the step this row is read on, which is the step the request it\n // describes belongs to. A caller that counts no steps leaves it absent.\n const context: OfferedTool[] = offersNothing\n ? []\n : (input.auto === undefined ? [] : autoOffers(input.auto))\n .filter((name) => mountedNames.has(name))\n .map((name): OfferedTool => ({\n name,\n via: 'context',\n ...(input.step === undefined ? {} : { step: input.step }),\n }))\n\n const offered = new Set<string>(baseline)\n for (const tool of activated) offered.add(tool.name)\n for (const tool of context) offered.add(tool.name)\n\n // `off` promises nothing, so the whole mounted surface is what this plugin\n // does not offer; `direct` filters nothing, so it hides nothing; only\n // `disclosure` over its budget hides the difference between the two.\n const deferred =\n offersNothing\n ? [...mountedNames].sort(compareNames)\n : deferring\n ? [...mountedNames].filter((name) => !offered.has(name)).sort(compareNames)\n : []\n\n // The request's own weight, split the way the request is: exactly the names in\n // `deferred` are the ones the assembly leaves out, so a surface that fits the\n // budget carries all of it and defers nothing, and what hiding saved is\n // `surfaceChars - visibleChars`. Both halves are measured with\n // {@link surfaceChars}, the same rule the budget gate uses, so the numbers\n // cannot drift from the decision.\n const deferredNames = new Set(deferred)\n let visibleChars = 0\n let deferredChars = 0\n for (const schema of mounted) {\n if (deferredNames.has(schema.name)) deferredChars += schemaChars(schema)\n else visibleChars += schemaChars(schema)\n }\n\n return {\n sessionId: input.sessionId,\n baseline,\n activated,\n context,\n deferred,\n mounted: mounted.length,\n surfaceChars: chars,\n visibleChars,\n deferredChars,\n budgetChars,\n deferring,\n }\n}\n\n/** Construction options for the `mcp_search_tools` definition. */\nexport interface SearchToolOptions {\n /** Live schemas the search matches and may activate: the whole visible MCP surface. */\n readonly available: () => readonly ToolSchemaLike[]\n /** Record the matched names as activated for the session. */\n readonly activate: (names: readonly string[]) => void\n /** Cap applied when a call omits `limit`; defaults to {@link DEFAULT_SEARCH_LIMIT}. */\n readonly defaultLimit?: number\n}\n\n/** One search result: what the model may call directly from the next step on. */\ninterface SearchMatch {\n readonly name: string\n readonly description: string\n}\n\n/**\n * Build the `mcp_search_tools` definition.\n *\n * The tool never pretends: a query that matches nothing says so, and it only\n * ever offers schemas its session actually sees (the caller supplies that\n * filtered list). Activating is enough to present a tool from the *next* step\n * on, because the assembly listener reads the state at every request.\n *\n * @param options - the session's visible schemas and activation sink.\n * @returns a registry-ready definition.\n */\nexport function createSearchTool(options: SearchToolOptions): ToolDefinitionLike {\n const defaultLimit = options.defaultLimit ?? DEFAULT_SEARCH_LIMIT\n return {\n name: SEARCH_TOOL_NAME,\n description:\n 'Search the MCP tools this session sees and activate every match, so the activated tools are offered directly from the next model step on. Use it when the tool you need is not listed: a tool it activates joins the offered list from the next model step on, and until then only the tools already listed are reliable. `query` matches tool names and descriptions — case-insensitive, each word on its own, so separate keywords (`issue update`) find what a whole sentence does not; `limit` caps how many matches are activated.',\n parameters: {\n type: 'object',\n properties: {\n query: {\n type: 'string',\n description: 'A keyword or name fragment of the needed MCP tool; several words are matched one by one.',\n },\n limit: {\n type: 'integer',\n description: `Maximum matches to activate; default ${defaultLimit}.`,\n },\n },\n required: ['query'],\n additionalProperties: false,\n },\n output: {\n // The canonical value is a small JSON object; any of its shapes is valid.\n schema: {},\n render: (_args, value) => [{ type: 'text', text: renderJson(value) }],\n },\n async execute(args) {\n const query = readQuery(args)\n if (query === '') {\n throw new Error(`${SEARCH_TOOL_NAME}: \"query\" must be a non-empty string`)\n }\n const matches = searchTools(options.available(), query, readLimit(args, defaultLimit))\n options.activate(matches.map((match) => match.name))\n return {\n query,\n matches,\n activated: matches.map((match) => match.name),\n message:\n matches.length === 0\n ? `no MCP tool of this project matches ${JSON.stringify(query)}`\n : `${matches.length} MCP tool(s) match and will be offered from the next step on`,\n }\n },\n }\n}\n\n/** What the wiring needs from the runtime; everything is read at use time. */\nexport interface ActivationWiringOptions {\n /** Agent-scoped context; both the listener and the search tool live here. */\n readonly ctx: ActivationContextLike\n /** Current activation state of the session. */\n readonly state: () => ActivationState\n /** Replace the session's activation state after a transition. */\n readonly setState: (next: ActivationState) => void\n /** Live schemas of the tools this plugin mounted for the session. */\n readonly available: () => readonly ToolSchemaLike[]\n /**\n * Every MCP schema the session sees — the profile plane, this plugin's own\n * mounts, and any F-19 forwarders — beyond {@link available}. The deferral\n * budget and the discovery tool count this whole surface, while the\n * context-driven tier and the usage counters keep reading `available` alone.\n * Absent means `available` is the whole surface, so a deployment whose\n * presentation owner already hides the profile plane keeps today's behaviour.\n */\n readonly visible?: () => readonly ToolSchemaLike[]\n /**\n * Names that belong to ANOTHER project mounted in this process, which this\n * session must never be offered. The runtime computes the set from the other\n * projects it manages, and the assembly listener drops every such name from\n * the assembled request — whatever the tool mode, and however large the\n * surface. The budget and the discovery tool keep counting the whole visible\n * surface, so this only trims the final list and never re-feeds the deferral\n * decision. Absent means nothing is foreign, which keeps a deployment without\n * the containment probe on today's behaviour.\n */\n readonly foreign?: () => ReadonlySet<string>\n /** Cap on the tools one search activates; defaults to {@link DEFAULT_SEARCH_LIMIT}. */\n readonly searchLimit?: number\n /**\n * Cap on the names the context-driven tier offers at once; defaults to\n * {@link DEFAULT_AUTO_ACTIVATION_LIMIT}, and `0` disables the tier.\n */\n readonly autoLimit?: number\n /** Extra advances a context offer survives; defaults to {@link DEFAULT_AUTO_ACTIVATION_STICKY_STEPS}. */\n readonly autoStickySteps?: number\n /** Lowest BM25 score the context-driven tier may offer; defaults to {@link MIN_AUTO_SCORE}. */\n readonly autoMinScore?: number\n /**\n * Serialized size of the MCP surface, in characters, above which this module\n * defers tools at all; defaults to {@link DEFAULT_TOOL_BUDGET_CHARS}. `0`\n * defers every surface, however small.\n */\n readonly toolBudgetChars?: number\n /**\n * Live tool policy of the session's project; absent means the shipped default,\n * {@link DEFAULT_TOOL_POLICY}. Read at every assembly, so a mode or pin change\n * applies from the next step on, without re-minting the scope.\n */\n readonly policy?: () => ToolPolicy\n /**\n * Number of the agent step this plugin is currently on, counted by the caller\n * from its own `agent/pre-step` hook. Read when a search activates names, so\n * the record of that offer carries the step it happened on. Absent means the\n * caller counts no steps, and then an activation records none.\n */\n readonly step?: () => number\n /**\n * Told the names one search just activated, and the step it happened on, so\n * the caller can keep that stamp for the lifetime of the session — longer\n * than one scope's wiring, which an idle release disposes. Absent drops the\n * stamp: the offer is still recorded, it simply carries no step.\n */\n readonly onActivated?: (names: readonly string[], step: number) => void\n /**\n * Told that a compaction ended some of the session's activations, so the\n * caller can drop the step records that belonged to the ones it removed.\n * Absent leaves the records in place, which only means a later activation of\n * the same name may carry the step of the offer the compaction removed.\n */\n readonly onCompaction?: () => void\n /**\n * Told that the offered set may have moved: a search activated names, a\n * compaction dropped the ones no call backed, or the context tier advanced.\n *\n * A harness whose assembly carries no tool list cannot be filtered from this\n * module at all (0.2.2 and later: declarations are provider-owned), so the\n * presentation lives in the caller's own registrations instead — the bridge's\n * `deferLoading` forwarders. This is the seat that keeps that copy level with\n * {@link ActivationState}; absent simply means nothing presents the set but the\n * assembly this module used to rewrite.\n */\n readonly onOfferedChanged?: () => void\n /** Context-driven state to start from; defaults to an empty state. */\n readonly autoState?: AutoOfferState\n /** Sink for the context-driven state after every advance that changed it. */\n readonly setAutoState?: (next: AutoOfferState) => void\n /** Sink for a contained failure of this plugin's own work. */\n readonly onError?: (error: unknown) => void\n}\n\n/**\n * The context-driven tier's live inputs, owned by the wiring for one scope.\n *\n * `userText` is the newest committed `user/message` and `calls` holds the tool\n * names called since the last advance; both are read from the events the\n * harness already dispatches, and `changed` records that the task context moved\n * since the offered set was last computed.\n */\ninterface ActivationQueryTracker {\n /** Context-driven state as of the last advance. */\n state: AutoOfferState\n /** Newest committed user-role text, `''` until the session has one. */\n userText: string\n /** Tool names called since the last advance, call order preserved. */\n calls: string[]\n /** `true` while a committed user message arrived after the last advance. */\n changed: boolean\n}\n\n/**\n * Install the session wiring on one agent scope: the `system-prompt/assemble`\n * listener, the `mcp_search_tools` registration, and the `session/event`\n * listener that feeds compaction, the task context, and the recent-call names.\n *\n * The listener is prepended so it is the **outermost** handler of the waterfall:\n * `next()` has already run every plugin that filters the catalogue (the\n * `dsh-progressive-tools` presentation this replaces), and the list it returns is\n * the one that runs. Idle pruning is not wired here — the runtime already\n * watches `agent/status`, and it calls {@link pruneIdle} on that transition.\n *\n * The context-driven tier advances only when the task context actually moves: a\n * new user message or a new tool call. When it does, and the resulting offered\n * set is the one the previous advance produced, this returns the identical\n * assembly object, so nothing downstream treats the tool list as changed.\n *\n * @param options - scope, session state accessors, and the mounted-schema probe.\n * @returns the disposer that unregisters everything installed here.\n */\nexport function installActivation(options: ActivationWiringOptions): () => void {\n const tracker: ActivationQueryTracker = {\n state: options.autoState ?? createAutoOfferState(),\n userText: '',\n calls: [],\n changed: false,\n }\n\n /**\n * Record the step an activation happened on. Owned by the caller, because the\n * session, not one scope's wiring, is what keeps an activation across an idle\n * release; this is the only place a search activation happens, so it is the\n * only place the record can be made.\n */\n const recordActivated = (names: readonly string[]): void => {\n const step = options.step?.() ?? 0\n if (step > 0) options.onActivated?.(names, step)\n }\n\n const dispose = (fn: () => void): void => {\n try {\n fn()\n } catch (error) {\n options.onError?.(error)\n }\n }\n const listen = (name: string, listener: ListenerLike, prepend: boolean): (() => void) => {\n const registered = options.ctx.on(name, listener, { prepend })\n return typeof registered === 'function' ? (registered as () => void) : () => undefined\n }\n\n /** Recompute the context-driven offer whenever the task context actually moved. */\n const advance = (): void => {\n const calls = tracker.calls\n tracker.calls = []\n // Nothing new: the offered set from the previous advance is still current,\n // so not touching it is what keeps the request prefix byte-identical.\n if (!tracker.changed && calls.length === 0) return\n tracker.changed = false\n if (autoOfferLimit(options.autoLimit) === 0) return\n const next = advanceAutoOffer(\n tracker.state,\n { userText: tracker.userText, recentCalls: calls },\n options.available(),\n {\n ...(options.autoLimit === undefined ? {} : { limit: options.autoLimit }),\n ...(options.autoStickySteps === undefined ? {} : { stickySteps: options.autoStickySteps }),\n ...(options.autoMinScore === undefined ? {} : { minScore: options.autoMinScore }),\n },\n )\n if (next === tracker.state) return\n tracker.state = next\n options.setAutoState?.(next)\n // The offered set moved, so a presentation that lives outside this assembly —\n // the bridge's `deferLoading` forwarders — has to follow it.\n options.onOfferedChanged?.()\n }\n\n /** Every name the session's explicit activation and context-driven tiers offer. */\n const offeredNames = (): ReadonlySet<string> => {\n const names = new Set(presentedNames(options.state()))\n for (const name of autoPresentedNames(tracker.state)) names.add(name)\n return names\n }\n\n /**\n * Every MCP schema the session sees, as one name-keyed surface: this plugin's\n * own mounts first, then the profile plane and any F-19 forwarders, each name\n * once. This plugin's discovery tool is left out by identity — it is added\n * separately below, so a profile that already lists a tool named\n * `mcp_search_tools` cannot shadow the one this module mints.\n */\n const wholeSurface = (): readonly ToolSchemaLike[] => {\n const available = options.available()\n const visible = options.visible?.() ?? []\n if (visible.length === 0) return available\n const seen = new Set<string>()\n const merged: ToolSchemaLike[] = []\n for (const schema of available) {\n if (schema.name === SEARCH_TOOL_NAME) continue\n seen.add(schema.name)\n merged.push(schema)\n }\n for (const schema of visible) {\n if (schema.name === SEARCH_TOOL_NAME || seen.has(schema.name)) continue\n seen.add(schema.name)\n merged.push(schema)\n }\n return merged\n }\n\n /**\n * Whether the whole visible MCP surface is large enough to be worth deferring\n * at all. A surface that already fits the budget is carried whole by the\n * request, so hiding a few of its tools would rewrite the prompt prefix — and\n * cost the model its cache — to save nothing. `0` disables the gate.\n */\n const deferring = (surface: readonly ToolSchemaLike[]): boolean =>\n overToolBudget(\n surfaceChars(surface),\n options.toolBudgetChars ?? DEFAULT_TOOL_BUDGET_CHARS,\n )\n\n /**\n * Containment: a name another project mounts in this process never reaches the\n * assembled request, whatever the mode does around it. The set is read fresh on\n * every assembly, and the whole visible surface the budget measures is\n * deliberately unchanged — containment trims the final list only, so the\n * deferral decision still counts a foreign name the host defect leaked into the\n * session's chain. Absent (or empty) means nothing is foreign, and the\n * continuation's value comes back by identity.\n */\n const contain = (result: AssemblyLike): AssemblyLike => {\n if (!Array.isArray(result.tools)) return result\n const foreign = options.foreign?.() ?? NO_FOREIGN\n if (foreign.size === 0) return result\n const kept = result.tools.filter((tool) => !foreign.has(tool.name))\n return kept.length === result.tools.length ? result : { ...result, tools: kept }\n }\n\n /**\n * The visible surface without the names another project's mount leaked into\n * this session's chain. The discovery catalogue is built from this rather than\n * from {@link wholeSurface}: a name the session may never be offered must not\n * come back as text through a search either, or the containment would hand the\n * foreign catalogue over one step later. The deferral decision still counts the\n * whole surface, foreign names included — they occupy the request just as\n * locally mounted ones would.\n */\n const searchable = (): readonly ToolSchemaLike[] => {\n const foreign = options.foreign?.() ?? NO_FOREIGN\n const surface = wholeSurface()\n return foreign.size === 0 ? surface : surface.filter((schema) => !foreign.has(schema.name))\n }\n\n const merge = (result: AssemblyLike): AssemblyLike => {\n const policy = options.policy?.() ?? DEFAULT_TOOL_POLICY\n // A harness whose assembly carries no tool list cannot be shaped from here at\n // all. From 0.2.2 on, `system-prompt/assemble` transforms a presentation and\n // the declared schemas are provider-owned, so a listener that rewrote\n // `assembly.tools` would be writing into a field the harness discards — and\n // reading it would throw on every model request. The presentation lives in\n // the caller's `deferLoading` forwarders instead (`src/bridge.ts`), kept level\n // through {@link ActivationWiringOptions.onOfferedChanged}; this listener\n // still drives the context tier and degrades to the rest of the harness's\n // answer.\n if (!Array.isArray(result.tools)) {\n if (policy.mode === 'disclosure') advance()\n return result\n }\n const surface = wholeSurface()\n // Nothing is visible: there is nothing to find, so nothing is added.\n if (surface.length === 0) return contain(result)\n // `off` promises that the project's tools are not offered, and the promise is\n // about the request, not only about what the panel says: the project plane\n // leaves the assembly here. Only this plugin's own mounts go — the profile\n // plane and other plugins' tools are none of this mode's business — and a pin\n // does not cancel the mode, so the discovery tool is not advertised either,\n // because there is nothing it may disclose.\n if (policy.mode === 'off') {\n const mounted = options.available()\n if (mounted.length === 0) return contain(result)\n const offNames = new Set(mounted.map((schema) => schema.name))\n const kept = result.tools.filter((tool) => !offNames.has(tool.name))\n return contain(kept.length === result.tools.length ? result : { ...result, tools: kept })\n }\n // `direct` is the opposite promise: the whole visible catalogue is listed, so\n // the assembly is handed back exactly as the rest of the harness produced it\n // and the discovery tool is not advertised — except that another project's\n // tools, which this session must never carry, still leave it.\n if (policy.mode !== 'disclosure') return contain(result)\n advance()\n // The discovery tool is pinned: offered in every disclosure assembly,\n // whatever the budget says. A surface inside the budget is carried whole —\n // every mounted tool stays listed — and the search tool is added alongside\n // them so the model can always discover tools as the project grows. Over\n // budget, this module does the trimming a presentation owner would\n // otherwise do: every `mcp__` tool the budget pushed out is dropped, while\n // the non-MCP tools the inner listeners listed (core tools, other plugins)\n // are kept. `withActiveTools` inserts the wanted schemas at their sorted\n // position and never duplicates or reorders an existing entry. Pins are\n // wanted unconditionally — offered from the first step of every request,\n // whatever the counters and the budget say — and a pin or activation may\n // name a profile-plane tool, whose schema is found in `surface` and\n // re-inserted.\n const defer = deferring(surface)\n const wanted = new Set(offeredNames())\n for (const pin of policy.pins) wanted.add(pin)\n wanted.add(SEARCH_TOOL_NAME)\n const kept = defer\n ? result.tools.filter(\n (tool) => wanted.has(tool.name) || !tool.name.startsWith('mcp__'),\n )\n : result.tools\n const merged = withActiveTools(kept, [...surface, schemaOf(search)], wanted)\n // Identity is decided on the list this call produced, never on whether the\n // names this module wants have changed: the inner listeners rebuild the\n // registry list from scratch on every step and re-apply their own filtering,\n // so a memoized \"nothing changed\" answer would hand back their trimmed list\n // with this module's additions missing, one step after they appeared.\n // Returning `result` when nothing was dropped or added keeps the prompt\n // prefix — and the model's cache — byte-identical, the property that matters.\n const changed = kept.length !== result.tools.length || merged.length !== kept.length\n return contain(changed ? { ...result, tools: merged } : result)\n }\n\n const assemble: AssembleListener = async (_assembly, _context, next) => {\n const result = await next()\n try {\n return merge(result)\n } catch (error) {\n // A listener that throws would break every model request of the session;\n // this one degrades to \"the assembly the rest of the harness produced\".\n options.onError?.(error)\n return result\n }\n }\n\n const observe = (_session: unknown, event: SessionEventLike): void => {\n try {\n if (event?.type === 'compaction/end') {\n options.setState(onCompaction(options.state(), Date.now()))\n // The step records of the activations the compaction just dropped go\n // with them: a name activated again after this is stamped with the step\n // it returns on, not with the one it left on, while a tool the session\n // really used keeps the step its offer happened on.\n options.onCompaction?.()\n // A compaction rewrote the conversation the offers belonged to, so the\n // context tier starts over; the counter baseline is untouched.\n tracker.state = resetAutoOffer(tracker.state)\n tracker.calls = []\n tracker.changed = false\n // The boundary is the one place that shrinks the offered set, so a\n // presentation outside this assembly re-applies it here.\n options.onOfferedChanged?.()\n return\n }\n if (event?.type === 'user/message') {\n const text = readUserMessage(event)\n // An empty text (an image-only or non-text message) says nothing about\n // the task, so it must not wipe a context an earlier message set up.\n if (text !== '' && text !== tracker.userText) {\n const bounded = boundTaskText(text)\n tracker.changed = bounded !== tracker.userText\n tracker.userText = bounded\n }\n return\n }\n if (event?.type === 'tool/call') {\n const name = readCallName(event)\n if (name !== '') {\n tracker.calls.push(name)\n if (tracker.calls.length > MAX_AUTO_RECENT_CALLS) {\n tracker.calls.splice(0, tracker.calls.length - MAX_AUTO_RECENT_CALLS)\n }\n }\n }\n } catch (error) {\n options.onError?.(error)\n }\n }\n\n const search = createSearchTool({\n available: searchable,\n activate: (names) => {\n recordActivated(names)\n options.setState(activate(options.state(), names, Date.now()))\n options.onOfferedChanged?.()\n },\n ...(options.searchLimit === undefined ? {} : { defaultLimit: options.searchLimit }),\n })\n\n const disposers: (() => void)[] = [\n listen('system-prompt/assemble', assemble as unknown as ListenerLike, true),\n listen('session/event', observe as unknown as ListenerLike, false),\n ]\n try {\n disposers.push(options.ctx.tools.register(search))\n } catch (error) {\n options.onError?.(error)\n }\n return () => {\n for (const registered of disposers) dispose(registered)\n }\n}\n\n/**\n * Read the tool name out of one committed `tool/call` event.\n *\n * The recent calls are context evidence only, never activation: a name the\n * context tier offers is still filtered by the runtime's own mount records, so\n * a call to a profile-level tool cannot smuggle a foreign name into the list.\n *\n * @param event - one event as the `session/event` listener receives it.\n * @returns the called tool's public name, or `''` when the event carries none.\n */\nfunction readCallName(event: SessionEventLike): string {\n if (event.type !== 'tool/call' || !isRecord(event.data)) return ''\n const name = event.data.name\n return typeof name === 'string' ? name : ''\n}\n\n/** Read and normalize the `query` argument. */\nfunction readQuery(args: unknown): string {\n if (!isRecord(args)) return ''\n const query = args.query\n return typeof query === 'string' ? query.trim() : ''\n}\n\n/** Read the `limit` argument, clamped to the tool's supported range. */\nfunction readLimit(args: unknown, fallback: number): number {\n if (!isRecord(args)) return fallback\n const raw = args.limit\n if (typeof raw !== 'number' || !Number.isFinite(raw)) return fallback\n const limit = Math.trunc(raw)\n if (limit <= 0) return fallback\n return Math.min(limit, MAX_SEARCH_LIMIT)\n}\n\n/**\n * Score one schema against the query: an exact name beats a name substring, and\n * both beat a description hit. Results keep the best score first and the name\n * order breaks ties, so one query always returns the same list.\n */\nfunction searchTools(\n available: readonly ToolSchemaLike[],\n query: string,\n limit: number,\n): SearchMatch[] {\n const needle = query.toLowerCase()\n const tokens = searchTokens(needle)\n const scored: { match: SearchMatch; score: number }[] = []\n for (const tool of available) {\n const description = typeof tool.description === 'string' ? tool.description : ''\n const score = scoreTool(tool.name, description, needle, tokens)\n if (score === 0) continue\n scored.push({ match: { name: tool.name, description }, score })\n }\n scored.sort((left, right) => right.score - left.score || compareNames(left.match.name, right.match.name))\n return scored.slice(0, limit).map((entry) => entry.match)\n}\n\n/**\n * Distinct words of a query, lowercased, in first-use order. Words shorter\n * than two characters are dropped (a one-letter word is a substring of half\n * the catalog and scores noise, not intent); the split keeps letters, digits\n * and underscores, so a query may quote a tool name verbatim (`issue_update`)\n * as well as name its concepts (`issue update`).\n */\nfunction searchTokens(needle: string): string[] {\n const tokens: string[] = []\n const seen = new Set<string>()\n for (const piece of needle.split(/[^\\p{L}\\p{N}_]+/u)) {\n if (piece.length < 2 || seen.has(piece)) continue\n seen.add(piece)\n tokens.push(piece)\n if (tokens.length >= MAX_SEARCH_TOKENS) break\n }\n return tokens\n}\n\n/**\n * Score one candidate tool; `0` means no match. The whole query as one\n * substring stays the strongest signal (an exact name beats a phrase that\n * happens to sit inside a description), and every query word then adds its\n * own hit — a word in the name outweighs the same word in the description.\n * The per-word tier is what keeps a natural query like \"issue get create\n * update\" useful: no tool contains that phrase, but the tools that contain\n * most of its words are exactly the ones the model meant.\n */\nfunction scoreTool(name: string, description: string, needle: string, tokens: readonly string[]): number {\n const lowerName = name.toLowerCase()\n if (lowerName === needle) return 1_000\n const lowerDescription = description.toLowerCase()\n let score = 0\n if (lowerName.includes(needle)) score += 500\n else if (lowerDescription.includes(needle)) score += 250\n for (const token of tokens) {\n if (lowerName.includes(token)) score += 10\n else if (lowerDescription.includes(token)) score += 1\n }\n return score\n}\n\n/** Code-unit name comparison, matching the canonical tool order of DSH. */\nfunction compareNames(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0\n}\n\n/** Serialize one canonical value for the model; total by construction. */\nfunction renderJson(value: unknown): string {\n const text = JSON.stringify(value, undefined, 2)\n return text === undefined ? String(value) : text\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n","/**\n * MCP document parsing for `dsh-project-mcp`.\n *\n * Reads Kimi Code / Claude-style documents (`{ \"mcpServers\": { ... } }`) and\n * converts every entry into an `@deepseek-ai/dsh-mcp-client` config. The module\n * is intentionally free of Cordis and of ambient process state: environment,\n * project dotenv values, plugin-level `inputs` and credential values are\n * injected through {@link ResolveContext}, so the whole conversion is\n * unit-testable.\n *\n * Error policy: a broken row never blocks the document. It becomes an entry\n * with `error` set, which the runtime surfaces as an `error` row.\n *\n * @module dsh-project-mcp/parse\n */\n\nimport { readFileSync } from 'node:fs'\nimport type { Config as McpClientConfig } from '@deepseek-ai/dsh-mcp-client'\n\n/**\n * `serverName` accepted by mcp-client; anything else cannot own a tool\n * namespace (`mcp__<serverName>__<rawName>`).\n */\nexport const SERVER_NAME_PATTERN = /^[A-Za-z0-9_-]{1,32}$/\n\n/** Whole-string `${NAME}` / `${input:NAME}` reference. */\nconst WHOLE_REF_PATTERN = /^\\$\\{(.+)\\}$/\n\n/** Any `${...}` reference inside a longer string. */\nconst INLINE_REF_PATTERN = /\\$\\{([^}]+)\\}/g\n\n/** The same grammar, read through `matchAll` where every reference is needed. */\nconst REFERENCE_PATTERN = /\\$\\{([^}]+)\\}/g\n\n/** Prefix selecting the interactive-input namespace of a reference. */\nconst INPUT_PREFIX = 'input:'\n\n/** Maximum length of a generated `serverName`. */\nconst MAX_SERVER_NAME_LENGTH = 32\n\n/** Severity of a parse diagnostic. */\nexport type IssueLevel = 'error' | 'warning'\n\n/** One diagnostic produced while reading a document. */\nexport interface ParseIssue {\n /** Absolute path of the document (or a pseudo-path for in-memory input). */\n source: string\n /** Server key the diagnostic belongs to, when it is entry-scoped. */\n server?: string\n /** Whether the entry is unusable (`error`) or merely notable (`warning`). */\n level: IssueLevel\n /** Human-readable description. */\n message: string\n /**\n * Stable wire code of `message` (`projectMcp.host` namespace), for\n * client-side translation. Additive: `message` keeps its byte-identical\n * English and stays the fallback, and behavioural matches key on this field\n * — never on the prose, which the client may have translated.\n */\n code?: string\n /** Flat params of {@link ParseIssue.code}, stringified at emission. */\n params?: Record<string, string>\n}\n\n/** One parsed `mcpServers` entry: exactly one of `config` / `error` is set. */\nexport interface ParsedEntry {\n /** Key in `mcpServers` (or the sanitized form of it). */\n name: string\n /** `false` only for an explicit `enabled: false` / `disabled: true`. */\n enabled: boolean\n /** Absolute path of the document the entry came from. */\n source: string\n /** mcp-client config, ready to mount. */\n config?: McpClientConfig\n /** Why the entry cannot be mounted. */\n error?: string\n /**\n * Stable wire code of `error` (`projectMcp.host` namespace) — the path by\n * which a parse failure becomes a translated `row.detail` on the client.\n */\n errorCode?: string\n /** Flat params of {@link ParsedEntry.errorCode}, stringified at emission. */\n errorParams?: Record<string, string>\n}\n\n/** External values needed to expand `${...}` references. */\nexport interface ResolveContext {\n /** Ambient environment (`process.env`). */\n env: Record<string, string | undefined>\n /** Project-local dotenv values (`<project>/.env`, then `<project>/.dsh/.env`). */\n dotenv: Record<string, string>\n /** Plugin-level `inputs` config: explicit `${input:NAME}` values. */\n inputs: Record<string, string>\n /** Values read from the DSH credentials file. */\n secrets: Record<string, string>\n /**\n * Identity of the three value sources above, so a caller that caches whole\n * parsed documents can tell \"the same values answered this parse\" from \"the\n * files moved\". Opaque here: the parser never reads it.\n */\n stamp?: string\n /** Project root used as the default `cwd` of stdio servers. */\n projectRoot: string\n /** Timeout applied to every generated config. */\n toolCallTimeoutMs: number\n /** Whether a failed initial connection should reject the mount. */\n failOnStartupError: boolean\n}\n\n/** Result of parsing one document. */\nexport interface ParsedDocument {\n /** Entries in document order. */\n entries: ParsedEntry[]\n /** Diagnostics for the document itself and for individual entries. */\n issues: ParseIssue[]\n /** `false` when the file could not be read or held no server map. */\n ok: boolean\n}\n\ntype Resolution =\n | { ok: true; value: string }\n | { ok: false; message: string; code: string; params?: Record<string, string> }\n\n/** Expand every `${...}` reference inside `value`. */\nexport function expandValue(value: string, ctx: ResolveContext): Resolution {\n const whole = WHOLE_REF_PATTERN.exec(value)\n if (whole !== null) return resolveRef(whole[1] as string, ctx)\n let failure: Extract<Resolution, { ok: false }> | undefined\n const replaced = value.replace(INLINE_REF_PATTERN, (match, ref: string) => {\n const resolved = resolveRef(ref, ctx)\n if (resolved.ok) return resolved.value\n failure ??= resolved\n return match\n })\n if (failure !== undefined) return failure\n return { ok: true, value: replaced }\n}\n\n/**\n * Whether `value` contains at least one `${...}` reference.\n *\n * A value written as a reference does not live in the declaring document, so\n * an editor is shown the key without it and a save keeps the declared text\n * instead of substituting the resolved value.\n * @param value - declared string value.\n * @returns `true` when the value carries a reference.\n */\nexport function hasReference(value: string): boolean {\n return /\\$\\{[^}]+\\}/.test(value)\n}\n\n/**\n * Whether any `${...}` reference of `value` is answered from outside the\n * process — by the project's `.env` or by the credentials file.\n *\n * Provenance only, mirroring {@link resolveRef}'s own fallback order (plugin\n * inputs, then the project dotenv values, then `process.env`, then credentials):\n * a value whose reference falls through to one of the two external maps is\n * marked `fromCredentials` in a snapshot — the flag the editor reads as \"do not\n * write the resolved value back\" — and stays as declared.\n * @param value - declared string value.\n * @param ctx - same resolve context the mount path uses.\n * @returns `true` when at least one reference was answered externally.\n */\nexport function referencesCredentials(value: string, ctx: ResolveContext): boolean {\n for (const match of value.matchAll(REFERENCE_PATTERN)) {\n const ref = match[1]?.trim() ?? ''\n const isInput = ref.startsWith(INPUT_PREFIX)\n const key = (isInput ? ref.slice(INPUT_PREFIX.length) : ref).trim()\n if (key === '') continue\n if (isInput && firstSet(ctx.inputs[key]) !== undefined) continue\n if (firstSet(ctx.dotenv[key]) !== undefined) return true\n if (firstSet(ctx.env[key]) !== undefined) continue\n if (firstSet(ctx.secrets[key]) !== undefined) return true\n }\n return false\n}\n\n/**\n * Resolve one `${...}` reference.\n *\n * `${input:NAME}` is answered by the plugin's own `inputs`, then by the same\n * chain a plain `${NAME}` uses, so a project can keep using the prefix its\n * `mcp.json` already carries. The chain is project-local first: the project's\n * dotenv documents, then the ambient environment, then the global credentials\n * file. An empty string counts as unset at every step.\n */\nfunction resolveRef(ref: string, ctx: ResolveContext): Resolution {\n const name = ref.trim()\n if (name.startsWith(INPUT_PREFIX)) {\n const key = name.slice(INPUT_PREFIX.length).trim()\n if (key === '') return { ok: false, message: 'empty ${input:} reference', code: 'parse.ref.empty' }\n const explicit = firstSet(ctx.inputs[key])\n if (explicit !== undefined) return { ok: true, value: explicit }\n const value = projectValue(ctx, key)\n if (value === undefined) {\n return {\n ok: false,\n message: `input \"${key}\" is not set (looked in plugin inputs, the project .env, the environment, and the credentials file)`,\n code: 'parse.ref.inputUnset',\n params: { key },\n }\n }\n return { ok: true, value }\n }\n const value = projectValue(ctx, name)\n if (value === undefined) {\n return {\n ok: false,\n message: `variable \"${name}\" is not set (looked in the project .env, the environment, and the credentials file)`,\n code: 'parse.ref.varUnset',\n params: { name },\n }\n }\n return { ok: true, value }\n}\n\n/** Project dotenv → ambient environment → credentials, for one key. */\nfunction projectValue(ctx: ResolveContext, key: string): string | undefined {\n return firstSet(ctx.dotenv[key], ctx.env[key], ctx.secrets[key])\n}\n\n/** The first non-empty value, or `undefined` when every source was unset. */\nfunction firstSet(...values: (string | undefined)[]): string | undefined {\n for (const value of values) {\n if (value !== undefined && value !== '') return value\n }\n return undefined\n}\n\n/** Sanitize an arbitrary `mcpServers` key into a valid `serverName`. */\nexport function slugifyServerName(name: string): string {\n const slug = name\n .replace(/[^A-Za-z0-9_-]+/g, '-')\n .replace(/^-+|-+$/g, '')\n return slug.slice(0, MAX_SERVER_NAME_LENGTH)\n}\n\n/**\n * Parse the text of one MCP document.\n * @param text - raw file content.\n * @param source - absolute path used for diagnostics and for entry `source`.\n * @param ctx - values used to expand references and to fill config defaults.\n * @returns parsed entries plus diagnostics; `ok` reports whether a server map was found.\n */\nexport function parseDocument(text: string, source: string, ctx: ResolveContext): ParsedDocument {\n const issues: ParseIssue[] = []\n let data: unknown\n try {\n data = JSON.parse(text) as unknown\n } catch (error) {\n return {\n entries: [],\n issues: [\n {\n source,\n level: 'error',\n message: `invalid JSON: ${errorText(error)}`,\n code: 'parse.json.invalid',\n params: { error: errorText(error) },\n },\n ],\n ok: false,\n }\n }\n const servers = extractServerMap(data)\n if (servers === null) {\n return {\n entries: [],\n issues: [\n {\n source,\n level: 'error',\n message: 'expected an object with an \"mcpServers\" object',\n code: 'parse.doc.notObject',\n },\n ],\n ok: false,\n }\n }\n const entries: ParsedEntry[] = []\n const seen = new Set<string>()\n for (const [key, raw] of Object.entries(servers)) {\n const name = sanitizeName(key, source, issues)\n if (name === undefined) continue\n if (seen.has(name)) {\n const message = `serverName \"${name}\" is declared twice in this document`\n const code = 'parse.server.duplicateName'\n const params = { name }\n issues.push({ source, server: name, level: 'error', message, code, params })\n entries.push({ name, enabled: false, source, error: message, errorCode: code, errorParams: params })\n continue\n }\n seen.add(name)\n entries.push(toEntry(name, raw, source, ctx, issues))\n }\n return { entries, issues, ok: true }\n}\n\n/** Read and parse one document; a missing file yields `undefined`. */\nexport function parseDocumentFile(path: string, ctx: ResolveContext): ParsedDocument | undefined {\n let text: string\n try {\n text = readFileSync(path, 'utf8')\n } catch {\n return undefined\n }\n return parseDocument(text, path, ctx)\n}\n\n/**\n * Extract a `name -> entry` map from a document: `mcpServers`, `servers`, or a\n * bare flat map whose values all look like server entries.\n * @param data - parsed document (or any JSON value).\n * @returns the server map, or `null` when the value holds none.\n */\nexport function extractServerMap(data: unknown): Record<string, unknown> | null {\n if (data === null || typeof data !== 'object' || Array.isArray(data)) return null\n const record = data as Record<string, unknown>\n for (const key of ['mcpServers', 'servers'] as const) {\n const container = record[key]\n if (container !== null && typeof container === 'object' && !Array.isArray(container)) {\n return container as Record<string, unknown>\n }\n }\n const values = Object.values(record)\n if (values.length === 0) return null\n const looksFlat = values.every(\n (value) => value !== null && typeof value === 'object' && !Array.isArray(value),\n )\n return looksFlat ? record : null\n}\n\n/**\n * Bring a `mcpServers` key into the `serverName` alphabet, or reject it when\n * nothing usable remains. A rename is a warning, not an error: the entry stays\n * mountable and only its tool namespace changes.\n */\nfunction sanitizeName(key: string, source: string, issues: ParseIssue[]): string | undefined {\n if (SERVER_NAME_PATTERN.test(key)) return key\n const slug = slugifyServerName(key)\n if (slug === '') {\n issues.push({\n source,\n server: key,\n level: 'error',\n message: `\"${key}\" cannot be converted into a valid serverName (${String(SERVER_NAME_PATTERN)})`,\n code: 'parse.server.badName',\n params: { key, pattern: String(SERVER_NAME_PATTERN) },\n })\n return undefined\n }\n issues.push({\n source,\n server: slug,\n level: 'warning',\n message: `serverName \"${key}\" is not a valid mcp-client name; using \"${slug}\"`,\n code: 'parse.server.renamedName',\n params: { key, slug },\n })\n return slug\n}\n\nfunction toEntry(\n name: string,\n raw: unknown,\n source: string,\n ctx: ResolveContext,\n issues: ParseIssue[],\n): ParsedEntry {\n if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {\n return fail(name, source, issues, 'entry must be an object', 'parse.entry.notObject')\n }\n const record = raw as Record<string, unknown>\n const enabled = record.enabled !== false && record.disabled !== true\n\n const declared = record.type ?? record.transport\n if (declared !== undefined && typeof declared !== 'string') {\n return fail(name, source, issues, '\"type\" must be a string', 'parse.entry.badType')\n }\n const normalized = declared === undefined ? undefined : declared.toLowerCase()\n if (\n normalized !== undefined\n && !['stdio', 'http', 'streamable-http', 'sse'].includes(normalized)\n ) {\n return fail(name, source, issues, '\"type\" must be one of \"stdio\", \"http\", \"streamable-http\" or \"sse\"', 'parse.entry.typeUnknown')\n }\n const hasUrl = record.url !== undefined\n const useHttp = normalized === undefined ? hasUrl : normalized !== 'stdio'\n return useHttp\n ? buildHttpEntry(name, record, source, ctx, issues, enabled)\n : buildStdioEntry(name, record, source, ctx, issues, enabled)\n}\n\nfunction buildStdioEntry(\n name: string,\n record: Record<string, unknown>,\n source: string,\n ctx: ResolveContext,\n issues: ParseIssue[],\n enabled: boolean,\n): ParsedEntry {\n const command = record.command\n if (typeof command !== 'string' || command === '') {\n return fail(name, source, issues, 'stdio servers require a \"command\"', 'parse.entry.noCommand')\n }\n const args = stringArray(record.args)\n if (args === undefined) return fail(name, source, issues, '\"args\" must be an array of strings', 'parse.entry.badArgs')\n const env = stringRecord(record.env)\n if (env === undefined) return fail(name, source, issues, '\"env\" must be an object of strings', 'parse.entry.badEnv')\n if (record.cwd !== undefined && typeof record.cwd !== 'string') {\n return fail(name, source, issues, '\"cwd\" must be a string', 'parse.entry.badCwd')\n }\n\n const expandedCommand = expandValue(command, ctx)\n if (!expandedCommand.ok) return fail(name, source, issues, expandedCommand.message, expandedCommand.code, expandedCommand.params)\n const expandedArgs = expandAll(args, ctx)\n if (!expandedArgs.ok) return fail(name, source, issues, expandedArgs.message, expandedArgs.code, expandedArgs.params)\n const expandedEnv = expandRecord(env, ctx)\n if (!expandedEnv.ok) return fail(name, source, issues, expandedEnv.message, expandedEnv.code, expandedEnv.params)\n const expandedCwd = expandValue(\n typeof record.cwd === 'string' && record.cwd !== '' ? record.cwd : ctx.projectRoot,\n ctx,\n )\n if (!expandedCwd.ok) return fail(name, source, issues, expandedCwd.message, expandedCwd.code, expandedCwd.params)\n\n return {\n name,\n enabled,\n source,\n config: {\n transport: 'stdio',\n serverName: name,\n command: expandedCommand.value,\n args: expandedArgs.value,\n env: expandedEnv.value,\n cwd: expandedCwd.value,\n toolCallTimeoutMs: ctx.toolCallTimeoutMs,\n failOnStartupError: ctx.failOnStartupError,\n },\n }\n}\n\nfunction buildHttpEntry(\n name: string,\n record: Record<string, unknown>,\n source: string,\n ctx: ResolveContext,\n issues: ParseIssue[],\n enabled: boolean,\n): ParsedEntry {\n const url = record.url\n if (typeof url !== 'string' || url === '') {\n return fail(name, source, issues, 'http servers require a \"url\"', 'parse.entry.noUrl')\n }\n const headers = stringRecord(record.headers)\n if (headers === undefined) {\n return fail(name, source, issues, '\"headers\" must be an object of strings', 'parse.entry.badHeaders')\n }\n const expandedUrl = expandValue(url, ctx)\n if (!expandedUrl.ok) return fail(name, source, issues, expandedUrl.message, expandedUrl.code, expandedUrl.params)\n const expandedHeaders = expandRecord(headers, ctx)\n if (!expandedHeaders.ok) return fail(name, source, issues, expandedHeaders.message, expandedHeaders.code, expandedHeaders.params)\n return {\n name,\n enabled,\n source,\n config: {\n transport: 'streamable-http',\n serverName: name,\n url: expandedUrl.value,\n headers: expandedHeaders.value,\n toolCallTimeoutMs: ctx.toolCallTimeoutMs,\n failOnStartupError: ctx.failOnStartupError,\n },\n }\n}\n\nfunction fail(\n name: string,\n source: string,\n issues: ParseIssue[],\n message: string,\n code: string,\n params?: Record<string, string>,\n): ParsedEntry {\n issues.push({\n source,\n server: name,\n level: 'error',\n message,\n code,\n ...(params === undefined ? {} : { params }),\n })\n return {\n name,\n enabled: false,\n source,\n error: message,\n errorCode: code,\n ...(params === undefined ? {} : { errorParams: params }),\n }\n}\n\nfunction expandAll(values: string[], ctx: ResolveContext): { ok: true; value: string[] } | Extract<Resolution, { ok: false }> {\n const result: string[] = []\n for (const value of values) {\n const expanded = expandValue(value, ctx)\n if (!expanded.ok) return expanded\n result.push(expanded.value)\n }\n return { ok: true, value: result }\n}\n\nfunction expandRecord(\n record: Record<string, string>,\n ctx: ResolveContext,\n): { ok: true; value: Record<string, string> } | Extract<Resolution, { ok: false }> {\n const result: Record<string, string> = {}\n for (const [key, value] of Object.entries(record)) {\n const expanded = expandValue(value, ctx)\n if (!expanded.ok) {\n return {\n ok: false,\n message: `${key}: ${expanded.message}`,\n // `{name}` deliberately carries the inner failure's English prose: the wrapper\n // covers three inner shapes (varUnset / inputUnset / empty ref) whose sentences\n // and params differ and collide with the flat `{key}` grammar, so no single\n // translated template can fill back byte-identically. Accepted partial\n // translation — F-48 ledger Ruling 4; only the wrapper punctuation localizes.\n code: 'parse.ref.failedInKey',\n params: { key, name: expanded.message },\n }\n }\n result[key] = expanded.value\n }\n return { ok: true, value: result }\n}\n\nfunction stringArray(value: unknown): string[] | undefined {\n if (value === undefined) return []\n if (!Array.isArray(value)) return undefined\n const result: string[] = []\n for (const item of value) {\n if (typeof item !== 'string') return undefined\n result.push(item)\n }\n return result\n}\n\nfunction stringRecord(value: unknown): Record<string, string> | undefined {\n if (value === undefined) return {}\n if (value === null || typeof value !== 'object' || Array.isArray(value)) return undefined\n const result: Record<string, string> = {}\n for (const [key, item] of Object.entries(value as Record<string, unknown>)) {\n if (typeof item !== 'string') return undefined\n result[key] = item\n }\n return result\n}\n\n/**\n * Merge per-document entry lists in priority order; a later document overrides\n * an earlier entry with the same `serverName`, keeping the position where that\n * name first appeared.\n * @param groups - entry lists from lowest to highest priority.\n * @returns merged entries plus the names that were overridden.\n */\nexport function mergeEntries(groups: ParsedEntry[][]): { entries: ParsedEntry[]; overridden: string[] } {\n const merged = new Map<string, ParsedEntry>()\n const overridden: string[] = []\n for (const group of groups) {\n for (const entry of group) {\n if (merged.has(entry.name)) overridden.push(entry.name)\n merged.set(entry.name, entry)\n }\n }\n return { entries: [...merged.values()], overridden }\n}\n\n/** Parse a YAML-ish credentials file into a flat string map. */\nexport function parseCredentials(text: string): Record<string, string> {\n const result: Record<string, string> = {}\n for (const line of text.split(/\\r?\\n/)) {\n const match = /^\\s*([A-Za-z_][A-Za-z0-9_]*)\\s*:\\s*(.*?)\\s*$/.exec(line)\n if (match === null) continue\n const value = (match[2] as string).replace(/^(['\"])(.*)\\1$/, '$2')\n if (value === '') continue\n result[match[1] as string] = value\n }\n return result\n}\n\n/**\n * Parse a dotenv document into a flat string map.\n *\n * The subset a project needs next to its `mcp.json`: one `KEY=value` per line,\n * an optional `export `, single or double quotes, and `#` comments — on their\n * own line, or after whitespace on a value line. Double quotes understand the\n * usual escapes (`\\n`, `\\r`, `\\t`, `\\\"`, `\\\\`); single quotes stay literal. An\n * empty value is skipped, exactly as {@link parseCredentials} skips one, so\n * `${NAME}` sees \"unset\" either way.\n * @param text - dotenv document contents.\n * @returns the values it declares, in first-wins order of the map.\n */\nexport function parseEnvFile(text: string): Record<string, string> {\n const result: Record<string, string> = {}\n for (const line of text.split(/\\r?\\n/)) {\n const match = /^\\s*(?:export\\s+)?([A-Za-z_][A-Za-z0-9_]*)\\s*=\\s*(.*?)\\s*$/.exec(line)\n if (match === null) continue\n const key = match[1] as string\n const value = unquoteEnvValue(match[2] as string)\n if (value === '') continue\n result[key] = value\n }\n return result\n}\n\n/** One dotenv value: unquoted (with an optional trailing comment), or quoted. */\nfunction unquoteEnvValue(raw: string): string {\n if (raw.startsWith('\"') && raw.endsWith('\"') && raw.length >= 2) {\n return raw\n .slice(1, -1)\n .replace(/\\\\n/g, '\\n')\n .replace(/\\\\r/g, '\\r')\n .replace(/\\\\t/g, '\\t')\n .replace(/\\\\\"/g, '\"')\n .replace(/\\\\\\\\/g, '\\\\')\n }\n if (raw.startsWith(\"'\") && raw.endsWith(\"'\") && raw.length >= 2) return raw.slice(1, -1)\n const comment = raw.indexOf(' #')\n return (comment === -1 ? raw : raw.slice(0, comment)).trim()\n}\n\nfunction errorText(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n","/**\n * Filesystem discovery for `dsh-project-mcp`: project root, config documents,\n * and the two credential sources behind `${...}` references — the global\n * credentials file and the project's own dotenv documents.\n *\n * Which MCP documents are read is a setting, not a constant: the deployment\n * lists its **local** documents (relative to a project root) and its **global**\n * ones (relative to `$HOME`, or absolute) in `localFiles` / `globalFiles`, and\n * one spec resolves through {@link expandConfigPath} to an absolute path.\n *\n * @module dsh-project-mcp/discovery\n */\n\nimport { existsSync, readFileSync, readdirSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { dirname, isAbsolute, join, resolve } from 'node:path'\nimport { parseCredentials, parseEnvFile } from './parse.ts'\n\n/** Directory/marker names that terminate the upward project-root walk. */\nexport const DEFAULT_PROJECT_MARKERS = ['.git', '.dsh', '.kimi-code', 'package.json']\n\n/** File-suffix markers that terminate the upward project-root walk. */\nexport const DEFAULT_FILE_MARKERS = ['.sln', '.slnx', '.csproj']\n\n/**\n * Project-relative documents read out of the box, in increasing priority: the\n * native DSH file only. A deployment that also wants another agent's document\n * names it in `localFiles`.\n */\nexport const DEFAULT_LOCAL_FILES: readonly string[] = ['.dsh/mcp.json']\n\n/**\n * Global documents read out of the box, in increasing priority: none. A global\n * document is read only when a deployment lists it in `globalFiles`, so a\n * project never inherits a server it did not ask for.\n */\nexport const DEFAULT_GLOBAL_FILES: readonly string[] = []\n\n/** `$DSH_HOME`, falling back to `~/.dsh`. */\nexport function dshHome(env: Record<string, string | undefined> = process.env): string {\n const configured = env.DSH_HOME\n return configured !== undefined && configured !== '' ? configured : join(homedir(), '.dsh')\n}\n\n/** Environment-variable references a path spec may carry. */\nconst HOME_REFERENCE = '~'\nconst DSH_HOME_REFERENCE = '$DSH_HOME'\nconst DSH_HOME_BRACED_REFERENCE = '${DSH_HOME}'\n\n/**\n * Resolve one configured document spec to an absolute path.\n *\n * A spec is read the way a shell reads it, in this order:\n *\n * - `~/x` (and a bare `~`) → `$HOME/x`;\n * - `$DSH_HOME/x` or `${DSH_HOME}/x` → the deployment's own home;\n * - an absolute path → itself;\n * - anything else → `base/x`, so a local document stays inside the project and\n * a global one stays inside `$HOME`.\n *\n * @param spec - one entry of `localFiles` or `globalFiles`.\n * @param base - directory a relative spec is read from.\n * @param env - environment used to resolve `$DSH_HOME`.\n * @returns the absolute document path.\n */\nexport function expandConfigPath(\n spec: string,\n base: string,\n env: Record<string, string | undefined> = process.env,\n): string {\n if (spec === HOME_REFERENCE) return homedir()\n if (spec.startsWith(`${HOME_REFERENCE}/`)) return resolve(homedir(), spec.slice(2))\n if (spec === DSH_HOME_REFERENCE || spec === DSH_HOME_BRACED_REFERENCE) return dshHome(env)\n if (spec.startsWith(`${DSH_HOME_REFERENCE}/`)) {\n return resolve(dshHome(env), spec.slice(DSH_HOME_REFERENCE.length + 1))\n }\n if (spec.startsWith(`${DSH_HOME_BRACED_REFERENCE}/`)) {\n return resolve(dshHome(env), spec.slice(DSH_HOME_BRACED_REFERENCE.length + 1))\n }\n if (isAbsolute(spec)) return resolve(spec)\n return resolve(base, spec)\n}\n\n/**\n * Project documents to read for one project root, in increasing priority — a\n * later document overrides an earlier entry of the same `serverName`.\n * @param projectRoot - absolute project root.\n * @param files - configured project-relative specs, lowest priority first.\n * @param env - environment used to resolve `$DSH_HOME`.\n * @returns absolute paths, lowest priority first.\n */\nexport function localConfigPaths(\n projectRoot: string,\n files: readonly string[] = DEFAULT_LOCAL_FILES,\n env: Record<string, string | undefined> = process.env,\n): string[] {\n return files.map((spec) => expandConfigPath(spec, projectRoot, env))\n}\n\n/**\n * Global documents of one deployment, in increasing priority. They are read\n * before a project's own documents, so a project declaration always wins.\n * @param files - configured specs, lowest priority first.\n * @param env - environment used to resolve `$DSH_HOME`.\n * @returns absolute paths, lowest priority first.\n */\nexport function globalConfigPaths(\n files: readonly string[] = DEFAULT_GLOBAL_FILES,\n env: Record<string, string | undefined> = process.env,\n): string[] {\n const home = homedir()\n return files.map((spec) => expandConfigPath(spec, home, env))\n}\n\n/** Default credentials document consulted for `${input:NAME}` values. */\nexport function defaultCredentialsPath(env: Record<string, string | undefined> = process.env): string {\n return join(dshHome(env), '.credentials.yaml')\n}\n\n/** Project-relative dotenv documents read for `${...}` values, lowest priority first. */\nexport const PROJECT_ENV_RELATIVE = ['.env', '.dsh/.env'] as const\n\n/**\n * Dotenv documents of one project, lowest priority first: the plain `.env` at\n * the project root, then the one in `.dsh` next to `mcp.json`. A value declared\n * in both is taken from the `.dsh` file — the project-local declaration wins.\n * @param projectRoot - absolute project root.\n * @returns absolute paths, lowest priority first.\n */\nexport function projectEnvPaths(projectRoot: string): string[] {\n return PROJECT_ENV_RELATIVE.map((relative) => join(projectRoot, relative))\n}\n\n/**\n * Walk upward from `cwd` to the first directory carrying a project marker.\n * @param cwd - absolute session working directory.\n * @param markers - directory/file marker names.\n * @param fileMarkers - file suffixes that also mark a project root.\n * @returns the absolute project root, or `undefined` when no marker is found.\n */\nexport function findProjectRoot(\n cwd: string,\n markers: readonly string[] = DEFAULT_PROJECT_MARKERS,\n fileMarkers: readonly string[] = DEFAULT_FILE_MARKERS,\n): string | undefined {\n let current = resolve(cwd)\n for (;;) {\n if (isProjectRoot(current, markers, fileMarkers)) return current\n const parent = dirname(current)\n if (parent === current) return undefined\n current = parent\n }\n}\n\nfunction isProjectRoot(\n dir: string,\n markers: readonly string[],\n fileMarkers: readonly string[],\n): boolean {\n for (const marker of markers) {\n if (existsSync(join(dir, marker))) return true\n }\n if (fileMarkers.length === 0) return false\n try {\n for (const entry of readdirSync(dir)) {\n if (fileMarkers.some((suffix) => entry.endsWith(suffix))) return true\n }\n } catch {\n return false\n }\n return false\n}\n\n/** Read the credentials document into a flat string map; missing file yields `{}`. */\nexport function readSecrets(path: string): Record<string, string> {\n try {\n return parseCredentials(readFileSync(path, 'utf8'))\n } catch {\n return {}\n }\n}\n\n/** Read one dotenv document into a flat string map; missing file yields `{}`. */\nexport function readEnvFile(path: string): Record<string, string> {\n try {\n return parseEnvFile(readFileSync(path, 'utf8'))\n } catch {\n return {}\n }\n}\n\n/**\n * Directories that hold this project's MCP documents. Used by the flat-watch\n * fallback when the runtime cannot watch a tree recursively.\n * @param projectRoot - absolute project root.\n * @param files - configured project-relative specs, lowest priority first.\n * @param env - environment used to resolve `$DSH_HOME`.\n * @returns existing directories, project root first, deduplicated.\n */\nexport function configDirectories(\n projectRoot: string,\n files: readonly string[] = DEFAULT_LOCAL_FILES,\n env: Record<string, string | undefined> = process.env,\n): string[] {\n const directories = [projectRoot]\n for (const path of localConfigPaths(projectRoot, files, env)) {\n const directory = dirname(path)\n if (!directories.includes(directory)) directories.push(directory)\n }\n return directories.filter((directory) => existsSync(directory))\n}\n","/**\n * Project-level MCP guidance for the session system prompt.\n *\n * A project can mount a large MCP surface, and with activation on (see\n * `./activation.ts`) most of its tools are not listed in a request at all: they\n * are offered on demand through `mcp_search_tools`. The per-server\n * `mcp:<server>` sections mcp-client publishes say what a server *is*, but\n * nothing tells the model that a tool it cannot see may still be asked for.\n *\n * This module contributes that one short section. {@link buildGuidance} is\n * pure: it turns a plain input object into markdown — or `''` when there is\n * nothing worth saying — with a hard length cap, a deterministic server order\n * and a deterministic truncated tool sample. {@link installGuidance} is the\n * thin scope wiring the runtime installs beside its mount and activation\n * wiring: it registers the section through `ctx.inject(['systemPrompt'], …)`\n * with a stable name whose code-unit order places it ahead of every per-server\n * block, and reads the project's live state at each assembly, so a rescan that\n * changes the mounted set changes the text without re-registering anything.\n *\n * The text never carries an absolute path, an endpoint or any other local\n * machine identifier: the project is named by its `~`-collapsed label\n * ({@link projectLabel}) and the input holds server names, states and tool\n * names only.\n *\n * Like `./activation.ts`, the module describes the prompt surface structurally\n * instead of importing `@deepseek-ai/dsh-system-prompt`: that peer is not\n * installed in every deployment, so the section and the injected scope are\n * declared by the minimal types below.\n *\n * @module dsh-project-mcp/guidance\n */\n\nimport { DEFAULT_ACTIVATION_ENABLED, SEARCH_TOOL_NAME } from './activation.ts'\nimport type { ServerStatus } from './types.ts'\n\n/** `true` unless a deployment turns the guidance section off. */\nexport const DEFAULT_GUIDANCE_ENABLED = true\n\n/**\n * Section name. At equal orders sections sort by code-unit name, and `-`\n * (0x2D) precedes `:` (0x3A), so this name — exactly like mcp-resources'\n * `mcp-resource-servers` — sorts ahead of every `mcp:<server>` instruction\n * block mcp-client publishes at the same order.\n */\nexport const GUIDANCE_SECTION_NAME = 'mcp-project-guidance'\n\n/** Hard cap on the section text; {@link buildGuidance} never returns more. */\nexport const MAX_GUIDANCE_CHARS = 1200\n\n/** Server bullets rendered at most, before the rest is summarized. */\nexport const MAX_GUIDANCE_SERVERS = 8\n\n/** Deferred tool names the on-demand inventory line shows before `+N more`. */\nexport const MAX_GUIDANCE_HIDDEN_NAMES = 12\n\n/** Baseline names the most-used line shows before `+N more`. */\nexport const MAX_GUIDANCE_MOST_USED = 4\n\n/** Longest purpose text kept in one server bullet. */\nexport const MAX_GUIDANCE_PURPOSE = 80\n\n/** One mounted server, as far as the guidance section describes it. */\nexport interface GuidanceServer {\n /** `serverName` of the mount. */\n readonly name: string\n /** Transport, when the mount has one. */\n readonly transport?: 'stdio' | 'streamable-http'\n /** Live mount state. */\n readonly status: ServerStatus\n /** Tool names the server currently publishes, in any order. */\n readonly tools?: readonly string[]\n /** Optional one-line purpose, shown after the server name. */\n readonly purpose?: string\n}\n\n/**\n * Plain input of {@link buildGuidance}. Every field is optional so a caller\n * that predates this feature (or a test) can pass a bare object; the defaults\n * describe \"no project, no servers\".\n */\nexport interface GuidanceInput {\n /** `~`-collapsed project label; defaults to `this project`. */\n readonly project?: string\n /** Mounted servers, in any order. */\n readonly servers?: readonly GuidanceServer[]\n /** Tool names offered directly in the request right now. */\n readonly offered?: readonly string[]\n /** Tool names reachable only through `mcp_search_tools` right now. */\n readonly deferred?: readonly string[]\n /**\n * The counter-seeded hot tools, most-called first. They are offered directly\n * from the first step on; naming them keeps the model from searching for\n * what it already has.\n */\n readonly mostUsed?: readonly string[]\n /** Whether the on-demand search surface is on; defaults to the activation default. */\n readonly activationEnabled?: boolean\n}\n\n/**\n * Build the project-MCP guidance section.\n *\n * Deterministic and total: server bullets follow code-unit name order, the\n * deferred surface is listed as one flat, sorted, deduped names line, and the\n * result never exceeds {@link MAX_GUIDANCE_CHARS} — when it would, trailing\n * server bullets are replaced by an `and N more server(s)` line, the on-demand\n * paragraph and the names line are reserved their room first, and a final cut\n * falls back to the last complete line. Equal input always yields equal\n * output, and `''` means there is nothing worth saying.\n *\n * @param input - project label, mounted servers and the offered/deferred split.\n * @returns markdown for one prompt section, or `''`.\n */\nexport function buildGuidance(input: GuidanceInput): string {\n const servers = normalizeServers(input.servers ?? [])\n if (servers.length === 0) return ''\n const activationEnabled = input.activationEnabled ?? DEFAULT_ACTIVATION_ENABLED\n const offered = new Set(input.offered ?? [])\n // A tool that is already offered is never presented as on-demand, and with\n // activation off nothing is on demand at all.\n const deferred = new Set(\n activationEnabled ? (input.deferred ?? []).filter((name) => !offered.has(name)) : [],\n )\n const header = [\n '## Project MCP servers',\n '',\n `Project \\`${label(input.project)}\\` mounts ${servers.length} MCP server(s) in this session.`,\n '',\n ]\n const tail: string[] = []\n // The counter-seeded hot tools are offered from the first step on; naming\n // them here keeps the model from searching for what it already has.\n const hot = mostUsedLine(input.mostUsed ?? [])\n if (activationEnabled && hot !== '') tail.push('', hot)\n if (deferred.size > 0) {\n tail.push('', onDemandParagraph(offered.size, deferred.size))\n tail.push('', hiddenNamesLine(deferred))\n }\n const bullets: string[] = []\n let hidden = 0\n for (const [index, server] of servers.entries()) {\n const remaining = servers.length - index\n const bullet = serverBullet(server)\n const overflow = remaining > 1 ? [`- … and ${remaining - 1} more server(s)`] : []\n const candidate = [...header, ...bullets, bullet, ...overflow, ...tail].join('\\n')\n if (index >= MAX_GUIDANCE_SERVERS || candidate.length > MAX_GUIDANCE_CHARS) {\n hidden = remaining\n break\n }\n bullets.push(bullet)\n }\n if (hidden > 0) bullets.push(`- … and ${hidden} more server(s)`)\n return applyCap([...header, ...bullets, ...tail].join('\\n'))\n}\n\n/**\n * `~`-collapsed display label for a project root.\n *\n * The session prompt must never carry an absolute path or a local machine\n * identifier, so the label is the home-relative form when the root lives under\n * `home` and the directory name otherwise. `home` is passed in rather than read\n * from the environment, which keeps the helper pure and testable.\n *\n * @param projectRoot - absolute project root, or any path-shaped string.\n * @param home - home directory to collapse to `~`, when known.\n * @returns a relative `~/…` label, the directory name, or `this project`.\n */\nexport function projectLabel(projectRoot: string, home?: string): string {\n const root = stripSeparators(projectRoot)\n if (root === '') return 'this project'\n if (home !== undefined) {\n const base = stripSeparators(home)\n if (base !== '') {\n if (root === base) return '~'\n if (root.startsWith(`${base}/`) || root.startsWith(`${base}\\\\`)) {\n return `~${root.slice(base.length)}`\n }\n }\n }\n const index = Math.max(root.lastIndexOf('/'), root.lastIndexOf('\\\\'))\n return index === -1 ? root : root.slice(index + 1)\n}\n\n/** The prompt-section fields this module registers (structural view). */\nexport interface GuidanceSectionLike {\n /** Unique section name. */\n readonly name: string\n /** Numeric sort order. */\n readonly order: number\n /** `false` preserves literal text; this section carries no variables. */\n readonly interpolate?: boolean\n /** Text, or a provider evaluated at each assembly. */\n readonly text: string | (() => string)\n}\n\n/** The `systemPrompt` slice the wiring reads (structural view). */\nexport interface GuidancePromptLike {\n /**\n * Register one ordered section in the calling scope.\n * @param section - the section to register.\n * @returns the registration's effect disposer.\n */\n section(section: GuidanceSectionLike): unknown\n /**\n * Resolve a centrally owned placement.\n * @param name - stable placement name.\n * @returns the numeric sort order.\n */\n getSectionOrder(name: 'MCP_SERVERS'): number\n}\n\n/** The injected scope carrying `systemPrompt`. */\nexport interface GuidancePromptScopeLike {\n /** The prompt registry. */\n readonly systemPrompt: GuidancePromptLike\n}\n\n/**\n * The agent-scoped context slice the guidance wiring touches. Described\n * structurally so the wiring is testable without a live harness.\n */\nexport interface GuidanceContextLike {\n /**\n * Start a callback once the injected services exist; the injected scope owns\n * what the callback registers.\n * @param deps - service names the callback requires.\n * @param callback - receives the injected scope.\n * @returns a disposer for the callback's own fiber, when the runtime gives one.\n */\n inject(deps: readonly string[], callback: (inner: GuidancePromptScopeLike) => unknown): unknown\n}\n\n/** Wiring options for {@link installGuidance}. */\nexport interface GuidanceWiringOptions {\n /** Agent-scoped context; the section lives here. */\n readonly ctx: GuidanceContextLike\n /** Live section text; called at every assembly, so it may read changing state. */\n readonly text: () => string\n /** Section name override; defaults to {@link GUIDANCE_SECTION_NAME}. */\n readonly name?: string\n /** Sink for a contained failure of this plugin's own work. */\n readonly onError?: (error: unknown) => void\n}\n\n/**\n * Register the guidance section on one agent scope.\n *\n * The section goes in through `ctx.inject(['systemPrompt'], …)`, so the scope\n * fiber owns it and a scope disposal unregisters it with the real registry.\n * The returned disposer is the explicit path for a host that publishes a plain\n * `systemPrompt` stub — the runtime keeps it and releases it exactly when it\n * releases the scope (idle release and agent disposal), so no section outlives\n * its mounts. It is idempotent.\n *\n * @param options - scope, live text provider and an optional failure sink.\n * @returns the disposer that unregisters everything installed here.\n */\nexport function installGuidance(options: GuidanceWiringOptions): () => void {\n const disposers: (() => void)[] = []\n const contain = (error: unknown): void => {\n options.onError?.(error)\n }\n try {\n const registered = options.ctx.inject(['systemPrompt'], (inner) => {\n const dispose = inner.systemPrompt.section({\n name: options.name ?? GUIDANCE_SECTION_NAME,\n order: inner.systemPrompt.getSectionOrder('MCP_SERVERS'),\n interpolate: false,\n text: options.text,\n })\n const release = disposerOf(dispose)\n if (release !== undefined) disposers.push(release)\n return dispose\n })\n const release = disposerOf(registered)\n if (release !== undefined) disposers.push(release)\n } catch (error) {\n contain(error)\n }\n return () => {\n // Newest first: the section registration is released before the injected\n // fiber that owns it. `splice` makes a second call a no-op.\n for (const dispose of disposers.splice(0).reverse()) {\n try {\n dispose()\n } catch (error) {\n contain(error)\n }\n }\n }\n}\n\n/** Dedupe by name, drop blank names and put the rest in code-unit name order. */\nfunction normalizeServers(servers: readonly GuidanceServer[]): GuidanceServer[] {\n const byName = new Map<string, GuidanceServer>()\n for (const server of servers) {\n const name = server.name.trim()\n if (name === '' || byName.has(name)) continue\n byName.set(name, { ...server, name })\n }\n return [...byName.values()].sort((left, right) => compareNames(left.name, right.name))\n}\n\n/** One server bullet: state and the optional purpose. */\nfunction serverBullet(server: GuidanceServer): string {\n const state =\n server.transport === undefined ? server.status : `${server.transport}, ${server.status}`\n const purpose = shorten(server.purpose, MAX_GUIDANCE_PURPOSE)\n return `- ${server.name} (${state})${purpose === '' ? '' : ` — ${purpose}`}`\n}\n\n/**\n * The flat inventory of the deferred surface: bare names only, sorted and\n * deduped, truncated to {@link MAX_GUIDANCE_HIDDEN_NAMES} with a `+N more`.\n * Descriptions and schemas are the expensive part, so the line carries names\n * only — the model picks the one it needs and runs a single targeted search\n * instead of rephrasing blind guesses. The sentence also states the\n * direct-call contract: deferral trims the assembled request list, it never\n * unregisters the tool, so a call by the exact full name still executes;\n * searching the name first is how the model sees the description and\n * parameters, not a gate.\n */\nfunction hiddenNamesLine(deferred: ReadonlySet<string>): string {\n const names = [...deferred].sort(compareNames)\n const shown = names.slice(0, MAX_GUIDANCE_HIDDEN_NAMES)\n const hidden = names.length - shown.length\n const list = hidden === 0 ? shown.join(', ') : `${shown.join(', ')} +${hidden} more`\n return (\n `On demand right now: ${list} — every one of them runs when called by its exact full ` +\n `name \\`mcp__<server>__<tool>\\`; search a name with \\`${SEARCH_TOOL_NAME}\\` first to see ` +\n 'its description and parameters.'\n )\n}\n\n/** The paragraph that turns \"a tool is missing\" into \"ask for it\". */\nfunction onDemandParagraph(offered: number, deferred: number): string {\n return (\n `${offered} of ${offered + deferred} MCP tool(s) are offered directly; the other ${deferred} ` +\n `are offered on demand — call \\`${SEARCH_TOOL_NAME}\\` with a keyword or a tool name (several ` +\n 'words are matched one by one), and a tool it activates becomes callable from the next ' +\n 'step. Search once with the best keywords you have; when the search reports no match, this ' +\n 'project mounts no such ' +\n 'tool — report the gap instead of rephrasing the search or guessing a name.'\n )\n}\n\n/**\n * The session-start \"most used\" line. The input arrives most-called first\n * (the seeded baseline's insertion order is the rank order), so the line\n * keeps that order and samples the top names before `+N more`.\n */\nfunction mostUsedLine(mostUsed: readonly string[]): string {\n const unique: string[] = []\n const seen = new Set<string>()\n for (const name of mostUsed) {\n const trimmed = name.trim()\n if (trimmed === '' || seen.has(trimmed)) continue\n seen.add(trimmed)\n unique.push(trimmed)\n }\n if (unique.length === 0) return ''\n const shown = unique.slice(0, MAX_GUIDANCE_MOST_USED)\n const hidden = unique.length - shown.length\n const list = hidden === 0 ? shown.join(', ') : `${shown.join(', ')} +${hidden} more`\n return (\n `Most used in this project's sessions, offered from the first step on: ${list} — ` +\n 'call them directly, no search needed.'\n )\n}\n\n/** Project label, or a neutral fallback for a blank/missing one. */\nfunction label(project: string | undefined): string {\n const value = project?.trim() ?? ''\n return value === '' ? 'this project' : value\n}\n\n/** Trim a purpose and bound it, so one server cannot crowd the section. */\nfunction shorten(text: string | undefined, max: number): string {\n const value = text?.trim() ?? ''\n if (value.length <= max) return value\n return `${value.slice(0, max - 1).replace(/\\s+$/, '')}…`\n}\n\n/** Final guard: cut at the last complete line and add an ellipsis. */\nfunction applyCap(text: string): string {\n if (text.length <= MAX_GUIDANCE_CHARS) return text\n const head = text.slice(0, MAX_GUIDANCE_CHARS - 1)\n const cut = head.lastIndexOf('\\n')\n const body = (cut === -1 ? head : head.slice(0, cut)).replace(/\\s+$/, '')\n return `${body}…`\n}\n\n/** Remove trailing path separators; a bare root collapses to an empty string. */\nfunction stripSeparators(path: string): string {\n return path.replace(/[\\\\/]+$/, '')\n}\n\nfunction compareNames(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0\n}\n\n/** Read a disposer from either a function or an object with `dispose()`. */\nfunction disposerOf(value: unknown): (() => void) | undefined {\n if (typeof value === 'function') return value as () => void\n if (typeof value === 'object' && value !== null) {\n const target = value as { dispose?: unknown }\n if (typeof target.dispose === 'function') {\n const dispose = target.dispose as () => void\n return () => {\n dispose.call(target)\n }\n }\n }\n return undefined\n}\n","/**\n * The local namespace of a project-declared MCP server.\n *\n * A profile-level `mcp-client` instance and a project document can declare the\n * same `serverName`. `dsh-mcp-client` reserves that name per scope, so only one\n * of them can mount — which is a lost server, not a bad declaration. This module\n * is the pure rule that gives the project's entry a second, local name instead\n * (`grafana-dev` → `p-grafana-dev`), so both toolsets stay in the model's hands\n * under names nobody has to guess at.\n *\n * The rule is a total function of the declared name, the prefix and the names\n * already taken, and it is the *only* place the alias is computed: the pass that\n * mounts the server, the row that reports it and the tool prefix the model sees\n * all read this answer, so they cannot drift apart.\n *\n * @module dsh-project-mcp/naming\n */\n\n/** The five characters a local prefix may carry, config or derived. */\nexport const MAX_LOCAL_PREFIX_LENGTH = 5\n\n/** The `serverName` cap `@deepseek-ai/dsh-mcp-client` enforces. */\nconst MAX_SERVER_NAME_LENGTH = 32\n\n/** A local prefix is a valid `serverName` head or it is nothing. */\nconst PREFIX_SHAPE = /^[A-Za-z0-9_-]+$/\n\n/**\n * Whether a value may serve as a local prefix.\n *\n * The routes and the loader schema both read an untrusted string, so the shape\n * is checked here rather than trusted: a prefix that carries a character\n * `serverName` does not allow would produce a server the registry rejects, and\n * an empty prefix is a request for the derived one, not an error.\n *\n * @param value - candidate prefix.\n * @returns `true` when it is empty or a valid prefix of at most five characters.\n */\nexport function isValidLocalPrefix(value: string): boolean {\n if (value === '') return true\n return value.length <= MAX_LOCAL_PREFIX_LENGTH && PREFIX_SHAPE.test(value)\n}\n\n/**\n * The prefix a project brings by itself: its own folder name.\n *\n * Used when the config names no prefix, so a conflict has an answer without a\n * setting. A folder that yields nothing usable — `/`, dots, digits only — has no\n * answer, and such a project keeps today's behaviour rather than a made-up name.\n *\n * @param projectRoot - absolute project root.\n * @returns up to five characters, or `undefined` when the folder yields none.\n */\nexport function deriveLocalPrefix(projectRoot: string): string | undefined {\n const folder = projectRoot.split(/[\\\\/]/).filter((part) => part !== '').pop()\n if (folder === undefined) return undefined\n const cleaned = folder\n .toLowerCase()\n .replace(/[^A-Za-z0-9_-]+/g, '-')\n // A `serverName` may not open with a digit, and neither may the prefix: a\n // folder `2fast-service` contributes `fast`, not `2fast`.\n .replace(/^[0-9]+-*/, '')\n .slice(0, MAX_LOCAL_PREFIX_LENGTH)\n // Trimmed after the cap as well, so a cut at a separator (`2fast-service`\n // capped to five) never leaves the trailing dash the cap exposed.\n .replace(/^-+|-+$/g, '')\n return cleaned || undefined\n}\n\n/**\n * The local name of one declaration: the prefix, then the declared name,\n * trimmed so the result fits the `serverName` cap.\n *\n * The declared name is what gets trimmed, never the prefix, because a truncated\n * prefix would collide across servers the user meant to tell apart.\n *\n * @param name - declared `serverName`.\n * @param prefix - local prefix, already known to be valid.\n * @returns a `serverName` of at most 32 characters.\n */\nexport function aliasOf(name: string, prefix: string): string {\n const head = `${prefix}-`\n return `${head}${name.slice(0, Math.max(1, MAX_SERVER_NAME_LENGTH - head.length))}`\n}\n\n/** One declaration considered for a local name. */\nexport interface ConflictNameInput {\n /** Declared `serverName`. */\n readonly name: string\n /** `true` when a live profile-level instance already owns that name. */\n readonly reserved: boolean\n}\n\n/** What {@link resolveConflictNames} is asked to name. */\nexport interface ResolveNamesInput {\n /** Every declaration of the project, in document order. */\n readonly entries: readonly ConflictNameInput[]\n /** Explicit local prefix; empty asks for the one derived from the project. */\n readonly prefix: string\n /** Project root, read only when `prefix` is empty. */\n readonly projectRoot?: string\n}\n\n/**\n * The local name of every declaration a profile-level instance shadows.\n *\n * Aliases are handed out in name order so the answer never depends on which\n * document was read first, and a candidate that is already owned — by another\n * declaration of this project, by the profile, or by an alias handed out a\n * moment ago — gets a numeric tail (`p-grafana-dev-2`) rather than stealing the\n * name. Names that conflict with nothing are absent from the map: the absence is\n * the honest answer \"this one mounts under the name it declared\".\n *\n * @param input - declarations, prefix and project root.\n * @returns declared name → local name, in name order; empty when nothing is shadowed.\n */\nexport function resolveConflictNames(input: ResolveNamesInput): Map<string, string> {\n const prefix = input.prefix !== '' ? input.prefix : deriveLocalPrefix(input.projectRoot ?? '')\n const aliases = new Map<string, string>()\n if (prefix === undefined || !isValidLocalPrefix(prefix) || prefix === '') return aliases\n const taken = new Set(input.entries.map((entry) => entry.name))\n const shadowed = input.entries.filter((entry) => entry.reserved).map((entry) => entry.name)\n // Sorted, so the numeric tail always lands on the same declaration.\n shadowed.sort()\n for (const name of shadowed) {\n let candidate = aliasOf(name, prefix)\n for (let tail = 2; taken.has(candidate); tail += 1) {\n candidate = aliasOf(`${name}-${tail}`, prefix)\n }\n taken.add(candidate)\n aliases.set(name, candidate)\n }\n return aliases\n}\n","/**\n * Durable per-project tool policy for `dsh-project-mcp`.\n *\n * The panel lets a user decide how one project's MCP tools are offered — never\n * defer (`direct`), do not offer them at all (`off`), or keep the shipped\n * on-demand presentation (`disclosure`) — and which tool names are pinned. That\n * decision is the same kind of state as the usage counters: remembered across\n * sessions and restarts in one versioned document under `$DSH_HOME`, written\n * atomically on a debounce, and never able to break a model request.\n *\n * The decision logic is pure ({@link policyFor}, {@link withMode},\n * {@link withPin}) and the document only sits behind {@link PolicyStore}, so the\n * model is testable without a filesystem. Absent file, absent project and absent\n * field all mean {@link DEFAULT_TOOL_POLICY}, so a broken or hand-edited\n * document can only ever fall back to the shipped behaviour.\n *\n * @module dsh-project-mcp/policy\n */\n\nimport { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { dshHome } from './discovery.ts'\nimport { DEFAULT_TOOL_POLICY } from './types.ts'\nimport type { ConflictChoice, ToolMode, ToolPolicy } from './types.ts'\n\n/** Current on-disk document version; another version is ignored, not migrated. */\nexport const POLICY_VERSION = 1\n\n/** Policy document name under `$DSH_HOME`, next to the usage counters. */\nexport const POLICY_FILE_NAME = 'dsh-project-mcp-policy.json'\n\n/** Every mode a request may store, in the order the type declares them. */\nexport const TOOL_MODES: readonly ToolMode[] = ['disclosure', 'direct', 'off']\n\n/** Policy of every project ever configured, keyed by project root. */\nexport type PolicyState = Record<string, ToolPolicy>\n\n/** The durable policy document as written to disk. */\nexport interface PolicyDocument {\n /** Document version; a reader that does not know it starts clean. */\n version: typeof POLICY_VERSION\n /** Policy of every project the user configured. */\n projects: PolicyState\n}\n\n/** The logger surface the store uses; a Cordis logger satisfies it. */\nexport interface PolicyLogger {\n /** Non-fatal report; the store never throws at its caller. */\n warn(message: string): void\n}\n\n/** Construction options for {@link PolicyStore}; production uses the defaults. */\nexport interface PolicyStoreOptions {\n /** Absolute document path; defaults to `$DSH_HOME/dsh-project-mcp-policy.json`. */\n file?: string\n /** Debounce before a policy change reaches disk. */\n flushMs?: number\n /** Sink for a corrupt document or a failed write. */\n logger?: PolicyLogger\n}\n\n/** Debounce that keeps a panel click off the filesystem. */\nconst DEFAULT_FLUSH_MS = 1_000\n\n/**\n * The shape `@deepseek-ai/dsh-mcp-client` accepts for a reserved `serverName`,\n * narrowed to a name that may open a stored conflict key: a key that fails it is\n * a hand-edit or an array index, and never a server this host could mount.\n */\nconst SERVER_NAME_SHAPE = /^[A-Za-z_][A-Za-z0-9_-]*$/\n\n/**\n * Whether a value is one of the modes this plugin stores.\n *\n * The routes read an untrusted JSON body, so the check belongs here rather than\n * in the type system: a body that names an unknown mode is refused instead of\n * being stored as a mode no assembly would know what to do with.\n *\n * @param value - parsed request or document value.\n * @returns `true` when the value is a {@link ToolMode}.\n */\nexport function isToolMode(value: unknown): value is ToolMode {\n return typeof value === 'string' && (TOOL_MODES as readonly string[]).includes(value)\n}\n\n/**\n * The policy in force for one project.\n *\n * Pure: it reads the state only. An absent project is the shipped default rather\n * than an error, which is what makes a fresh install behave exactly like the\n * plugin before this document existed.\n *\n * @param state - policies before the read.\n * @param projectRoot - project root the policy belongs to.\n * @returns the stored policy, or {@link DEFAULT_TOOL_POLICY} when there is none.\n */\nexport function policyFor(state: PolicyState, projectRoot: string): ToolPolicy {\n return state[projectRoot] ?? DEFAULT_TOOL_POLICY\n}\n\n/**\n * Whether a value is one of the conflict answers this plugin stores.\n *\n * Read from an untrusted route body and from a hand-edited document, so the\n * check lives here: a body that names an answer no build knows is refused\n * instead of stored.\n *\n * @param value - parsed request or document value.\n * @returns `true` when the value is a {@link ConflictChoice}.\n */\nexport function isConflictChoice(value: unknown): value is ConflictChoice {\n return value === 'profile' || value === 'local' || value === 'native'\n}\n\n/**\n * What the user chose for one contested `serverName`.\n *\n * Pure: the absence of a choice is the shipped answer — the profile's instance\n * keeps the name — so a project that never saw the toggle behaves exactly like\n * the plugin before the choice existed.\n *\n * @param state - policies before the read.\n * @param projectRoot - project root the name belongs to.\n * @param server - contested `serverName` as declared.\n * @returns the stored answer, or `'profile'` when there is none.\n */\nexport function choiceFor(state: PolicyState, projectRoot: string, server: string): ConflictChoice {\n return aliasesOf(state[projectRoot])[server] ?? 'profile'\n}\n\n/** The choices of one policy, treating an absent map and an empty one alike. */\nexport function aliasesOf(policy: ToolPolicy | undefined): Readonly<Record<string, ConflictChoice>> {\n return policy?.aliases ?? {}\n}\n\n/**\n * Store one contested name's answer, keeping the mode, the pins and the other\n * names.\n *\n * Pure and idempotent. Choosing the profile again *removes* the entry rather\n * than storing `'profile'`, because the absence already says exactly that: a\n * document that kept both spellings of one answer would grow with every click\n * and hand-edit its way into disagreeing with itself.\n *\n * @param state - policies before the change.\n * @param projectRoot - project root the name belongs to.\n * @param server - contested `serverName` as declared.\n * @param choice - the answer to store.\n * @returns a new state, or the input when the answer did not change.\n */\nexport function withConflictChoice(\n state: PolicyState,\n projectRoot: string,\n server: string,\n choice: ConflictChoice,\n): PolicyState {\n const current = policyFor(state, projectRoot)\n if (choiceFor(state, projectRoot, server) === choice) return state\n const aliases: Record<string, ConflictChoice> = { ...aliasesOf(current) }\n if (choice === 'profile') delete aliases[server]\n else aliases[server] = choice\n return { ...state, [projectRoot]: normalizePolicy(current.mode, current.pins, aliases) }\n}\n\n/**\n * Store one project's mode, keeping its pins.\n *\n * Pure and idempotent: storing the mode already in force returns the input state\n * unchanged, so a panel that resubmits a switch does not schedule a write.\n *\n * @param state - policies before the change.\n * @param projectRoot - project root the mode applies to.\n * @param mode - the mode to store.\n * @returns a new state, or the input when the mode did not change.\n */\nexport function withMode(state: PolicyState, projectRoot: string, mode: ToolMode): PolicyState {\n const current = policyFor(state, projectRoot)\n if (current.mode === mode) return state\n return { ...state, [projectRoot]: normalizePolicy(mode, current.pins, aliasesOf(current)) }\n}\n\n/**\n * Pin or unpin one name of one project.\n *\n * Pins keep the order the user pinned them in — a pin is appended, an unpin\n * removes exactly that name — because the panel lists them in that order and a\n * re-pin after an unpin must not silently jump to the front. A name is never\n * validated against the project's mounts here: a pin of a tool the project does\n * not mount yet is kept, so a declaration that comes back finds its pin again.\n *\n * @param state - policies before the change.\n * @param projectRoot - project root the pin belongs to.\n * @param tool - public registry name, eg `mcp__tglider__workspace`.\n * @param pinned - `true` pins it, `false` unpins it.\n * @returns a new state, or the input when the list did not change.\n */\nexport function withPin(\n state: PolicyState,\n projectRoot: string,\n tool: string,\n pinned: boolean,\n): PolicyState {\n const current = policyFor(state, projectRoot)\n const has = current.pins.includes(tool)\n if (pinned === has) return state\n const pins = pinned ? [...current.pins, tool] : current.pins.filter((name) => name !== tool)\n return { ...state, [projectRoot]: normalizePolicy(current.mode, pins, aliasesOf(current)) }\n}\n\n/**\n * One policy entry as the store keeps it: the mode and the pins always, the\n * choices only when there are any.\n *\n * Written through here rather than assembled field by field at each call site,\n * so the state the panel changes and the document that is flushed have one\n * shape — an entry that carries an empty map in memory but not on disk would be\n * a difference nothing could explain from the file.\n *\n * @param mode - mode in force.\n * @param pins - pinned names, in order.\n * @param aliases - choices per contested name.\n * @returns the entry to store.\n */\nfunction normalizePolicy(\n mode: ToolMode,\n pins: readonly string[],\n aliases: Readonly<Record<string, ConflictChoice>>,\n): ToolPolicy {\n return Object.keys(aliases).length === 0 ? { mode, pins } : { mode, pins, aliases }\n}\n\n/**\n * Parse one durable policy document.\n *\n * Anything this version cannot trust — malformed JSON, a foreign shape, or\n * another version — yields `undefined` so the caller starts from the shipped\n * default instead of throwing. A project entry is sanitized field by field: an\n * unknown mode falls back to `disclosure` and a pin list keeps only non-empty\n * deduplicated strings, so a hand-edited document cannot poison a request.\n *\n * @param text - raw document contents.\n * @returns the policies, or `undefined` when the document is not usable.\n */\nexport function parsePolicyDocument(text: string): PolicyState | undefined {\n let value: unknown\n try {\n value = JSON.parse(text)\n } catch {\n return undefined\n }\n if (!isRecord(value)) return undefined\n if (value.version !== POLICY_VERSION) return undefined\n if (!isRecord(value.projects)) return undefined\n const projects: PolicyState = {}\n for (const [root, raw] of Object.entries(value.projects)) {\n const policy = sanitizePolicy(raw)\n if (policy === undefined) continue\n // An entry that carries no mode, no pin and no choice says nothing the\n // default would not say, so it is dropped rather than written back.\n if (\n policy.mode === DEFAULT_TOOL_POLICY.mode &&\n policy.pins.length === 0 &&\n Object.keys(aliasesOf(policy)).length === 0\n ) {\n continue\n }\n projects[root] = policy\n }\n return projects\n}\n\n/**\n * The durable policy: one versioned document under `$DSH_HOME`, loaded once when\n * the plugin applies and written atomically on a debounce.\n *\n * Every failure mode is non-fatal by design, exactly like the counters. A\n * missing, unreadable, foreign or older-version document starts from the shipped\n * default, and a write that fails is logged and forgotten, because a panel click\n * must never fail on a policy that could not be stored.\n */\nexport class PolicyStore {\n private state: PolicyState\n private timer: ReturnType<typeof setTimeout> | undefined\n private dirty = false\n private disposed = false\n private readonly file: string\n private readonly flushMs: number\n private readonly logger: PolicyLogger | undefined\n\n /** @param options - document path, debounce and log sink. */\n constructor(options: PolicyStoreOptions = {}) {\n this.file = options.file ?? join(dshHome(), POLICY_FILE_NAME)\n this.flushMs = options.flushMs ?? DEFAULT_FLUSH_MS\n this.logger = options.logger\n this.state = this.load()\n }\n\n /** Policy of one project root; the shipped default when it has none. */\n forProject(projectRoot: string): ToolPolicy {\n return policyFor(this.state, projectRoot)\n }\n\n /** Store one project's mode and schedule the debounced write. */\n setMode(projectRoot: string, mode: ToolMode): ToolPolicy {\n this.commit(withMode(this.state, projectRoot, mode))\n return policyFor(this.state, projectRoot)\n }\n\n /** Pin or unpin one name of one project and schedule the debounced write. */\n setPin(projectRoot: string, tool: string, pinned: boolean): ToolPolicy {\n this.commit(withPin(this.state, projectRoot, tool, pinned))\n return policyFor(this.state, projectRoot)\n }\n\n /**\n * Store which of two conflicting declarations one name shows and schedule the\n * debounced write.\n *\n * Durable on purpose: the answer is what the user decided about their project,\n * not what one session happened to mount, so it survives the restart that\n * would otherwise bring the profile's instance back unopposed.\n */\n setConflictChoice(\n projectRoot: string,\n server: string,\n choice: ConflictChoice,\n ): ToolPolicy {\n this.commit(withConflictChoice(this.state, projectRoot, server, choice))\n return policyFor(this.state, projectRoot)\n }\n\n /** Write the policy atomically now. Best effort: it never throws. */\n flush(): void {\n if (!this.dirty) return\n const document: PolicyDocument = { version: POLICY_VERSION, projects: this.state }\n const temporary = `${this.file}.${process.pid}.tmp`\n try {\n mkdirSync(dirname(this.file), { recursive: true })\n writeFileSync(temporary, `${JSON.stringify(document, undefined, 2)}\\n`, 'utf8')\n renameSync(temporary, this.file)\n this.dirty = false\n } catch (error) {\n this.logger?.warn(\n `project-mcp: writing the tool policy to ${this.file} failed: ${errorText(error)}`,\n )\n }\n }\n\n /**\n * Cancel the pending write, flush what is dirty, and stop storing. Safe to\n * call more than once; the plugin fiber calls it on disposal.\n */\n dispose(): void {\n if (this.timer !== undefined) {\n clearTimeout(this.timer)\n this.timer = undefined\n }\n if (this.disposed) return\n this.disposed = true\n this.flush()\n }\n\n /** Adopt a state a pure change produced, and schedule the write when it moved. */\n private commit(next: PolicyState): void {\n if (this.disposed || next === this.state) return\n this.state = next\n this.dirty = true\n if (this.timer !== undefined) return\n this.timer = setTimeout(() => {\n this.timer = undefined\n this.flush()\n }, this.flushMs)\n this.timer.unref?.()\n }\n\n private load(): PolicyState {\n let text: string\n try {\n text = readFileSync(this.file, 'utf8')\n } catch {\n return {}\n }\n const state = parsePolicyDocument(text)\n if (state === undefined) {\n this.logger?.warn(\n `project-mcp: ignoring the tool policy in ${this.file} (unreadable or unsupported version); starting from the default`,\n )\n return {}\n }\n return state\n }\n}\n\n/** Sanitize one project entry; `undefined` when it is not even a record. */\nfunction sanitizePolicy(value: unknown): ToolPolicy | undefined {\n if (!isRecord(value)) return undefined\n const pins: string[] = []\n if (Array.isArray(value.pins)) {\n for (const pin of value.pins) {\n if (typeof pin !== 'string' || pin === '' || pins.includes(pin)) continue\n pins.push(pin)\n }\n }\n const aliases: Record<string, ConflictChoice> = {}\n if (isRecord(value.aliases)) {\n for (const [server, choice] of Object.entries(value.aliases)) {\n // The profile is what an absent entry means, so storing it would only\n // duplicate the default; an answer this build does not know is dropped.\n // A key that is no `serverName` at all — empty, or a bare index — is a\n // hand-edit or an array that JSON turned into an object, and is dropped\n // with the answer it carried.\n if (!SERVER_NAME_SHAPE.test(server) || !isConflictChoice(choice) || choice === 'profile') continue\n aliases[server] = choice\n }\n }\n return normalizePolicy(isToolMode(value.mode) ? value.mode : DEFAULT_TOOL_POLICY.mode, pins, aliases)\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction errorText(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n","/**\n * F-19 forwarding bridge: one `mcp-client` per project, a thin definition per\n * session.\n *\n * A preset composition mounts each session's tools from its own preset subtree,\n * and `agent-presets` binds every composed agent's scope key to the preset's\n * standing key *before* the agent is published. `dsh-scope` binds a key to one\n * parent exactly once, so the project's scope can never join that session's\n * chain — `bindScopeParent` throws, and the runtime's only remaining option was\n * to mount the same declarations again under the session's own scope: one child\n * process per session.\n *\n * The bridge takes the other path. The project keeps its one instance mounted in\n * the project's own scope; a session whose chain cannot reach that scope gets a\n * *forwarding* definition registered in its own layer instead. The forwarder\n * carries the project tool's model-facing surface, and each call resolves the\n * project's live definition by name and runs it:\n *\n * ```\n * project scope session scope (per session)\n * ┌────────────────────────┐ ┌──────────────────────────────────┐\n * │ mcp-client instance │ │ register(\"mcp__a__run\") ──────┐ │\n * │ register(\"mcp__a__run\")│◄────────┼── get(\"mcp__a__run\", project) │ │\n * │ execute(args, exec) │ │ → projectDefinition.execute │ │\n * └────────────────────────┘ └──────────────────────────────────┘\n * ```\n *\n * The resolution is by name at call time, not a captured definition object,\n * because `mcp-client` swaps its whole tool generation on every `tools/list`\n * refresh: a captured definition would keep executing a disposed generation.\n *\n * One session owns one live batch of forwarders, and {@link ForwardBatch} keeps\n * it level with the project's live set: the set is re-read on every trigger,\n * the batch is replaced as a whole (released before the replacement is\n * registered), and the re-entry every registration forces on the sync through\n * `tools/change` is owned rather than left to tear the batch down. Because that\n * event is emitted once per entry registered and once per entry disposed, the\n * subscription takes {@link ForwardBatch.note} — which folds a whole burst into\n * one queued pass — and never {@link ForwardBatch.sync}, whose work belongs to\n * the frame that asked for it.\n *\n * The module is import-free of `@deepseek-ai/dsh-tools` on purpose, exactly like\n * {@link ./activation.ts}: the registry, definition and schema surfaces are\n * described by the minimal structural types below, so the plugin stays\n * installable in a deployment that does not carry the tools package.\n *\n * @module dsh-project-mcp/bridge\n */\n\n/**\n * Minimal structural view of one model-facing content block.\n *\n * Deliberately open: every block the harness vocabulary carries has a `type` and\n * its own fields, so this is a supertype of all of them. That is what lets a\n * project definition typed against the real `ContentBlock` be copied into a\n * forwarder without a cast at the seam.\n */\nexport interface TextBlockLike {\n /** Block discriminant, eg `text`. */\n readonly type: string\n /** Every other block field, unread here. */\n readonly [key: string]: unknown\n}\n\n/**\n * Minimal structural view of one model-facing tool schema.\n *\n * It is the shape of `ctx.tools.schemas(scope)` entries, described locally\n * because `@deepseek-ai/dsh-tools` is a peer this plugin does not import.\n */\nexport interface BridgeToolSchema {\n /** Public registry name, eg `mcp__alpha__run`. */\n readonly name: string\n /** Model-facing description. */\n readonly description: string\n /** JSON Schema object arguments. */\n readonly parameters: Record<string, unknown>\n}\n\n/**\n * Minimal structural view of one registered tool definition.\n *\n * Every field except `execute` is carried over from the project's definition\n * verbatim — copied as a whole (`forwarder` spreads the definition), never by\n * enumerating the fields this module happens to know, so the forwarding entry is\n * indistinguishable from the original to everything that reads a definition:\n * schema projection, presentation metadata and callbacks, the concurrency\n * classifier, the timeout budget, the output renderer and the last-mile\n * `finalizeContent` the registry snapshots from the definition the session\n * resolves.\n */\nexport interface ForwardableDefinition extends BridgeToolSchema {\n /** Canonical output contract: schema plus model-facing renderer. */\n readonly output: {\n /** Enforced JSON Schema of the canonical value `execute` returns. */\n readonly schema: Record<string, unknown>\n /**\n * Project the canonical value onto model-facing content.\n * @param args - parsed call arguments.\n * @param value - the validated canonical value.\n * @returns the content blocks the model sees.\n */\n render(args: unknown, value: never): readonly TextBlockLike[]\n /**\n * Optional presentation projection, preserved so a call renders the same\n * card through either layer.\n * @param args - parsed call arguments.\n * @param value - the validated canonical value.\n * @returns the presentation metadata.\n */\n presentationMeta?(args: unknown, value: never): unknown\n }\n /** Cooperative timeout budget, preserved for the timeout policy wrapper. */\n readonly timeoutMs?: number\n /**\n * Deferred-loading request, owned by the presentation rather than by the\n * project.\n *\n * The harness projects this flag onto the model-facing schema\n * (`projectToolSchema`), and an adapter that understands it (the shipped\n * `dsh-llm-pi-ai` route omits such a schema from the wire request) then leaves\n * the definition out of the model's tool list while the registry keeps the\n * tool admitted for dispatch — a tool the model does not see but can still\n * call by its exact full name. It is set on the forwarder, never copied from\n * the project, because which of a session's tools are offered is this plugin's\n * presentation decision.\n */\n readonly deferLoading?: true\n /**\n * Pure sibling-overlap classifier. Preserved: a forwarder that dropped it\n * would make every forwarded call exclusive while the project tool is\n * parallel-safe.\n * @param args - parsed call arguments.\n * @returns whether this call may join a parallel group.\n */\n isConcurrencySafe?(args: unknown): boolean\n /**\n * Last-mile transform of the model-facing content, preserved.\n *\n * The registry snapshots this from the definition the *session* resolves —\n * which is the forwarder, not the project's entry — and calls it once per\n * normalized outcome. A forwarder that dropped it would silently degrade\n * every provider result that relies on it: an MCP result's stored images, for\n * one, would arrive as the adapter's plain text fallback.\n * @param exec - the execution identity, passed through unchanged.\n * @param result - the normalized outcome before materialization.\n * @returns replacement content, or `undefined` to preserve the current one.\n */\n finalizeContent?(exec: unknown, result: unknown): readonly TextBlockLike[] | undefined\n /**\n * Pending-state presentation, preserved so a forwarded call renders the same\n * card as the project's own entry.\n * @param args - parsed call arguments.\n * @returns the presentation intent, or `undefined` for the generic card.\n */\n presentCall?(args: unknown): unknown\n /**\n * Completed-state presentation, preserved for the same reason.\n * @param args - parsed call arguments.\n * @param result - the durable result projection.\n * @returns the presentation intent, or `undefined` to keep the pending one.\n */\n presentResult?(args: unknown, result: unknown): unknown\n /**\n * Run one accepted call.\n * @param args - parsed call arguments.\n * @param exec - execution identity, cancellation, and context deferral.\n * @returns the canonical value declared by `output.schema`.\n */\n execute(args: unknown, exec: never): Promise<unknown>\n}\n\n/**\n * The registry surface the bridge reads: one scoped lookup and one scoped\n * schema probe.\n *\n * `get(name, scope)` is the registry's public lookup and `schemas(scope)` its\n * public schema projection (`@deepseek-ai/dsh-tools` `ToolRuntime`); passing the\n * project's scope key reads the project's own layer and its ancestors, which is\n * where the shared instance registered its tools.\n */\nexport interface BridgeRegistryLike {\n /**\n * Resolve one tool as one scope sees it.\n * @param name - registered tool name.\n * @param scope - viewing scope key; omitted reads the global view.\n * @returns the visible definition, or `undefined` when none is.\n */\n get(name: string, scope?: object): ForwardableDefinition | undefined\n /**\n * Project one scope's visible definitions onto their model-facing schemas.\n * @param scope - viewing scope key; omitted reads the global view.\n * @returns one schema per visible tool, in registry order.\n */\n schemas(scope?: object): readonly BridgeToolSchema[]\n}\n\n/**\n * The registration context slices the bridge touches.\n *\n * A session's scope context is passed in, so `register` files every entry into\n * that session's own layer — the one layer this session owns, where the name is\n * visible to itself and to nobody else.\n */\nexport interface BridgeContextLike {\n /** Resolve one service, the injection-free read the plugin already uses. */\n get(name: string): unknown\n}\n\n/** Options for {@link forwardProjectTools}. */\nexport interface ForwardProjectToolsOptions {\n /** Session-scope context; every forwarder is registered through it. */\n readonly ctx: BridgeContextLike\n /** Project scope key whose definitions are executed. */\n readonly project: object\n /** Names to forward, as {@link projectToolNames} resolved them. */\n readonly names: readonly string[]\n /**\n * Names this pass forwards as deferred, so their schemas stay out of the\n * model's tool list while the registry keeps them callable. Absent defers\n * none, which is what a session with nothing hidden gets.\n * @param name - one forwarded name.\n * @returns whether the forwarder of that name carries `deferLoading`.\n */\n readonly deferred?: (name: string) => boolean\n /** Registry lookup used to resolve the live project definition per call. */\n readonly registry: BridgeRegistryLike\n}\n\n/**\n * Marker a forwarder carries, naming the definition it delegates to.\n *\n * The harness's registry has no \"forwarded\" concept and needs none — this is\n * addressed only to a test double standing in for the registry, which must tell\n * a forwarder from one of the session's own tools to resolve a call the way the\n * registry would.\n */\nexport const FORWARDED_TO = Symbol('dsh-project-mcp.forwarded-to')\n\n/**\n * Build one forwarding definition over a project's live definition.\n *\n * The schema fields are copied once, at registration time; the executable\n * delegate is resolved per call, so a project re-sync (which disposes and\n * re-registers every tool) never leaves a forwarder pointing at a dead\n * generation. Calling the project's definition directly — rather than\n * dispatching through the registry — is deliberate: the outer call already\n * traversed the policy pipeline under this session's identity, and a second\n * dispatch would apply pre-execute listeners and guards twice.\n * @param project - the definition to forward, read for its surface.\n * @param lookup - resolves the current project definition of this name.\n * @param deferred - whether this forwarder asks for deferred loading, so the\n * model's tool list leaves it out while the registry keeps it callable.\n * @returns the definition to register in a session's layer.\n */\nfunction forwarder(\n project: ForwardableDefinition,\n lookup: () => ForwardableDefinition | undefined,\n deferred: boolean,\n): ForwardableDefinition {\n // The marker rides outside the definition's own surface: it is addressed to a\n // test double standing in for the registry, never to the harness.\n return Object.assign(\n {\n // Every field the project declared rides along verbatim, including the\n // ones this module never reads — `finalizeContent`, `presentCall`,\n // `presentResult`, and whatever a future provider adds. Enumerating them\n // is what silently lost `dsh-mcp-client`'s finalizer: the registry takes\n // it from the definition the session resolves, which is this one.\n ...project,\n // After the spread, because the presentation decides this flag and the\n // project has no say in it. A forwarder that is not deferred carries no\n // flag at all rather than `deferLoading: false`, which is not part of the\n // harness's schema vocabulary.\n ...deferred ? { deferLoading: true as const } : {},\n async execute(args: unknown, exec: never): Promise<unknown> {\n const live = lookup()\n if (live === undefined) {\n throw new Error(`the project's \"${project.name}\" is no longer registered; the shared instance was released or replaced`)\n }\n return await live.execute(args, exec)\n },\n },\n { [FORWARDED_TO]: project },\n )\n}\n\n/**\n * Register one thin definition per name in the session's layer.\n *\n * A name the session already resolves to a definition of its own is skipped:\n * registering over it would either shadow the session's registration (if the\n * session's own layer holds it) or throw on a duplicate, and either way the\n * session's own tool is the one it should call.\n * @param options - session context, project key, names, and registry lookup.\n * @returns the exact releaser that drops every forwarder this call added.\n */\nexport function forwardProjectTools(options: ForwardProjectToolsOptions): () => void {\n // `ctx.get(name)` rather than `ctx.tools`: the session's scope context is a\n // raw extended context (the runtime mints it with `createScope`, not with a\n // plugin that injects `tools`), and a dot-read there throws\n // `cannot get property \"tools\" without inject`.\n const tools = options.ctx.get('tools') as {\n register(definition: ForwardableDefinition): () => void\n }\n const disposes: (() => void)[] = []\n for (const name of options.names) {\n const project = options.registry.get(name, options.project)\n if (project === undefined) continue\n try {\n disposes.push(tools.register(forwarder(\n project,\n () => options.registry.get(name, options.project),\n options.deferred?.(name) === true,\n )))\n } catch {\n // A duplicate in this session's own layer is the session's own tool: it\n // keeps the name, and the bridge steps aside rather than failing a mount.\n continue\n }\n }\n let released = false\n return () => {\n if (released) return\n released = true\n for (const dispose of disposes.reverse()) {\n try {\n dispose()\n } catch {\n // Disposal is idempotent at the registry, and a failure here must not\n // keep the remaining forwarders registered.\n }\n }\n }\n}\n\n/**\n * The names to forward, and how to register one batch of them.\n *\n * Both are read fresh on every pass: `names` because a server publishing a late\n * `tools/list` (or dropping one) is the ordinary life of a project, and\n * `register` because a pass can be requested from inside a pass.\n */\nexport interface ForwardBatchOptions {\n /**\n * The project's live tool names, probed on every pass.\n *\n * `undefined` reports a probe that failed: it says nothing about what the\n * project publishes, so the batch it could not describe is the batch that\n * stays live.\n * @returns the names this session should forward, or `undefined` on failure.\n */\n readonly names: () => readonly string[] | undefined\n /**\n * The names this session presents as deferred — hidden from the model's tool\n * list while the registry keeps them callable — read once on every pass.\n *\n * A pass whose names matched but whose deferred set moved still re-registers:\n * `deferLoading` is baked into the definition at registration, so the flag a\n * schema carries is exactly the flag its forwarder was registered with.\n * Absent defers none, which is the presentation of a session with nothing\n * hidden.\n * @returns the deferred names, or none.\n */\n readonly deferred?: () => readonly string[]\n /**\n * Register one batch of forwarders over the session's layer, which this call\n * reaches empty-handed: the batch it replaces is released first.\n * @param names - the names to forward, in registry order.\n * @param deferred - the names of this batch that carry `deferLoading`.\n * @returns the exact releaser that drops the whole batch.\n */\n readonly register: (names: readonly string[], deferred: ReadonlySet<string>) => () => void\n /**\n * Report a failure thrown by a pass this batch ran on its own.\n *\n * A pass requested by {@link ForwardBatch.note} runs off the caller's stack:\n * the registry call that announced the change has already returned, and so\n * has every frame that could have propagated the failure. Without this the\n * batch would go quiet — no forwarder, and no trace of why.\n * @param error - what the scheduled pass threw.\n */\n readonly onError?: (error: unknown) => void\n}\n\n/**\n * How many synchronous passes one {@link ForwardBatch.sync} may run.\n *\n * Two is the ordinary ceiling: a pass that replaced the batch is re-entered once\n * by its own announcements and short-circuits on the second round, and a pass\n * that found the set unchanged exits on the first. The extra room is for a set\n * that genuinely moved while the batch was registering — and the ceiling itself\n * is what stops a registry that keeps moving under the batch from holding the\n * event loop for as long as it likes.\n */\nexport const MAX_SYNC_PASSES = 4\n\n/**\n * One session's live forwarding batch, kept level with the project's live tools.\n *\n * The registry announces every registration by emitting `tools/change`\n * synchronously from inside the insertion, and a bridged session is subscribed\n * to exactly that event (`src/runtime.ts`, `installBridge`). A pass therefore\n * re-enters itself once per forwarder it registers. Nothing else owns that\n * re-entry, and left unowned it tears the batch down: the nested pass finds a\n * batch still being built, releases it, and registers a second copy of it —\n * which the live first copy refuses as a duplicate. A bridge that steps aside\n * for a duplicate (it must, for the session's own tools) then drops those names\n * silently, and a full pass records `namesIn` as the whole set, so the loss is\n * frozen for every later pass. That is the first defect this class exists to\n * close.\n *\n * So: a pass requested from inside a pass only marks the batch dirty, and the\n * frame that owns the batch runs one more pass when it is complete — which is\n * also how a project set that changed mid-registration is still honoured. And\n * the old batch is released **before** the new one is registered, because one\n * layer holds one entry per name: registering over a live batch would refuse\n * every name it already had.\n *\n * Owning the re-entry is not enough on its own, and the shape of the event is\n * why. Replacing a batch of N entries announces 2·N changes — one per disposal\n * and one per registration — and the event carries no origin, so every session\n * watching the stream runs a pass for every one of them, and every pass begins\n * by projecting the project's whole catalog, which the registry answers by deep\n * cloning each visible definition's JSON schema. The registry per pass is what\n * makes that cost real: one MCP generation swap was measured holding the event\n * loop for the full 54 seconds of a CPU profile (47% of its samples inside this\n * sync, 52% in the collector the projections feed), while the plugin's own\n * frames were 0.46% of it. So {@link note} is the seat a `tools/change`\n * subscription takes, not {@link sync}: a change that arrives during a pass is\n * absorbed by it, and a burst that arrives between passes costs **one** queued\n * pass however many events it carries. A stale forwarder is safe in the window\n * that opens — it resolves the project entry at call time and fails closed when\n * there is none (`forwarder`) — and every read path brings the batch level\n * before it reads, so a reader never waits for the queue.\n */\nexport class ForwardBatch {\n /** The names the live batch was registered for; `undefined` before the first pass. */\n #namesIn: readonly string[] | undefined = undefined\n /** The names the live batch registered as deferred; `undefined` with no live batch. */\n #deferredIn: ReadonlySet<string> | undefined = undefined\n /** Disposer of the live registration batch; `undefined` while none is live. */\n #release: (() => void) | undefined = undefined\n /** Whether an owning frame is inside {@link sync}, registering right now. */\n #building = false\n /** Whether a pass asked for while {@link #building} still needs a run. */\n #again = false\n /** Whether a scheduled pass is already waiting for a burst of changes. */\n #queued = false\n\n constructor(private readonly options: ForwardBatchOptions) {}\n\n /**\n * The names the live batch was registered for.\n *\n * `undefined` before the first successful pass, and again after a pass whose\n * registration failed: an unset state is what makes the next pass retry\n * rather than short-circuit on a set that never landed.\n */\n get namesIn(): readonly string[] | undefined {\n return this.#namesIn\n }\n\n /**\n * Bring the session's layer level with the project's live tool set, now.\n *\n * Cheap when it already is: an unchanged set short-circuits and leaves the\n * live batch — and its generation of definitions — untouched. Re-entrant\n * while registering, and bounded to {@link MAX_SYNC_PASSES} synchronous\n * rounds so no registry state can hold the caller's frame: see the class note.\n * @returns nothing; a failure from the probe or the registry propagates.\n */\n sync(): void {\n if (this.#building) {\n this.#again = true\n return\n }\n // A queued pass would read the very registry this one is about to read, so\n // it is dropped here rather than left to repeat the probe.\n this.#queued = false\n this.#building = true\n try {\n for (let pass = 0; pass < MAX_SYNC_PASSES; pass += 1) {\n this.#again = false\n this.#syncOnce()\n if (!this.#again) return\n }\n // Still moving after a full round: hand the rest to the queue. A registry\n // that keeps changing under the batch must not hold the caller's frame.\n this.#schedule(true)\n } finally {\n this.#building = false\n }\n }\n\n /**\n * Note that the registry changed, and bring the batch level — off this stack.\n *\n * This is the seat a `tools/change` subscription takes, and the reason it is\n * not {@link sync}: the event is emitted once per entry registered and once\n * per entry disposed, from inside the registry's own insertion and removal,\n * so one MCP generation swap is a burst of thousands. A change that arrives\n * while a pass is running is absorbed by that pass — it re-reads the set it is\n * replacing before it returns — and a burst that arrives between passes costs\n * one pass: the first queues, every later one folds into it.\n *\n * Nothing reads a stale layer for it. Every read path brings the batch level\n * first (`src/runtime.ts`, `mountedSchemas`), and the queued pass has run\n * before any turn that could read the layer at all.\n */\n note(): void {\n if (this.#building) {\n this.#again = true\n return\n }\n this.#schedule(false)\n }\n\n /**\n * Drop the live batch: the session keeps no forwarder, and the next\n * {@link sync} starts from nothing rather than amending a stale set.\n * Idempotent.\n *\n * The release announces itself (`tools/change`) once per entry, and the\n * session is subscribed to that event; a pass re-entered from there must not\n * resurrect the batch it is watching being dropped. So the guard is held for\n * the whole release, and the pass it queues is discarded rather than run.\n *\n * The guard is *held*, not taken: a drop that runs inside a pass — a detach\n * driven from a listener, a scope torn down under a registration — restores\n * the pass's own `building` rather than clearing it. Clearing it there would\n * let the next `tools/change` start a nested pass inside a frame that still\n * owns one, which is exactly the re-entry this class exists to own.\n */\n drop(): void {\n const building = this.#building\n this.#building = true\n try {\n this.#releaseBatch()\n } finally {\n this.#building = building\n this.#again = false\n this.#queued = false\n }\n }\n\n /**\n * Queue the one deferred pass a burst of changes needs.\n * @param yielding - run it on the timer queue rather than the microtask queue.\n * A pass that overran {@link MAX_SYNC_PASSES} asks for this: a chain of\n * microtasks still starves timers and I/O, a round of timers does not.\n */\n #schedule(yielding: boolean): void {\n if (this.#queued) return\n this.#queued = true\n const run = (): void => {\n if (!this.#queued) return\n this.#queued = false\n try {\n this.sync()\n } catch (error) {\n this.options.onError?.(error)\n }\n }\n if (yielding) setTimeout(run, 0)\n else queueMicrotask(run)\n }\n\n /** One pass: read the project's set, then replace the batch when it moved. */\n #syncOnce(): void {\n const names = this.options.names()\n if (names === undefined) return\n // A name that enters or leaves the deferred set is a definition change even\n // when the name set itself is identical: the flag is part of the schema the\n // registry projects, so a batch registered before the flip would keep\n // presenting the old answer for every later request.\n const deferred = new Set(this.options.deferred?.() ?? [])\n if (this.#namesIn !== undefined\n && sameNames(this.#namesIn, names)\n && sameNameSet(this.#deferredIn, deferred)) return\n // Released first, and deliberately — see the class note. Until the new batch\n // is registered the session's layer is empty for the length of one\n // synchronous call, which is the price of every forwarded name being free.\n try {\n this.#releaseBatch()\n } catch {\n // The registry's disposer is exact and idempotent, and a failure here must\n // not keep the new batch from registering.\n }\n this.#release = this.options.register(names, deferred)\n this.#namesIn = names\n this.#deferredIn = deferred\n }\n\n /**\n * Release the live batch and forget it.\n *\n * The fields are cleared before the disposer runs, so a throw leaves the batch\n * in the retryable empty state rather than half-released and half-claimed.\n */\n #releaseBatch(): void {\n const release = this.#release\n this.#release = undefined\n this.#namesIn = undefined\n this.#deferredIn = undefined\n release?.()\n }\n}\n\n/**\n * The project scope's tool names, restricted to the servers the project\n * actually mounted.\n *\n * The probe reads the PROJECT scope, not the session's: the shared instance\n * registered its tools there, so a session's own view would also carry its own\n * registrations (and could not tell them apart). `servers` keeps a name another\n * scope's server happens to publish from being forwarded.\n * @param project - project scope key whose view is probed.\n * @param schemas - reads one scope's visible schemas, as `ctx.tools.schemas`.\n * @param servers - server namespaces the project mounted.\n * @returns the tool names to forward, in registry order.\n */\nexport function projectToolNames(\n project: object,\n schemas: (scope: object) => readonly BridgeToolSchema[],\n servers: ReadonlySet<string>,\n): string[] {\n const names: string[] = []\n for (const schema of schemas(project)) {\n const match = /^mcp__([A-Za-z0-9_-]+?)__/.exec(schema.name)\n if (match === null) continue\n if (!servers.has(match[1] as string)) continue\n names.push(schema.name)\n }\n return names\n}\n\n/**\n * Whether two name lists are the same set in the same order.\n *\n * A sync is skipped when the project publishes exactly what the last one\n * forwarded: re-registering an unchanged batch would dispose and rebuild every\n * forwarder for nothing, and the registry announces each change to every\n * watcher.\n * @param left - the names the last sync forwarded.\n * @param right - the names this sync found.\n * @returns whether the two lists match entry for entry.\n */\nexport function sameNames(left: readonly string[], right: readonly string[]): boolean {\n return left.length === right.length && left.every((name, index) => name === right[index])\n}\n\n/**\n * Whether two deferred-name sets are the same set.\n *\n * The batch short-circuits a pass whose forwarded names did not move, and it\n * must not do that when the *deferred* subset moved instead: the flag rides in\n * the registered definition, so a stale batch presents a stale answer. Order\n * carries no meaning here, hence a set comparison rather than {@link sameNames}.\n * @param left - the deferred set of the live batch; `undefined` with no live batch.\n * @param right - the deferred set this pass read.\n * @returns whether the two describe the same names.\n */\nexport function sameNameSet(\n left: ReadonlySet<string> | undefined,\n right: ReadonlySet<string>,\n): boolean {\n if (left === undefined || left.size !== right.size) return false\n for (const name of right) if (!left.has(name)) return false\n return true\n}\n","/**\n * The plugin's own event ring, and its only owner.\n *\n * The Logs tab of the sidebar panel answers \"what happened to this project's\n * servers\" from the plugin's own lifecycle events — mounting, `is up`, stall,\n * unmount, failure — and from nothing else. The DSH log is deliberately not a\n * source: no foreign line can be attributed to one project, and attribution is\n * exactly what the tab promises (contract C1, decision 2 of the review).\n *\n * The ring is per project root and bounded by {@link LOG_RING_LIMIT}, the oldest\n * event evicted first. It is written from the single runtime point that already\n * writes the matching lifecycle line to the DSH log, so both readers see the\n * same facts and there is no second write path to keep in sync. The newest\n * {@link LOG_PAGE_SIZE} events travel inside the snapshot the tab is drawn from;\n * {@link page} is what \"show older\" asks for the rest.\n *\n * Nothing here touches the disk, and the clock belongs to the caller. A module\n * map rather than runtime state on purpose: the route handler ({@link module:dsh-project-mcp/ui})\n * answers `GET logs` without a runtime, and the panel and the runtime must read\n * one buffer. {@link record} never throws — a ring write must not fail the pass\n * that reported the event.\n *\n * @module dsh-project-mcp/logs\n */\n\nimport type { LogEvent } from './types.ts'\n\n/** Events one project's ring holds; the oldest is evicted past it. */\nexport const LOG_RING_LIMIT = 200\n\n/** Events one page carries: the snapshot's tail, and {@link page}'s default window. */\nexport const LOG_PAGE_SIZE = 50\n\n/**\n * One ring per project root, oldest event first.\n *\n * Kept per root because two projects of one host are two histories; the history\n * lives exactly as long as the process, since the panel's `Clear` is client-side\n * and there is no `Clear` route (contract C1).\n */\nconst rings = new Map<string, LogEvent[]>()\n\n/**\n * Add one event to its project's ring.\n *\n * Called from the runtime points that write the lifecycle line to the DSH log,\n * in addition to it. An event identical to one already held is dropped, so a\n * repeated pass can never make the tab show the same line twice. Total: a\n * malformed event or a ring bug is swallowed rather than thrown into the pass\n * that reported it.\n * @param event - the event to record; `message` is folded onto one line.\n */\nexport function record(event: LogEvent): void {\n try {\n if (typeof event.projectRoot !== 'string' || event.projectRoot === '') return\n const ring = ringOf(event.projectRoot)\n if (ring.some((existing) => sameEvent(existing, event))) return\n ring.push({ ...event, message: oneLine(event.message) })\n if (ring.length > LOG_RING_LIMIT) ring.splice(0, ring.length - LOG_RING_LIMIT)\n } catch {\n // Nothing a ring write can raise is worth failing the pass for.\n }\n}\n\n/**\n * The newest events of one project, oldest first.\n *\n * This is what a snapshot carries, and it hands out a copy: a reader that kept\n * the array could otherwise watch it change under a later pass.\n * @param projectRoot - project whose ring is read.\n * @param limit - how many of the newest events to return; clamped to\n * `1…{@link LOG_RING_LIMIT}`, {@link LOG_PAGE_SIZE} when omitted.\n * @returns the events, oldest first; empty for a project with no history.\n */\nexport function latest(projectRoot: string, limit: number = LOG_PAGE_SIZE): LogEvent[] {\n const ring = rings.get(projectRoot)\n if (ring === undefined) return []\n const size = clampLimit(limit)\n return ring.slice(Math.max(0, ring.length - size))\n}\n\n/**\n * One page of a project's history, for \"show older\".\n *\n * Without `before` the page is the newest `limit` events — the same window a\n * snapshot carries, which is what the tab asks for on a refresh. With `before`\n * it is the newest `limit` events strictly older than that instant: the cursor\n * is the `at` of the oldest event already on screen, so consecutive pages do\n * not overlap.\n * @param input - the project to read, and the optional window.\n * @param input.projectRoot - project whose ring is read.\n * @param input.before - exclusive cursor in epoch ms; `at < before` only.\n * @param input.limit - page size; clamped to `1…{@link LOG_RING_LIMIT}`,\n * {@link LOG_PAGE_SIZE} when omitted.\n * @returns the page, the ring's total size, and whether older events remain\n * beyond the page — `more` is true when the window had to cut the history short.\n */\nexport function page(input: { projectRoot: string; before?: number; limit?: number }): {\n events: LogEvent[]\n total: number\n more: boolean\n} {\n const ring = rings.get(input.projectRoot) ?? []\n const older = input.before === undefined ? ring : ring.filter((event) => event.at < (input.before as number))\n const events = older.slice(Math.max(0, older.length - clampLimit(input.limit)))\n return { events, total: ring.length, more: older.length > events.length }\n}\n\n/**\n * How many events one project's ring holds right now.\n * @param projectRoot - project whose ring is read.\n * @returns the count, `0` for a project with no history.\n */\nexport function countOf(projectRoot: string): number {\n return rings.get(projectRoot)?.length ?? 0\n}\n\n/**\n * How many events of one project's ring belong to one session.\n *\n * Events the lifecycle line itself attributes to a session — `mounting`, `is up`,\n * a stall — are counted here; a project-level event (a shared instance's unmount)\n * carries no session and is counted by no session.\n * @param projectRoot - project whose ring is read.\n * @param sessionId - agent (session) id to count.\n * @returns the count, `0` for a session that produced nothing.\n */\nexport function countForSession(projectRoot: string, sessionId: string): number {\n return (rings.get(projectRoot) ?? []).filter((event) => event.sessionId === sessionId).length\n}\n\n/**\n * Drop one project's history, or every project's, for tests.\n *\n * Not a route: the panel's `Clear` is client-side (contract C1), so nothing in\n * the product calls this — a test that asserts on a ring starts from no history.\n * @param projectRoot - project to forget; omitted forgets every project.\n */\nexport function clear(projectRoot?: string): void {\n if (projectRoot === undefined) rings.clear()\n else rings.delete(projectRoot)\n}\n\n/** The ring of one root, created empty on first use. */\nfunction ringOf(projectRoot: string): LogEvent[] {\n const existing = rings.get(projectRoot)\n if (existing !== undefined) return existing\n const ring: LogEvent[] = []\n rings.set(projectRoot, ring)\n return ring\n}\n\n/**\n * Whether two events are the same event, field by field. The project is the ring\n * they share, so it is the one field not compared here.\n */\nfunction sameEvent(left: LogEvent, right: LogEvent): boolean {\n return (\n left.at === right.at &&\n left.level === right.level &&\n left.sessionId === right.sessionId &&\n left.server === right.server &&\n left.message === right.message &&\n left.detail === right.detail\n )\n}\n\n/**\n * Fold a message onto one line, as {@link LogEvent.message} promises: the tab\n * renders a row per event, and a newline inside one would break the column.\n */\nfunction oneLine(message: string): string {\n return message.replace(/\\s*\\n\\s*/g, ' ').trim()\n}\n\n/**\n * A page size clamped to what the ring can serve: a caller cannot ask for more\n * than {@link LOG_RING_LIMIT} events, and a zero or a negative size is raised to\n * the one event every page is at least worth.\n */\nfunction clampLimit(limit: number | undefined): number {\n if (limit === undefined || !Number.isFinite(limit)) return LOG_PAGE_SIZE\n return Math.min(LOG_RING_LIMIT, Math.max(1, Math.trunc(limit)))\n}\n","/**\n * The plugin's event service: one publication point, and its consumers.\n *\n * A lifecycle fact used to be written three times by the runtime — a line in the\n * DSH log, the same fact into the ring (`src/logs.ts`), and the snapshot\n * announcement the panel watches. Three writes that had to agree. Here they are\n * one: the runtime publishes a {@link PluginEvent} through {@link emitEvent}, and\n * every reader is a subscriber —\n *\n * 1. the ring, subscribed here against {@link module:dsh-project-mcp/logs}\n * `record`, so the tab and the log are fed by one publication;\n * 2. the DSH log, subscribed by the runtime's own\n * {@link module:dsh-project-mcp/runtime} wiring through {@link logConsumer},\n * because only the runtime holds the host `ctx`;\n * 3. anything else a test or a later surface attaches through\n * {@link subscribeEvent}.\n *\n * Publication is synchronous and total: listeners run in subscription order, a\n * listener that throws is swallowed rather than failing the pass that reported\n * the event, and {@link emitEvent} never throws into its caller. The clock\n * belongs to the caller ({@link PluginEvent.at}), as it does in the ring, so a\n * test can pin an event to a moment.\n *\n * @module dsh-project-mcp/notifications\n */\n\nimport { record } from './logs.ts'\nimport type { LogLevel } from './types.ts'\n\n/**\n * One lifecycle event, as every consumer reads it.\n *\n * The same fields the ring keeps, because the ring is a subscriber — the tab\n * draws exactly the event this service published. The one field with two\n * readers is {@link PluginEvent.level}: the ring colours the row with it, and\n * the DSH log writes the line through the matching level method.\n */\nexport interface PluginEvent {\n /** When the event happened, epoch ms. */\n readonly at: number\n /** How serious it is, as the Logs tab colours it. */\n readonly level: LogLevel\n /** Project root the event belongs to; the ring is keyed by it. */\n readonly projectRoot: string\n /**\n * Session the event is attributed to. Set exactly when the lifecycle line it\n * mirrors names one — `mounting`, `is up`, a stall — and absent on a\n * project-level event such as a shared instance's unmount.\n */\n readonly sessionId?: string\n /** `serverName` the event is about; absent for an event with no server. */\n readonly server?: string\n /** One line, without the `project-mcp:` prefix the log line carries. */\n readonly message: string\n /** The three facts an error carries — the failure, the endpoint, the document. */\n readonly detail?: string\n /**\n * Wire code of {@link PluginEvent.message} (F-48), into the client's\n * `projectMcp.host` namespace. The prose fields stay byte-identical English\n * and remain the fallback: a consumer that never resolves codes — the DSH\n * log is one — reads exactly what it read before the code existed.\n */\n readonly code?: string\n /**\n * Flat params of {@link PluginEvent.code}; numbers stringify at emission. A\n * param whose name ends in `Code` (`reasonCode`, `sharingCode`) is itself a\n * wire code the client resolves two-level, substituting it under the plain\n * name.\n */\n readonly params?: Record<string, string>\n /** Wire code of {@link PluginEvent.detail}, the same additive companion. */\n readonly detailCode?: string\n /** Flat params of {@link PluginEvent.detailCode}. */\n readonly detailParams?: Record<string, string>\n /**\n * The DSH log line, when it says more than {@link PluginEvent.message}.\n *\n * `message` is what the tab lists one row per event; the line is what an\n * operator reads in the host log, and for two events it names what the row's\n * own columns already carry — the declaring path and the endpoint of a failed\n * mount, the server and the root of a release. The runtime passes the very\n * text the line had before the event existed, so the log is unchanged; absent\n * means `message` is the line.\n */\n readonly line?: string\n /**\n * Severity the DSH log writes this event under, when it differs from\n * {@link PluginEvent.level}.\n *\n * The tab's level is about the row — a release is a warning there, a failed\n * mount is an error — while the host log keeps the level the line always had\n * (`info` for the whole lifecycle except a failure or a stall, which are\n * `warn`). Two readers, two vocabularies: without this field, wiring the log\n * through the event would silently promote `unmounting` to `warn` and\n * `mount failed` to `error` in the operator's log. Absent means the host log\n * follows {@link PluginEvent.level}.\n */\n readonly logLevel?: LogLevel\n}\n\n/** One subscriber, told the whole event at publication time. */\nexport type PluginEventListener = (event: PluginEvent) => void\n\n/**\n * The one level method this module calls on a host logger.\n *\n * Structural on purpose: the runtime's `ctx.logger` satisfies it, and so does a\n * test double with no error method.\n */\nexport type LoggerMethod = (format: unknown, ...parameters: unknown[]) => void\n\n/**\n * The host logger as this module needs it: the level methods, and nothing else.\n *\n * Deliberately not `LoggerService` — the service has a call signature and a\n * `debug` method this module never uses, so declaring only the three makes a\n * partial double (`{ warn }`) a valid logger.\n */\nexport interface PluginLoggerLike {\n error?: LoggerMethod\n info?: LoggerMethod\n warn?: LoggerMethod\n}\n\n/** Listeners in subscription order; publication walks a copy of it. */\nconst listeners = new Set<PluginEventListener>()\n\n/**\n * Publish one plugin event to every subscriber, and swallow what they raise.\n *\n * Called from the runtime points that used to write the DSH log and the ring by\n * hand, and the only publication point there is. Listeners run synchronously in\n * subscription order — so a consumer registered first sees the event first —\n * over a snapshot of the set, which keeps a listener that unsubscribes itself\n * (or subscribes another) during the walk from corrupting it.\n * @param event - the event to publish.\n */\nexport function emitEvent(event: PluginEvent): void {\n for (const listener of [...listeners]) {\n try {\n listener(event)\n } catch {\n // A consumer's failure is not the reporting pass's failure: the ring\n // already promises the same, and one broken reader must not cost the\n // others the event.\n }\n }\n}\n\n/**\n * Subscribe a consumer.\n *\n * The ring is one such consumer, installed here for the life of the module; a\n * host logger and a test are others. Subscribing the same listener twice keeps\n * the one entry it already has, so a wrapper re-registered around the same touch\n * does not make the event arrive twice, and unsubscribing is idempotent:\n * {@link PluginEventListener} is unique in the set, and removing what is absent\n * is a no-op.\n * @param listener - told every event published from now on.\n * @returns the disposer that stops it; safe to call more than once.\n */\nexport function subscribeEvent(listener: PluginEventListener): () => void {\n listeners.add(listener)\n return () => {\n listeners.delete(listener)\n }\n}\n\n/**\n * Whether a listener is subscribed right now.\n *\n * A diagnostic for the subscription itself: the disposer returns nothing, so\n * this is how a caller — a test proving that a disposer detached its listener,\n * or memory after a re-mount — reads the fact without counting a publication.\n * @param listener - the listener to look up.\n * @returns `true` while it is subscribed.\n */\nexport function isSubscribed(listener: PluginEventListener): boolean {\n return listeners.has(listener)\n}\n\n/**\n * The DSH log as a consumer: one line per event, under the plugin's own prefix\n * and level.\n *\n * Returns the listener rather than attaching anything itself: the logger lives\n * on the host context, which only the runtime holds, so the runtime owns the\n * subscription (and drops it when it is disposed). The line is `project-mcp: `\n * plus {@link logText}, so the text a reader has seen does not change; the level\n * method is {@link PluginEvent.logLevel} when the event names one, because that\n * is the level the line has always had, and the tab's own level otherwise — and\n * a partial logger gets the nearest method it has ({@link levelMethod}).\n * @param logger - host logger whose level methods carry the line.\n * @returns the listener to subscribe; detach it with the disposer\n * {@link subscribeEvent} returned.\n */\nexport function logConsumer(logger: PluginLoggerLike): PluginEventListener {\n return (event) => {\n const method = levelMethod(logger, event.logLevel ?? event.level)\n if (method === undefined) return\n method(`project-mcp: ${logText(event)}`)\n }\n}\n\n/**\n * The one line the DSH log writes for an event.\n *\n * An event that named the line it replaces carries it ({@link PluginEvent.line}),\n * so the log is byte-for-byte what it was. The rest compose it: where the\n * lifecycle line named the server in front of the message, the event carries the\n * name as its own field, because the tab draws it as a column and does not repeat\n * it in the message — `mounting`, `is up` and `unmounting` put the name back in\n * here. The stall and the failure already open their message with the name (it is\n * the first line of the row's detail).\n * @param event - the event to render.\n * @returns the line, without the `project-mcp: ` prefix.\n */\nfunction logText(event: PluginEvent): string {\n if (event.line !== undefined) return event.line\n const server = event.server\n if (server !== undefined) {\n if (event.message.startsWith('mounting ')) return `${server}: ${event.message}`\n if (event.message.startsWith('is up — ')) return `${server} ${event.message}`\n if (event.message.startsWith('unmounting — ')) {\n return `unmounting ${server} in ${event.projectRoot} — ${event.message.slice('unmounting — '.length)}`\n }\n }\n return event.message\n}\n\n/**\n * The logger method one level writes through; `up` is an info-level success.\n *\n * A partial logger falls back to the levels it does have — `error`, then `warn`,\n * then `info` — rather than losing the line: the harnesses that publish only\n * `warn` are the reason, and a deployment's logger has all three.\n */\nfunction levelMethod(logger: PluginLoggerLike, level: LogLevel): LoggerMethod | undefined {\n if (level === 'warn') return logger.warn ?? logger.info\n if (level === 'error') return logger.error ?? logger.warn ?? logger.info\n return logger.info\n}\n\n/**\n * The ring as a consumer, installed once for the module.\n *\n * Subscribed here rather than called by the runtime so the runtime has exactly\n * one write path: it publishes, and the tab and the DSH log both read that one\n * publication. {@link record} stays the ring's only writer, and stays total —\n * it is written to be called from an event the pass must not fail over.\n */\nsubscribeEvent((event) => {\n record(event)\n})\n","/**\n * Durable per-project MCP usage counters for `dsh-project-mcp`.\n *\n * The host half counts the `tools/result` events whose tool belongs to a server\n * it mounted itself, keyed by project root and `serverName`. The numbers are\n * remembered across sessions and restarts in one versioned document under\n * `$DSH_HOME`, written atomically on a debounce so a tool call never waits for\n * the filesystem, and a failed write is logged and dropped rather than allowed\n * to disturb the call.\n *\n * Counting itself is pure ({@link recordUsage}) and the document only sits\n * behind {@link UsageStore}, so the model is testable without a filesystem.\n *\n * @module dsh-project-mcp/usage\n */\n\nimport { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { dshHome } from './discovery.ts'\nimport type { ServerUsage, SessionUsage } from './types.ts'\n\n/** Current on-disk document version; another version is ignored, not migrated. */\nexport const USAGE_VERSION = 1\n\n/** Counter document name under `$DSH_HOME`. */\nexport const USAGE_FILE_NAME = 'dsh-project-mcp-usage.json'\n\n/** Counters keyed by project root, then by `serverName`. */\nexport type UsageState = Record<string, Record<string, ServerUsage>>\n\n/** The durable counter document as written to disk. */\nexport interface UsageDocument {\n /** Document version; a reader that does not know it starts clean. */\n version: typeof USAGE_VERSION\n /** Counters of every project ever seen. */\n projects: UsageState\n}\n\n/** One registry call, before it is attributed to a mounted server. */\nexport interface UsageCall {\n /** Project root the calling agent resolved to. */\n projectRoot: string\n /** Server names this plugin currently mounts for that project. */\n servers: ReadonlySet<string>\n /**\n * Public tool name delivered by `tools/result`, ie `mcp__<serverName>__<name>`.\n * A name the registry had to truncate to the function-name budget keeps this\n * prefix, so the server is still identifiable.\n */\n toolName: string\n /** `true` when the settled result carried an error. */\n isError: boolean\n /** Epoch milliseconds of the call. */\n at: number\n /**\n * Session the call belongs to: the id of the agent that made it.\n *\n * The host resolves an agent from the call's own event, and every other\n * surface of this plugin already calls that id the session id (a `LogEvent`,\n * a `SessionSnapshot`). Counting is therefore attributable without a second\n * lookup, which is what lets the panel answer \"and how much of this is mine?\"\n * (F-34).\n */\n sessionId: string\n}\n\n/** One counted call, attributed to a project and a server this plugin mounted. */\nexport interface UsageEvent {\n /** Project root the calling agent resolved to. */\n projectRoot: string\n /** `serverName` this plugin mounted for that project. */\n serverName: string\n /**\n * Tool name as declared by the server, ie without the `mcp__<serverName>__`\n * prefix. A name the registry truncated to its function-name budget cannot be\n * reversed, so its key is the public suffix the registry published.\n */\n tool: string\n /** `true` when the settled result carried an error. */\n isError: boolean\n /** Epoch milliseconds of the call. */\n at: number\n /** Session (agent) id this call is counted under, besides the project total. */\n sessionId: string\n}\n\n/** The `tools/result` execution view this module reads. */\nexport interface ToolResultEventLike {\n /** Public tool name, `mcp__<serverName>__<name>`. */\n readonly name: string\n /** Agent the call ran for; absent on a host-level call, which is not counted. */\n readonly agent?: { readonly id: string } | undefined\n}\n\n/** The settled `tools/result` outcome view this module reads. */\nexport interface ToolResultLike {\n /** `true` when the call settled as an error. */\n readonly isError: boolean\n}\n\n/** Everything {@link observeToolResults} needs, injected so it is testable. */\nexport interface ToolResultObserverOptions {\n /** Register the `tools/result` listener; returns its disposer. */\n on(\n name: 'tools/result',\n handler: (exec: ToolResultEventLike, result: ToolResultLike) => undefined,\n ): (() => void) | undefined\n /** Resolve the project and the mounted servers of the agent that made a call. */\n mountsFor(agentId: string): { projectRoot: string; servers: ReadonlySet<string> } | undefined\n /** Durable store the attributed calls are recorded in. */\n store: Pick<UsageStore, 'record'>\n /** Clock override; defaults to `Date.now`. */\n now?: () => number\n}\n\n/** The logger surface the store uses; a Cordis logger satisfies it. */\nexport interface UsageLogger {\n /** Non-fatal report; the store never throws at its caller. */\n warn(message: string): void\n}\n\n/** Construction options for {@link UsageStore}; production uses the defaults. */\nexport interface UsageStoreOptions {\n /** Absolute document path; defaults to `$DSH_HOME/dsh-project-mcp-usage.json`. */\n file?: string\n /** Debounce before a recorded call reaches disk. */\n flushMs?: number\n /** Sink for a corrupt document or a failed write. */\n logger?: UsageLogger\n}\n\n/** Debounce that keeps a tool call off the filesystem. */\nconst DEFAULT_FLUSH_MS = 1_000\n\n/**\n * Attribute one registry tool name to a server this plugin mounted.\n *\n * The prefix is never parsed blindly: only mounted names are candidates, and\n * the longest match wins, so a mounted `alpha_` is never shadowed by a mounted\n * `alpha` when both publish tools into one scope.\n *\n * @param toolName - public registry name, `mcp__<serverName>__<name>`.\n * @param servers - names this plugin mounted for the calling agent's project.\n * @returns the matched `serverName`, or `undefined` for a foreign tool.\n */\nexport function matchServer(toolName: string, servers: ReadonlySet<string>): string | undefined {\n let match: string | undefined\n for (const server of servers) {\n if (!toolName.startsWith(`mcp__${server}__`)) continue\n if (match === undefined || server.length > match.length) match = server\n }\n return match\n}\n\n/**\n * Attribute one registry call, or `undefined` when no server this plugin\n * mounted for the project claims the name.\n * @param call - the raw `tools/result` view plus the caller's mounts.\n * @returns the counted event, ready for {@link recordUsage}.\n */\nexport function usageEventFor(call: UsageCall): UsageEvent | undefined {\n const serverName = matchServer(call.toolName, call.servers)\n if (serverName === undefined) return undefined\n return {\n projectRoot: call.projectRoot,\n serverName,\n tool: call.toolName.slice(`mcp__${serverName}__`.length),\n isError: call.isError,\n at: call.at,\n sessionId: call.sessionId,\n }\n}\n\n/**\n * Count one call into the state.\n *\n * Pure: it reads and returns counters only, touching no filesystem, clock or\n * logger, so the model is testable on its own.\n *\n * @param state - counters before the call.\n * @param event - one attributed call.\n * @returns a new state carrying the increment; `lastUsedAt` moves and is set\n * only on a success, while a failure keeps the previous stamp.\n */\nexport function recordUsage(state: UsageState, event: UsageEvent): UsageState {\n const project = state[event.projectRoot] ?? {}\n const previous = project[event.serverName]\n const tools: Record<string, number> = { ...previous?.tools }\n tools[event.tool] = (tools[event.tool] ?? 0) + 1\n const lastUsedAt = event.isError ? previous?.lastUsedAt : new Date(event.at).toISOString()\n const sessions: Record<string, SessionUsage> = { ...previous?.sessions }\n const previousSession = sessions[event.sessionId]\n const sessionTools: Record<string, number> = { ...previousSession?.tools }\n sessionTools[event.tool] = (sessionTools[event.tool] ?? 0) + 1\n const sessionLastUsedAt = event.isError\n ? previousSession?.lastUsedAt\n : new Date(event.at).toISOString()\n sessions[event.sessionId] = {\n calls: (previousSession?.calls ?? 0) + 1,\n errors: (previousSession?.errors ?? 0) + (event.isError ? 1 : 0),\n tools: sessionTools,\n ...(sessionLastUsedAt === undefined ? {} : { lastUsedAt: sessionLastUsedAt }),\n }\n const usage: ServerUsage = {\n calls: (previous?.calls ?? 0) + 1,\n errors: (previous?.errors ?? 0) + (event.isError ? 1 : 0),\n tools,\n sessions,\n ...(lastUsedAt === undefined ? {} : { lastUsedAt }),\n }\n return {\n ...state,\n [event.projectRoot]: { ...project, [event.serverName]: usage },\n }\n}\n\n/**\n * Subscribe the durable counters to `tools/result`.\n *\n * Counting is per event, never deduplicated against a parent: a programmatic\n * sub-dispatch is its own call with its own result, while the enclosing\n * `run_code` carries a name no server claims, so each MCP call is counted\n * exactly once on either path.\n *\n * @param options - registry subscription, agent resolver, store and clock.\n * @returns the disposer that unregisters the listener.\n */\nexport function observeToolResults(options: ToolResultObserverOptions): () => void {\n const now = options.now ?? Date.now\n const listener = (exec: ToolResultEventLike, result: ToolResultLike): undefined => {\n const agentId = exec.agent?.id\n if (agentId === undefined) return undefined\n const mounts = options.mountsFor(agentId)\n if (mounts === undefined) return undefined\n const event = usageEventFor({\n projectRoot: mounts.projectRoot,\n servers: mounts.servers,\n toolName: exec.name,\n isError: result.isError,\n at: now(),\n sessionId: agentId,\n })\n if (event === undefined) return undefined\n options.store.record(event)\n return undefined\n }\n const dispose = options.on('tools/result', listener)\n return () => {\n dispose?.()\n }\n}\n\n/**\n * The durable counters: one versioned document under `$DSH_HOME`, loaded once\n * when the plugin applies and written atomically on a debounce.\n *\n * Every failure mode is non-fatal by design. A missing, unreadable, foreign or\n * older-version document starts clean, and a write that fails is logged and\n * forgotten, because a tool call must never fail on a counter that could not\n * be stored.\n */\nexport class UsageStore {\n private state: UsageState\n private timer: ReturnType<typeof setTimeout> | undefined\n private dirty = false\n private disposed = false\n private readonly file: string\n private readonly flushMs: number\n private readonly logger: UsageLogger | undefined\n\n /** @param options - document path, debounce and log sink. */\n constructor(options: UsageStoreOptions = {}) {\n this.file = options.file ?? join(dshHome(), USAGE_FILE_NAME)\n this.flushMs = options.flushMs ?? DEFAULT_FLUSH_MS\n this.logger = options.logger\n this.state = this.load()\n }\n\n /** Counters of one project root, or `undefined` when it has none yet. */\n forProject(projectRoot: string): Record<string, ServerUsage> | undefined {\n return this.state[projectRoot]\n }\n\n /** Count one attributed call and schedule the debounced write. */\n record(event: UsageEvent): void {\n if (this.disposed) return\n this.state = recordUsage(this.state, event)\n this.dirty = true\n if (this.timer !== undefined) return\n this.timer = setTimeout(() => {\n this.timer = undefined\n this.flush()\n }, this.flushMs)\n this.timer.unref?.()\n }\n\n /** Write the counters atomically now. Best effort: it never throws. */\n flush(): void {\n if (!this.dirty) return\n const document: UsageDocument = { version: USAGE_VERSION, projects: this.state }\n const temporary = `${this.file}.${process.pid}.tmp`\n try {\n mkdirSync(dirname(this.file), { recursive: true })\n writeFileSync(temporary, `${JSON.stringify(document, undefined, 2)}\\n`, 'utf8')\n renameSync(temporary, this.file)\n this.dirty = false\n } catch (error) {\n this.logger?.warn(\n `project-mcp: writing usage counters to ${this.file} failed: ${errorText(error)}`,\n )\n }\n }\n\n /**\n * Cancel the pending write, flush what is dirty, and stop counting. Safe to\n * call more than once; the plugin fiber calls it on disposal.\n */\n dispose(): void {\n if (this.timer !== undefined) {\n clearTimeout(this.timer)\n this.timer = undefined\n }\n if (this.disposed) return\n this.disposed = true\n this.flush()\n }\n\n private load(): UsageState {\n let text: string\n try {\n text = readFileSync(this.file, 'utf8')\n } catch {\n return {}\n }\n const state = parseUsageDocument(text)\n if (state === undefined) {\n this.logger?.warn(\n `project-mcp: ignoring usage counters in ${this.file} (unreadable or unsupported version); starting clean`,\n )\n return {}\n }\n return state\n }\n}\n\n/**\n * Parse one durable counter document.\n *\n * Anything this version cannot trust — malformed JSON, a foreign shape, or\n * another version — yields `undefined` so the caller starts clean instead of\n * throwing, and each counter is validated so a hand-edited document cannot\n * poison later arithmetic.\n *\n * @param text - raw document contents.\n * @returns the counters, or `undefined` when the document is not usable.\n */\nexport function parseUsageDocument(text: string): UsageState | undefined {\n let value: unknown\n try {\n value = JSON.parse(text)\n } catch {\n return undefined\n }\n if (!isRecord(value)) return undefined\n if (value.version !== USAGE_VERSION) return undefined\n if (!isRecord(value.projects)) return undefined\n return sanitizeProjects(value.projects)\n}\n\nfunction sanitizeProjects(raw: Record<string, unknown>): UsageState {\n const projects: UsageState = {}\n for (const [root, servers] of Object.entries(raw)) {\n if (!isRecord(servers)) continue\n const rows: Record<string, ServerUsage> = {}\n for (const [server, usage] of Object.entries(servers)) {\n const parsed = sanitizeUsage(usage)\n if (parsed !== undefined) rows[server] = parsed\n }\n if (Object.keys(rows).length > 0) projects[root] = rows\n }\n return projects\n}\n\nfunction sanitizeUsage(value: unknown): ServerUsage | undefined {\n if (!isRecord(value)) return undefined\n if (!isCount(value.calls) || !isCount(value.errors)) return undefined\n return {\n calls: value.calls,\n errors: value.errors,\n tools: countMap(value.tools),\n // The per-session split is carried through, not rebuilt: a reader that\n // dropped it would lose every session figure on the first restart, while\n // the project totals it kept looked perfectly healthy.\n ...sanitizeSessions(value.sessions),\n ...(typeof value.lastUsedAt === 'string' ? { lastUsedAt: value.lastUsedAt } : {}),\n }\n}\n\n/** A record of non-negative integer counts, with every other entry dropped. */\nfunction countMap(value: unknown): Record<string, number> {\n const counts: Record<string, number> = {}\n if (isRecord(value)) {\n for (const [name, count] of Object.entries(value)) {\n if (isCount(count)) counts[name] = count\n }\n }\n return counts\n}\n\n/** The `sessions` half of a stored record, as the `...` spread a caller wants. */\nfunction sanitizeSessions(value: unknown): { sessions?: Record<string, SessionUsage> } {\n if (!isRecord(value)) return {}\n const sessions: Record<string, SessionUsage> = {}\n for (const [id, usage] of Object.entries(value)) {\n const parsed = sanitizeSessionUsage(usage)\n if (parsed !== undefined) sessions[id] = parsed\n }\n return Object.keys(sessions).length === 0 ? {} : { sessions }\n}\n\nfunction sanitizeSessionUsage(value: unknown): SessionUsage | undefined {\n if (!isRecord(value)) return undefined\n if (!isCount(value.calls) || !isCount(value.errors)) return undefined\n return {\n calls: value.calls,\n errors: value.errors,\n tools: countMap(value.tools),\n ...(typeof value.lastUsedAt === 'string' ? { lastUsedAt: value.lastUsedAt } : {}),\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction isCount(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0\n}\n\nfunction errorText(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n","/**\n * Write half of the entry editor: every decision one save makes, plus the\n * atomic document write those decisions guard.\n *\n * The host and the browser half agree on the outcome through the contract\n * (`docs/design/contracts/write-path.md`): a save replaces `mcpServers[<server>]`\n * wholesale, keeps every other key of the document, normalizes the formatting\n * (two spaces, trailing newline) and never writes a value the editor could not\n * see. Everything here is pure except {@link writeDocument}, so the rules are\n * testable without a filesystem.\n *\n * @module dsh-project-mcp/write\n */\n\nimport { createHash, randomUUID } from 'node:crypto'\nimport { copyFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'\nimport { basename, dirname, join, resolve } from 'node:path'\nimport { DEFAULT_LOCAL_FILES } from './discovery.ts'\nimport { hasReference } from './parse.ts'\nimport type { EntryField, EntrySnapshot, WriteScope } from './types.ts'\n\n/** Characters of the SHA-256 digest published as a document revision. */\nconst REVISION_LENGTH = 16\n\n/**\n * Key names whose literal value is treated as a credential. The document is the\n * only place such a value exists, so the host shows the key and withholds the\n * value; a save keeps whatever the document declares for it.\n */\nconst SECRET_KEY_PATTERN =\n /(?:^|[^a-z0-9])(?:password|passwd|secret|token|credential|credentials|apikey|api[_-]?key|private[_-]?key|access[_-]?key|auth)/i\n\n/**\n * Keys the editor presents, whatever the transport.\n */\nconst COMMON_KEYS = ['type', 'transport', 'enabled', 'disabled', 'connectTimeoutMs'] as const\n\n/** Keys that belong to one transport alone; the other section is not modelled. */\nconst SECTION_KEYS: Record<'stdio' | 'streamable-http', readonly string[]> = {\n stdio: ['command', 'args', 'cwd', 'env'],\n 'streamable-http': ['url', 'headers'],\n}\n\n/** Every presented key, whichever transport an entry declares. */\nconst PRESENTED_KEYS = new Set([...COMMON_KEYS, ...SECTION_KEYS.stdio, ...SECTION_KEYS['streamable-http']])\n\n/**\n * Opaque content revision of one document.\n *\n * A save carries the revision the editor was built from, so a document changed\n * underneath the form is refused instead of merged. The value is a prefix of a\n * SHA-256 digest: stable for identical bytes, different for any change, and\n * carrying nothing about the content.\n * @param text - exact document bytes as read from disk.\n * @returns a short hexadecimal digest of the content.\n */\nexport function documentRevision(text: string): string {\n return createHash('sha256').update(text, 'utf8').digest('hex').slice(0, REVISION_LENGTH)\n}\n\n/** How one declaring document may be written, and why not when it may not. */\nexport interface WriteScopeInfo {\n /** Tier of the declaring document. */\n readonly scope: WriteScope\n /** One line saying why a write is unavailable, when one is. */\n readonly reason?: string\n /**\n * Stable wire code of `reason` (`projectMcp.host` namespace), for\n * client-side translation; the prose `reason` keeps its byte-identical\n * English and stays the fallback.\n */\n readonly blockedCode?: string\n /** Flat params of {@link blockedCode}. */\n readonly blockedParams?: Record<string, string>\n}\n\n/**\n * Which tier one declaring document belongs to.\n *\n * The two lists are the deployment's own: `projectDocuments` — the project\n * documents it reads (`localFiles`) — are always writable, and `globalDocuments`\n * — the ones its `globalFiles` names — are writable only with an explicit\n * per-write consent and a deployment that enables `allowGlobalWrite`. Anything\n * else (a profile document, a bundled one, an in-memory pseudo-path) is never\n * written.\n * @param document - absolute path of the declaring document.\n * @param projectRoot - project root the row belongs to.\n * @param options - the deployment's document lists and the `allowGlobalWrite` switch.\n * @returns the tier plus the blocking sentence, when there is one.\n */\nexport function writeScopeFor(\n document: string,\n projectRoot: string,\n options: {\n projectDocuments?: readonly string[]\n globalDocuments?: readonly string[]\n allowGlobalWrite?: boolean\n } = {},\n): WriteScopeInfo {\n const target = resolve(document)\n const projectDocuments = (options.projectDocuments ?? DEFAULT_LOCAL_FILES).map((path) =>\n resolve(projectRoot, path),\n )\n if (projectDocuments.includes(target)) return { scope: 'project' }\n const globalDocuments = (options.globalDocuments ?? []).map((path) => resolve(path))\n if (!globalDocuments.includes(target)) {\n const writable = [...projectDocuments, ...globalDocuments]\n // The prose is the fallback and never changes by a character; the code\n // and its flat params are the additive companions the client translates\n // (`projectMcp.host` namespace).\n const notConfigured = writable.length === 0\n return {\n scope: 'readonly',\n reason: notConfigured\n ? `${document} is not a document this deployment reads, and it configures none to write`\n : `${document} is not one of this deployment's MCP documents; only ${writable.join(', ')} can be written`,\n blockedCode: notConfigured ? 'write.blocked.notConfigured' : 'write.blocked.notWritable',\n blockedParams: notConfigured ? { document } : { document, writable: writable.join(', ') },\n }\n }\n if (options.allowGlobalWrite === true) return { scope: 'global' }\n return {\n scope: 'global',\n reason: `writing the global tier is disabled by this deployment (allowGlobalWrite: false); ${document} stays read-only here`,\n blockedCode: 'write.blocked.globalDisabled',\n blockedParams: { document },\n }\n}\n\n/** Raw `env`/`headers` keys whose declared value is answered outside the document. */\nexport interface CredentialKeys {\n /** Keys of the entry's `env` object. */\n readonly env?: ReadonlySet<string>\n /** Keys of the entry's `headers` object. */\n readonly headers?: ReadonlySet<string>\n}\n\n/** Mutable local view of {@link EntrySnapshot}, so the builder can assign fields. */\ninterface MutableEntry {\n transport: 'stdio' | 'streamable-http'\n command?: string\n args?: string[]\n cwd?: string\n env?: EntryField[]\n url?: string\n headers?: EntryField[]\n enabled?: boolean\n connectTimeoutMs?: number\n extra?: Record<string, unknown>\n}\n\n/**\n * Parse one declared entry into the body the editor is given.\n *\n * Every field is what the document declares: a resolved default (the project\n * root folded into `cwd`, for example) is never copied in, because a save\n * replaces the declaration, not the runtime config. A `env`/`headers` value is\n * handed over only when the document really holds it as a literal and the key\n * is not credential-shaped — otherwise the key is published with `masked` (and\n * `fromCredentials` when the project `.env` or the credentials file answered it)\n * and the value stays on the host.\n * @param declared - raw `mcpServers[<server>]` value as parsed from the document.\n * @param transport - transport of the parsed config, which decides the shape used.\n * @param credentials - key names per section that are answered outside the document.\n * @returns the entry body for the snapshot.\n */\nexport function buildEntrySnapshot(\n declared: unknown,\n transport: 'stdio' | 'streamable-http',\n credentials: CredentialKeys = {},\n): EntrySnapshot {\n const record = isRecord(declared) ? declared : {}\n const snapshot: MutableEntry = { transport }\n if (transport === 'stdio') {\n if (typeof record.command === 'string') snapshot.command = record.command\n const args = record.args\n if (Array.isArray(args) && args.every((item) => typeof item === 'string')) {\n snapshot.args = [...(args as string[])]\n }\n if (typeof record.cwd === 'string') snapshot.cwd = record.cwd\n const env = entryFields(record.env, credentials.env)\n if (env !== undefined) snapshot.env = env\n } else {\n if (typeof record.url === 'string') snapshot.url = visibleUrl(record.url)\n const headers = entryFields(record.headers, credentials.headers)\n if (headers !== undefined) snapshot.headers = headers\n }\n if (record.enabled === false || record.disabled === true) snapshot.enabled = false\n if (typeof record.connectTimeoutMs === 'number') {\n snapshot.connectTimeoutMs = record.connectTimeoutMs\n }\n const extra: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(record)) {\n // A key of the other transport is neither shown nor carried in `extra`:\n // {@link entryToDeclaration} keeps it from the declaration itself, so a\n // value the editor never saw cannot travel through the payload.\n if (PRESENTED_KEYS.has(key)) continue\n extra[key] = value\n }\n if (Object.keys(extra).length > 0) snapshot.extra = extra\n return snapshot\n}\n\n/**\n * Build the JSON object a save writes for one server.\n *\n * The declaration starts from the raw document entry, so keys the editor never\n * showed survive verbatim — including the other transport's section, which the\n * editor of the declared transport does not model and a switch drops on\n * purpose. `type`/`transport` keeps its declared spelling while the transport is\n * unchanged. `env`/`headers` follow the contract's three-way rule per key: a\n * masked key submitted without a `value` keeps the declared one, a key with a\n * `value` writes that value, and a declared key the submission omits is removed.\n * A key marked `fromCredentials` never writes the submitted value: the declared\n * text (usually a `${input:NAME}` reference) stays exactly as it is, so a\n * resolved secret can never reach the document.\n * @param entry - the entry body the panel submitted.\n * @param declared - raw `mcpServers[<server>]` value as parsed from the document.\n * @returns the declaration object to write in its place.\n */\nexport function entryToDeclaration(entry: EntrySnapshot, declared: unknown): Record<string, unknown> {\n const base: Record<string, unknown> = isRecord(declared) ? { ...declared } : {}\n const declaredUrl = typeof base.url === 'string' ? base.url : undefined\n const declaredEnv = stringRecord(base.env) ?? {}\n const declaredHeaders = stringRecord(base.headers) ?? {}\n const declaredTypeKey =\n typeof base.type === 'string' ? 'type' : typeof base.transport === 'string' ? 'transport' : undefined\n const declaredTypeValue = declaredTypeKey === undefined ? undefined : base[declaredTypeKey]\n const declaredType = declaredTransport(base)\n const sameTransport = declaredType === entry.transport\n\n for (const key of COMMON_KEYS) delete base[key]\n for (const key of SECTION_KEYS[entry.transport]) delete base[key]\n // A switched transport drops the other transport's keys with it; an unchanged\n // one keeps them, because the editor of this transport never modelled them.\n if (!sameTransport) {\n for (const key of [...SECTION_KEYS.stdio, ...SECTION_KEYS['streamable-http']]) delete base[key]\n }\n\n if (entry.extra !== undefined) {\n for (const [key, value] of Object.entries(entry.extra)) {\n if (PRESENTED_KEYS.has(key)) continue\n base[key] = value\n }\n }\n // `type`/`transport` is a presented key, but its declared spelling is kept\n // while the transport is unchanged (`sse`, for example, would otherwise be\n // rewritten as `streamable-http`).\n if (declaredTypeKey !== undefined && sameTransport) base[declaredTypeKey] = declaredTypeValue\n\n if (entry.transport === 'stdio') {\n if (entry.command !== undefined) base.command = entry.command\n if (entry.args !== undefined) base.args = [...entry.args]\n if (entry.cwd !== undefined) base.cwd = entry.cwd\n if (entry.env !== undefined) base.env = fieldsToRecord(entry.env, declaredEnv)\n } else {\n if (entry.url !== undefined) base.url = urlToWrite(entry.url, declaredUrl)\n if (entry.headers !== undefined) base.headers = fieldsToRecord(entry.headers, declaredHeaders)\n }\n if (entry.enabled === false) base.enabled = false\n if (entry.connectTimeoutMs !== undefined) base.connectTimeoutMs = entry.connectTimeoutMs\n return base\n}\n\n/**\n * A refusal {@link applyEntry} throws: the English message, byte-identical to\n * what the site threw before codes existed, plus the `projectMcp.host` wire\n * code and its flat params beside it (F-48). The save path catches it and\n * reuses the companions as its own `messageCode`/`messageParams`, so the\n * client translates the refusal instead of wrapping raw English.\n */\nexport class WriteDocError extends Error {\n constructor(\n message: string,\n /** The dotted wire code, into the client's `projectMcp.host` namespace. */\n readonly code: string,\n /** Flat params of the code, when it has any. */\n readonly params?: Record<string, string>,\n ) {\n super(message)\n this.name = 'WriteDocError'\n }\n}\n\n/**\n * Replace one entry in a document's text.\n *\n * Only `mcpServers[server]` changes: the rest of the server map and every other\n * key of the document are serialized back as they were, with two-space\n * indentation and a trailing newline.\n * @param documentText - current document bytes.\n * @param server - key inside `mcpServers` to replace.\n * @param declaration - object to write in its place.\n * @returns the full new document text.\n * @throws {@link WriteDocError} when the text is not valid JSON or holds no\n * `mcpServers` object.\n */\nexport function applyEntry(\n documentText: string,\n server: string,\n declaration: Record<string, unknown>,\n): string {\n let root: unknown\n try {\n root = JSON.parse(documentText) as unknown\n } catch (error) {\n throw new WriteDocError(`the document is not valid JSON: ${errorText(error)}`, 'write.doc.invalidJson', {\n error: errorText(error),\n })\n }\n if (!isRecord(root)) throw new WriteDocError('the document is not a JSON object', 'write.doc.notObject')\n const servers = root.mcpServers\n if (!isRecord(servers)) throw new WriteDocError('the document has no \"mcpServers\" object', 'write.doc.noMcpServers')\n const next = { ...servers, [server]: declaration }\n return `${JSON.stringify({ ...root, mcpServers: next }, null, 2)}\\n`\n}\n\n/**\n * Write one document so that a failure at any step leaves it exactly as it was.\n *\n * Order: a `<document>.bak` copy of the current bytes first, then the new text\n * into a temporary file in the same directory, then a `rename` over the\n * document. The `rename` is the only operation that touches the original path,\n * so a failure while copying or while writing the temporary file cannot leave\n * half a document behind; a failed write drops the temporary file and rethrows.\n * @param document - absolute path of the document to replace.\n * @param text - the full new content.\n * @throws when the backup, the temporary write or the rename fails.\n */\nexport function writeDocument(document: string, text: string): void {\n copyFileSync(document, `${document}.bak`)\n const temporary = join(dirname(document), `.${basename(document)}.${randomUUID()}.tmp`)\n try {\n writeFileSync(temporary, text, 'utf8')\n renameSync(temporary, document)\n } catch (error) {\n try {\n unlinkSync(temporary)\n } catch {\n // The temporary file was never created, or is already gone.\n }\n throw error\n }\n}\n\n/**\n * URL as the editor sees it: a query string or fragment can carry a credential\n * (`?token=…`), so it is dropped from the panel. A save that leaves the visible\n * URL untouched keeps the declared one, query included.\n * @param url - declared or submitted endpoint.\n * @returns the endpoint without its query string or fragment.\n */\nexport function visibleUrl(url: string): string {\n const index = url.search(/[?#]/)\n return index === -1 ? url : url.slice(0, index)\n}\n\n/** The URL a declaration writes: keep the declared query when unchanged. */\nfunction urlToWrite(submitted: string, declaredUrl: string | undefined): string {\n if (declaredUrl !== undefined && visibleUrl(declaredUrl) === submitted) return declaredUrl\n return submitted\n}\n\n/** The three-way rule of one `env`/`headers` section, applied to one record. */\nfunction fieldsToRecord(\n fields: readonly EntryField[],\n declared: Record<string, string>,\n): Record<string, string> {\n const result: Record<string, string> = {}\n for (const field of fields) {\n const declaredValue = declared[field.key]\n if (field.fromCredentials === true) {\n // Never write an externally answered value: the declared text stays.\n if (declaredValue !== undefined) result[field.key] = declaredValue\n continue\n }\n if (field.value !== undefined) {\n result[field.key] = field.value\n continue\n }\n // No value at all: a masked key keeps what the document declares, so an\n // editor that cannot see a secret can never erase or replace it. A shape\n // with neither `value` nor `masked` has nothing to contribute either, and\n // is kept for the same reason — removal is expressed by omitting the key.\n if (declaredValue !== undefined) result[field.key] = declaredValue\n }\n return result\n}\n\n/** One `env`/`headers` section as entry fields, values masked where needed. */\nfunction entryFields(\n record: unknown,\n credentials: ReadonlySet<string> | undefined,\n): EntryField[] | undefined {\n if (!isRecord(record)) return undefined\n const fields: EntryField[] = []\n for (const [key, value] of Object.entries(record)) {\n if (typeof value !== 'string') return undefined\n if (credentials?.has(key) === true) {\n fields.push({ key, masked: true, fromCredentials: true })\n continue\n }\n // A `${...}` reference is resolved on the host and is not a literal the\n // document holds, so its value is withheld as well.\n if (SECRET_KEY_PATTERN.test(key) || hasReference(value)) {\n fields.push({ key, masked: true })\n continue\n }\n fields.push({ key, value })\n }\n return fields\n}\n\n/**\n * Transport a declaration names, normalized the way `parse.ts` reads it: an\n * explicit `type`/`transport` wins, otherwise the presence of `url` decides.\n */\nfunction declaredTransport(record: Record<string, unknown>): 'stdio' | 'streamable-http' {\n const raw = record.type ?? record.transport\n if (typeof raw === 'string') {\n const normalized = raw.toLowerCase()\n if (normalized === 'stdio') return 'stdio'\n if (normalized === 'http' || normalized === 'streamable-http' || normalized === 'sse') {\n return 'streamable-http'\n }\n }\n return record.url !== undefined ? 'streamable-http' : 'stdio'\n}\n\n/** Flat string map, or `undefined` when the value is not one. */\nfunction stringRecord(value: unknown): Record<string, string> | undefined {\n if (!isRecord(value)) return undefined\n const result: Record<string, string> = {}\n for (const [key, item] of Object.entries(value)) {\n if (typeof item !== 'string') return undefined\n result[key] = item\n }\n return result\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction errorText(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n","/**\n * Project-scoped MCP mounting runtime.\n *\n * Isolation model: every live agent (session) resolves its own working\n * directory to a project root, and the servers declared by that project are\n * mounted **once for the project** inside a Cordis scope minted for it\n * (`createScope(hostCtx, projectKey)`), exactly the pattern the in-box\n * browser-use runtime uses for MCP servers. Each session additionally gets its\n * own scope, parented to its project's (`bindScopeParent(agent, projectKey)`):\n * a session sees its project's layer through the scope chain, which is how one\n * child process serves every session of that project — subagents included —\n * while a session of another project never resolves it. Because mcp-client\n * reserves a `serverName` per registration scope, two projects may declare the\n * same name without a conflict, and the plugin's own teardown disposes every\n * scope it minted: the project scope when its last holder releases it, so a\n * shared instance goes away on exactly the trigger a per-session one did.\n *\n * @module dsh-project-mcp/runtime\n */\n\nimport { readFileSync, statSync, watch } from 'node:fs'\nimport type { FSWatcher } from 'node:fs'\nimport { homedir } from 'node:os'\nimport * as mcpClient from '@deepseek-ai/dsh-mcp-client'\nimport { bindScopeParent, createScope, scopeOf } from '@deepseek-ai/dsh-scope'\nimport type { Scope, ScopeParentBinding } from '@deepseek-ai/dsh-scope'\nimport type { Context } from '@deepseek-ai/cordis'\nimport { ForwardBatch, forwardProjectTools, projectToolNames } from './bridge.ts'\nimport type { BridgeContextLike, BridgeRegistryLike } from './bridge.ts'\nimport {\n DEFAULT_ACTIVATION_ENABLED,\n DEFAULT_ACTIVATION_MIN_CALLS,\n DEFAULT_ACTIVATION_SEEDED,\n DEFAULT_TOOL_BUDGET_CHARS,\n DEFAULT_TOOL_IDLE_MS,\n SEARCH_TOOL_NAME,\n autoPresentedNames,\n createActivationState,\n createAutoOfferState,\n installActivation,\n noteUse,\n overToolBudget,\n presentedNames,\n pruneIdle,\n schemaChars,\n seedFromUsage,\n surfaceChars,\n toolsFor,\n} from './activation.ts'\nimport type {\n ActivationContextLike,\n ActivationState,\n AutoOfferState,\n ToolSchemaLike,\n} from './activation.ts'\nimport {\n configDirectories,\n findProjectRoot,\n globalConfigPaths,\n localConfigPaths,\n projectEnvPaths,\n readEnvFile,\n readSecrets,\n} from './discovery.ts'\nimport {\n DEFAULT_GUIDANCE_ENABLED,\n buildGuidance,\n installGuidance,\n projectLabel,\n} from './guidance.ts'\nimport type { GuidanceContextLike, GuidanceServer } from './guidance.ts'\n// The volatile key list lives at the entry (`src/index.ts`) because the schema\n// declares it; the import cycles back here, but it is read only inside\n// `applyLiveConfig`, long after both modules finished evaluating.\nimport { VOLATILE_CONFIG_KEYS } from './index.ts'\nimport { LOG_PAGE_SIZE, countForSession, countOf, latest } from './logs.ts'\nimport { emitEvent, logConsumer, subscribeEvent } from './notifications.ts'\nimport type { PluginEvent } from './notifications.ts'\nimport {\n SERVER_NAME_PATTERN,\n extractServerMap,\n mergeEntries,\n parseDocument,\n referencesCredentials,\n slugifyServerName,\n} from './parse.ts'\nimport type { ParsedEntry, ParseIssue, ResolveContext } from './parse.ts'\nimport { isValidLocalPrefix, resolveConflictNames } from './naming.ts'\nimport { aliasesOf, isConflictChoice, isToolMode } from './policy.ts'\nimport type { ConflictRequest, PinRequest, PolicyRequest, SaveErrorCode, SaveRequest } from './shared.ts'\nimport { DEFAULT_TOOL_POLICY } from './types.ts'\nimport type {\n ConfiguredFile,\n ConflictChoice,\n EntrySnapshot,\n McpSnapshot,\n ProjectSnapshot,\n PresentationOwner,\n ServerConflict,\n ServerRow,\n ServerStatus,\n ServerUsage,\n SessionSnapshot,\n SessionTools,\n SnapshotChange,\n SnapshotIssue,\n ToolFacts,\n ToolField,\n ToolMode,\n ToolPolicy,\n ToolReason,\n WriteScope,\n} from './types.ts'\nimport { matchServer } from './usage.ts'\nimport {\n applyEntry,\n buildEntrySnapshot,\n documentRevision,\n entryToDeclaration,\n visibleUrl,\n WriteDocError,\n writeDocument,\n writeScopeFor,\n} from './write.ts'\nimport type { CredentialKeys, WriteScopeInfo } from './write.ts'\n\n/** Live agent handle: only the fields this plugin consumes. */\nexport interface AgentLike {\n /** Session id, unique per agent. */\n readonly id: string\n /** Session header carrying the working directory. */\n readonly session: { readonly header?: { readonly cwd?: string } }\n /**\n * Host-reported lifecycle status, when the composition publishes one. Read\n * live where a release decision needs the truth rather than the last event\n * this plugin happened to see.\n */\n readonly status?: 'idle' | 'running'\n /** The agent's own Cordis context. */\n readonly ctx: Context\n}\n\n/** The subset of `ctx.agents` used here. */\nexport interface AgentsLike {\n /** All live agents. */\n list(): AgentLike[]\n}\n\n/** One agent-plane event, as far as this plugin consumes it. */\nexport interface AgentEventLike {\n /** The subject agent. */\n agent: AgentLike\n /** `agent/status` only: whether a turn is currently running. */\n status?: 'idle' | 'running'\n}\n\n/** The subset of the hosting scope used here. */\nexport interface AgentScopeLike {\n /** Agent registry (injected). */\n readonly agents: AgentsLike\n /**\n * Subscribe to an agent lifecycle or turn event. `agent/pre-step` is a\n * waterfall hook, so its handler receives a continuation and must return it.\n */\n on(name: string, handler: (event: AgentEventLike, next: () => Promise<unknown>) => unknown): unknown\n /** Register a fiber-scoped cleanup. */\n effect(fn: () => unknown, label?: string): unknown\n}\n\n/** Resolved plugin configuration. */\nexport interface RuntimeConfig {\n /**\n * Project-relative MCP documents to read, lowest priority first. A spec is\n * relative to the project root, or absolute / `~/…` / `$DSH_HOME/…`.\n */\n localFiles: string[]\n /**\n * Global MCP documents read before a project's own, lowest priority first;\n * `[]` reads none.\n */\n globalFiles: string[]\n /**\n * Read the project's own dotenv documents (`<project>/.env` and\n * `<project>/.dsh/.env`) for `${...}` values.\n */\n envFiles?: boolean\n inputs: Record<string, string>\n projectMarkers: string[]\n fileMarkers: string[]\n toolCallTimeoutMs: number\n failOnStartupError: boolean\n /** Window after which a mount that produced no tool is reported as an error; `0` disables. */\n connectTimeoutMs: number\n /** Mount a session's project on its first turn instead of at session creation. */\n lazy: boolean\n /** Release a session's mounts after this much inactivity; `0` disables. */\n idleTimeoutMs: number\n /** How long the first step of a turn may wait for a pending mount; `0` never waits. */\n activationWaitMs: number\n profileWins: boolean\n /**\n * Local namespace a project entry takes when a profile-level instance already\n * owns its `serverName` and the user chose to see the project's copy too.\n * Empty asks for one derived from the project's own folder\n * (`src/naming.ts`, {@link isValidLocalPrefix}); never longer than five\n * characters, because it is a name a person has to read in front of every\n * tool of that server.\n */\n localPrefix: string\n watch: boolean\n debounceMs: number\n rescanIntervalMs: number\n credentialsFile: string\n /**\n * Offer the session's MCP tools through `mcp_search_tools` + activation, and\n * put the active ones back into each assembled request. Optional so a config\n * object that predates this feature keeps the shipped default.\n */\n activationEnabled?: boolean\n /** Total tools the durable counters may seed into the baseline; `0` seeds none. */\n activationSeeded?: number\n /** Calls one tool needs in the counters before it is seeded into the baseline. */\n activationMinCalls?: number\n /** Drop a session-activated tool after this long without a call; `0` disables. */\n toolIdleMs?: number\n /**\n * Publish one short project-MCP guidance section in the session's system\n * prompt, just ahead of the per-server `mcp:<server>` instruction blocks.\n * `false` registers no section at all. Optional so a config object that\n * predates this feature keeps the shipped default.\n */\n guidanceEnabled?: boolean\n /**\n * Cap on the names the context-driven tier offers at once; `0` disables the\n * tier. Optional so a config object that predates this feature keeps the\n * shipped default.\n */\n activationAutoLimit?: number\n /** Extra advances one context-driven offer survives after leaving the ranking. */\n activationAutoStickySteps?: number\n /**\n * Serialized size of a session's MCP surface, in characters, above which its\n * tools are offered on demand instead of being listed; `0` defers every\n * surface, however small.\n */\n activationToolBudgetChars?: number\n /**\n * Permit writes to the documents of the `globalFiles` list. Off by default:\n * a global write needs both this switch and an explicit per-write `consent`,\n * so a panel mistake cannot rewrite every project's servers. Optional so a\n * config object that predates this feature keeps it disabled.\n */\n allowGlobalWrite?: boolean\n}\n\n/**\n * Outcome of {@link ProjectMcpRuntime.saveEntry}: the fresh snapshot after a\n * write, or the code the route maps to a status.\n */\nexport type SaveOutcome =\n | { readonly ok: true; readonly snapshot: McpSnapshot }\n | {\n readonly ok: false\n readonly code: SaveErrorCode\n readonly message: string\n /**\n * Stable wire code of `message` (`projectMcp.host` namespace), for\n * client-side translation (F-48); the prose `message` keeps its\n * byte-identical English and stays the fallback.\n */\n readonly messageCode?: string\n /** Flat params of {@link messageCode}, stringified at emission. */\n readonly messageParams?: Record<string, string>\n }\n\n/**\n * Outcome of {@link ProjectMcpRuntime.setPin} and\n * {@link ProjectMcpRuntime.setPolicy}: the fresh snapshot after the store was\n * changed, or the code the route maps to a status. Both refusals are `400`s:\n * `not-found` for a project this host has no live session in, `invalid` for a\n * mode no assembly knows, `failed` when the host was built without a policy\n * store.\n */\nexport type PolicyOutcome =\n | { readonly ok: true; readonly snapshot: McpSnapshot }\n | {\n readonly ok: false\n readonly code: SaveErrorCode\n readonly message: string\n /** Wire code of `message`, the same contract as {@link SaveOutcome}'s. */\n readonly messageCode?: string\n /** Flat params of {@link messageCode}, stringified at emission. */\n readonly messageParams?: Record<string, string>\n }\n\n/**\n * Outcome of {@link ProjectMcpRuntime.toolFactsOf}: one tool's on-demand detail,\n * or the code the route maps to a status.\n *\n * A refusal is a `404`: the route only asks about a project root, a session id\n * and a name a panel read from a snapshot, so one this host does not know is a\n * stale read rather than a malformed request — the three parameters themselves\n * are checked by the route. The prose stays plain English and uncoded, the way\n * `GET logs` refuses.\n */\nexport type ToolFactsOutcome =\n | { readonly ok: true; readonly value: ToolFacts }\n | { readonly ok: false; readonly code: SaveErrorCode; readonly message: string }\n\n/**\n * Identity of the Cordis scope one project's servers are mounted in. Every\n * session of that project is parented to it, so the registrations inside are\n * visible to those sessions and to nobody else.\n */\nexport interface ProjectScopeKey {\n /** Project root whose sessions share this scope. */\n readonly projectRoot: string\n}\n\n/**\n * Whether one scope key names a project's shared registrations rather than a\n * session. A host that models scopes (a test double, a diagnostic) can tell the\n * two apart without the object identity the runtime keeps to itself.\n * @param key - key handed to {@link RuntimeOptions.createScope}.\n * @returns `true` when the key is a {@link ProjectScopeKey}.\n */\nexport function isProjectScopeKey(key: unknown): key is ProjectScopeKey {\n return isRecord(key) && typeof (key as { projectRoot?: unknown }).projectRoot === 'string'\n}\n\n/** Injection points that tests override; production uses the real defaults. */\nexport interface RuntimeOptions {\n /** Plugin object mounted per server; defaults to `@deepseek-ai/dsh-mcp-client`. */\n plugin?: unknown\n /**\n * Scope factory; defaults to `createScope` from `@deepseek-ai/dsh-scope`.\n * Called once per session and once per project that mounts something. The\n * parent link of a session scope is established by the runtime itself, before\n * this is called — the factory only mints the scope. A session key is the\n * agent's own scope key; a project key is a {@link ProjectScopeKey}.\n */\n createScope?: (ctx: Context, key: AgentLike | ProjectScopeKey) => Pick<Scope, 'ctx' | 'dispose'>\n /**\n * Registry surface the forwarding bridge reads: one scoped lookup. It is read\n * off the plugin's own context by default, which is the same `ctx.tools` the\n * registration path uses; tests override it with their double's registry.\n */\n registry?: BridgeRegistryLike\n /**\n * Bridge context factory; defaults to reading the scope tag\n * ({@link scopeOf}) from the minted scope's context and wiring the registry\n * getter to it. A test whose scope double is a plain object overrides this,\n * because its contexts carry no `dsh-scope` tag to read.\n */\n bridgeContext?: (scope: Pick<Scope, 'ctx' | 'dispose'>) => BridgeContextLike\n /** Durable counters `snapshot()` publishes alongside the rows; absent means none. */\n usage?: UsageSource\n /**\n * Durable per-project policy the snapshot publishes and the assembly reads;\n * absent means every project keeps {@link DEFAULT_TOOL_POLICY}.\n */\n policy?: PolicySource\n}\n\n/** Read-only view of the durable counters, consulted by {@link ProjectMcpRuntime.snapshot}. */\nexport interface UsageSource {\n /** Counters recorded for one project root, or `undefined` when it has none. */\n forProject(projectRoot: string): Record<string, ServerUsage> | undefined\n}\n\n/**\n * The durable policy as the runtime consumes it: read on every snapshot and\n * every assembly, written by the two panel service methods. Structural on\n * purpose, so a test can pass a plain object and the plugin does not depend on\n * the store class.\n */\nexport interface PolicySource {\n /** Policy of one project root; the shipped default when none is stored. */\n forProject(projectRoot: string): ToolPolicy\n /** Store one project's mode and return the policy now in force. */\n setMode(projectRoot: string, mode: ToolMode): ToolPolicy\n /** Pin or unpin one tool of one project and return the policy now in force. */\n setPin(projectRoot: string, tool: string, pinned: boolean): ToolPolicy\n /**\n * Store which declaration of one contested `serverName` the project shows and\n * return the policy now in force.\n */\n setConflictChoice(\n projectRoot: string,\n server: string,\n choice: ConflictChoice,\n ): ToolPolicy\n}\n\n/**\n * What this plugin currently mounts for one live agent: the project root the\n * agent resolved to and the server names it mounted there.\n */\nexport interface AgentMounts {\n /** Project root the agent's working directory resolved to. */\n projectRoot: string\n /** Names of the servers this plugin mounted for that agent right now. */\n servers: ReadonlySet<string>\n}\n\n/** Minimal fiber surface used for mount bookkeeping. */\ninterface MountFiber {\n dispose(): unknown\n await?(): Promise<unknown>\n}\n\n/** Result of a bounded wait on a fiber operation. */\ntype WaitOutcome<T> =\n | { kind: 'settled'; value: T }\n | { kind: 'failed'; error: unknown }\n | { kind: 'timeout' }\n\n/** Cordis fiber states (mirrors `@deepseek-ai/cordis`). */\nconst FIBER_ACTIVE = 2\n\n/** Plugin names that identify a profile-level mcp-client registration. */\nconst MCP_CLIENT_ENTRY_NAMES = new Set(['@deepseek-ai/dsh-mcp-client', 'dsh-mcp-client'])\n\n/**\n * Entry names that identify a second owner of the assembled tool list.\n *\n * Matched the way {@link MCP_CLIENT_ENTRY_NAMES} is: by the module specifier the\n * loader entry imports. A loader entry's `options.name` names a module, not a\n * capability, so a check that did not name the known owners could not tell a\n * presentation plugin from a logging one. The scoped spelling is included\n * because that is how a published plugin is mounted in a profile.\n */\nconst PRESENTATION_OWNER_ENTRY_NAMES = new Set([\n '@deepseek-ai/dsh-progressive-tools',\n 'dsh-progressive-tools',\n])\n\n/**\n * Why this plugin and another presentation owner cannot shape one request.\n *\n * One explanation for every owner, not one per artifact: the reason is about\n * the plumbing (`assembly.tools` waterfall, outer listener wins) and not about\n * what the other plugin is called. Short because a panel prints it in a single\n * line under the tools list.\n */\nconst PRESENTATION_OWNER_NOTE =\n 'a second presentation owner rewrites assembly.tools after this plugin does, so the two never combine in one request: either this plugin shapes only its own mcp__* entries, or the other owner is unmounted.'\n\n/**\n * Host prose plus its wire code (F-48): the English sentence, byte-identical\n * to what the site emitted before codes existed, and the `projectMcp.host`\n * code the client translates by. The two travel as one value so a call site\n * cannot reword the prose without touching the code, and so a reason passed\n * down a call chain (`detach` → `releaseProject` → `unmount`) keeps its code.\n */\ninterface CodedText {\n /** The English sentence, as it always read. */\n readonly text: string\n /** The dotted wire code, into the client's `projectMcp.host` namespace. */\n readonly code: string\n /** Flat params of the code, when it has any; numbers stringify here. */\n readonly params?: Record<string, string>\n}\n\n/** `detail` of a declared server that `lazy` has not mounted yet. */\nconst LAZY_DETAIL: CodedText = {\n code: 'idle.lazy',\n text: 'not mounted yet — this session has not started a turn (lazy mounting is on)',\n}\n\n/** Why one pass may start a project's servers for one session. */\nexport type MountTrigger = 'turn' | 'mounted' | 'eager' | 'operator'\n\n/** What one session contributes to the mount decision of one pass. */\nexport interface MountDecision {\n /** Whether `lazy` is on: without it a session mounts as soon as it exists. */\n lazy: boolean\n /** This session's own turn asked for its project (a pre-step or a `running` status). */\n activationPending: boolean\n /** This session already holds mounts, so a pass reconciles them live. */\n mounted: boolean\n /** An operator asked for exactly this session (`syncNow`, `retry`, an edit). */\n operatorRequested: boolean\n}\n\n/**\n * Sessions one pass may mount without their own turn asking: `'all'` for an\n * operator call that reconciles every session, a set of session ids for a pass\n * that belongs to one project, the project root itself for an operator call\n * scoped to a project — matched while the pass runs, so it also covers a session\n * whose working directory has not been read yet — and no requests at all for a\n * pass driven by a turn, an event or the rescan tick.\n */\nexport type PassRequests = 'all' | ReadonlySet<string> | { readonly projectRoot: string }\n\n/** The pass a turn, an event or the rescan tick runs: every session must ask. */\nconst NO_REQUESTS: PassRequests = new Set()\n\n/**\n * Decide whether one pass may start servers for one session, and why.\n *\n * The plugin's isolation rule lives here: a session starts the servers of the\n * project its working directory resolves to only when *that* session asks to\n * work there — its own turn, an operator request that names it, or a\n * deployment that turned `lazy` off. A session that is merely live (restored,\n * listed, idle, or another session's neighbour) never starts anything, and a\n * session that already holds mounts is reconciled so edits reach them.\n * @param decision - what one session contributes to one pass.\n * @returns the trigger, or `undefined` when the session must stay idle.\n */\nexport function mountTrigger(decision: MountDecision): MountTrigger | undefined {\n if (decision.operatorRequested) return 'operator'\n if (decision.activationPending) return 'turn'\n if (decision.mounted) return 'mounted'\n if (!decision.lazy) return 'eager'\n return undefined\n}\n\n/**\n * Run the parsed config through mcp-client's own Schemastery schema, exactly as\n * the in-box precedent does (`ctx.plugin(McpClient, McpClient.Config({...}))`):\n * this fills `maxInstructionBytes`/`reconnect` defaults and fails loudly on a\n * config the client would reject. A plugin without a callable `Config` keeps\n * the raw value.\n */\nfunction clientConfig(value: unknown): unknown {\n const schema = (mcpClient as { Config?: (input: unknown) => unknown }).Config\n return typeof schema === 'function' ? schema(value) : value\n}\n\ninterface LoaderEntryLike {\n options?: {\n id?: unknown\n name?: unknown\n config?: { serverName?: unknown }\n disabled?: unknown\n }\n fiber?: { state?: unknown }\n}\n\ninterface LoaderLike {\n entries?(): LoaderEntryLike[]\n}\n\ninterface MountedInstance {\n name: string\n /**\n * The `serverName` this mount actually registers under: the declared name, or\n * the local alias when a profile instance owns the declared one. It is what\n * the registry prefixes this server's tools with, so every lookup that goes by\n * tool prefix — status, guidance, the activation baseline — reads this and\n * never {@link name}.\n */\n runtimeName: string\n /** Project root whose declaration this instance was mounted from. */\n projectRoot: string\n fingerprint: string\n fiber: MountFiber | undefined\n status: ServerStatus\n detail: string | undefined\n /** Wire companions of {@link MountedInstance.detail} (F-48), set with it. */\n detailCode: string | undefined\n detailParams: Record<string, string> | undefined\n source: string | undefined\n transport: 'stdio' | 'streamable-http' | undefined\n /** Endpoint label already stripped of arguments and query strings. */\n endpoint: string\n /** When this mount started, for the connect watchdog. */\n startedAt: number\n /** `true` once the watchdog has reported the mount as never connected. */\n stalled: boolean\n /** `true` when activation itself failed, so no retry can revive this fiber. */\n failed: boolean\n}\n\n/**\n * The forwarding bridge one session holds when its key could not be joined to\n * its project's chain: the thin definitions registered in the session's own\n * layer, and the subscription that keeps them level with the project's live\n * tool set.\n */\ninterface BridgeForwarders {\n /**\n * The session's live registration batch. It owns the swap and the re-entrancy\n * every registration forces on it (`tools/change` is emitted from inside the\n * insertion, and the session is subscribed to it).\n */\n readonly batch: ForwardBatch\n /** Disposer of the project-scope `tools/change` subscription. */\n detach: () => void\n}\n\n/**\n * Where one session's MCP instances live — one home per project, forever.\n *\n * A session whose scope key could be parented to its project resolves the\n * project's shared home directly: one scope and one process per declared\n * server, shared by every session that works there. A session whose key the\n * harness already parented to something else cannot join that chain —\n * `dsh-scope` binds a key once, and the agent-preset roster binds every\n * composed agent before it is published — so it holds the SAME project home and\n * reads it through the forwarding bridge: a thin definition in its own layer\n * whose call runs the project's own. That is what makes \"one process per\n * project\" true in a preset composition too, instead of one instance per\n * session. See `docs/design/contracts/bridge.md`.\n */\ninterface MountHome {\n /** The project root whose declarations this home serves. */\n projectRoot: string\n /** Scope key the mcp-client instances are mounted under. */\n key: AgentLike | ProjectScopeKey\n /** The scope those instances live in; `undefined` before the first mount. */\n scope: Pick<Scope, 'ctx' | 'dispose'> | undefined\n /** One live instance per declared `serverName`. */\n mounts: Map<string, MountedInstance>\n /** `true` when every session of the project shares this home. */\n shared: boolean\n}\n\n/**\n * One project's shared mount state: the scope its sessions' servers are\n * registered in, and the live mounts those sessions share. The scope is minted\n * with the project's first mount and dropped with its last holder, so a project\n * costs one scope and one process per declared server however many sessions\n * work in it.\n */\ninterface ProjectState extends MountHome {\n projectRoot: string\n /** Scope key the project's registrations are tagged with. */\n key: ProjectScopeKey\n /** The project scope; `undefined` before the first mount and after teardown. */\n scope: Pick<Scope, 'ctx' | 'dispose'> | undefined\n /** One live instance per declared `serverName`, shared by every holder. */\n mounts: Map<string, MountedInstance>\n shared: true\n}\n\n/** No mounts: what a session that holds none sees. */\nconst NO_MOUNTS: ReadonlyMap<string, MountedInstance> = new Map()\n\n/**\n * Parent links minted for session scope keys, kept process-wide because the\n * relation they feed (`bindScopeParent`) is process-wide too: a second runtime\n * in one process reuses the handle the first bound instead of failing on a key\n * that is already linked.\n */\nconst parentBindings = new WeakMap<object, ScopeParentBinding>()\n\n/**\n * Point one scope key at the scope key it may resolve layers from, and keep the\n * binding that alone may re-link it later.\n *\n * This link is the mechanism that makes a project's shared servers visible to\n * exactly its sessions: the tools registry and the prompt assembly resolve a\n * session's catalog by walking `scopeChainOf(agentKey)`, so a project layer is\n * reachable only from a key parented to it. Re-linking is what a project change\n * and a release need, which is why the binding is retained rather than passed\n * to {@link createScope} and forgotten: the dsh-scope contract for a re-link\n * holds here — the runtime disposes the session scope and drops every\n * registration produced under the old parent before pointing the key\n * elsewhere.\n *\n * Reports who owns the resulting link: `true` when this runtime just created it\n * or already owns the key's binding, `false` when another composition parented\n * the key first — in which case the link is left untouched and the caller takes\n * the forwarding bridge instead of silently moving a binding it does not own.\n *\n * @param key - scope key to link.\n * @param parent - the key whose registrations the linked key may see.\n * @returns whether this runtime now owns the link.\n */\nfunction linkScopeParent(key: object, parent: object): boolean {\n const bound = parentBindings.get(key)\n if (bound !== undefined) {\n bound.rebind(parent)\n return true\n }\n try {\n parentBindings.set(key, bindScopeParent(key, parent))\n return true\n } catch {\n return false\n }\n}\n\ninterface AgentState {\n agent: AgentLike\n cwd: string | undefined\n projectRoot: string | undefined\n /**\n * Digest of the last reconciled pass: the document set, the profile\n * reservations, and the published state of the shared mounts. Identical means\n * \"nothing to do\" — including when another session of the same project\n * mounted, settled or dropped something this session would otherwise render\n * from a stale row.\n */\n digest: string | undefined\n scope: Pick<Scope, 'ctx' | 'dispose'> | undefined\n /**\n * The project whose shared mounts this session currently holds; `undefined`\n * while it holds none. Every holder resolves the one home, whether its own key\n * joined the project's chain or the bridge carries the tools to it.\n */\n project: ProjectState | undefined\n /**\n * The forwarding bridge this session holds when its key could not be parented\n * to its project (the harness bound that key first, and `dsh-scope` binds a\n * key once). `undefined` for a session whose own chain already resolves the\n * project's layer, which needs no bridge.\n */\n bridge: BridgeForwarders | undefined\n /**\n * Whether {@link linkScopeParent} linked this session's key, so a detach knows\n * it owns the re-link and not another plugin that parented the same key.\n */\n parentLinked: boolean\n /**\n * Layer-less scope key a released session is re-linked to. Without it a\n * session that let a project's servers go would keep resolving them from the\n * still-running shared layer — the one thing per-session mounting gave for\n * free, because disposing the session scope removed its whole chain.\n */\n detachedKey: object | undefined\n rows: ServerRow[]\n issues: SnapshotIssue[]\n /**\n * `serverName` conflicts of the last reconciled pass: a profile-level\n * instance that already owns a name, or one name two project documents\n * declare. Always the truth of that pass — an empty list is the answer \"no\n * conflicts\", not an absent one.\n */\n conflicts: ServerConflict[]\n /** Last observed activity (turn start, step, turn end); `undefined` until then. */\n lastActivityAt: number | undefined\n /** `true` while a turn runs, so idle release never fires in the middle of one. */\n busy: boolean\n /**\n * Set when a turn starts while nothing is mounted, so the next pass mounts\n * the project even in `lazy` mode. Cleared by the pass that mounts it.\n */\n activationPending: boolean\n /**\n * Session activation state (counter baseline + session-activated names).\n * `undefined` until the session's first scope is minted and seeds it; kept\n * across an idle release so the session keeps what it activated.\n */\n activation: ActivationState | undefined\n /**\n * Number of the agent step this session is on, counted from `agent/pre-step`\n * and starting at `1` for the first step the hook sees. `0` means no step has\n * started yet, and then no offer carries a number.\n */\n step: number\n /**\n * Step each session activation was recorded on, keyed by public name. Kept\n * next to {@link AgentState.activation} because the two outlive an idle\n * release together: the activation is what a row lists, and this is when it\n * was offered. Pruned with the activation it belongs to.\n */\n steps: Map<string, number>\n /**\n * Disposer of the activation wiring installed on the current scope. Kept so a\n * scope teardown unregisters `mcp_search_tools` explicitly: the scope fiber\n * owns that registration with the real registry, but a test host may publish a\n * plain `tools` stub, and the tool must disappear either way.\n */\n activationDispose: (() => void) | undefined\n /**\n * Disposer of the guidance-section wiring installed on the current scope. Kept\n * for the same reason as {@link AgentState.activationDispose}: the scope fiber\n * owns the registration with the real prompt registry, but a host that\n * publishes a plain `systemPrompt` stub has only this path.\n */\n guidanceDispose: (() => void) | undefined\n /**\n * Context-driven offer window (BM25 task ranking + sticky names). Kept next\n * to `activation` so a re-minted scope of the same session resumes the offers\n * it was showing instead of starting over — the same reason the activation\n * state outlives an idle release.\n */\n auto: AutoOfferState | undefined\n}\n\ninterface CachedDocument {\n mtimeMs: number\n size: number\n /** Exact bytes the parse was made from; the write path revises them. */\n text: string\n /**\n * Identity of the value sources the parse expanded `${...}` against. A\n * document whose own bytes did not move is still re-parsed when its sources\n * did, so an edit to a project `.env` or to the credentials file reaches the\n * mounts without `mcp.json` being touched at all.\n */\n stamp: string\n /** Raw `name -> entry` map the document declared, when it held one. */\n raw: Record<string, unknown> | undefined\n entries: ParsedEntry[]\n issues: ParseIssue[]\n}\n\n/** Everything the editor needs from one declaring document, per server name. */\ninterface DocumentInfo extends WriteScopeInfo {\n /** Content revision of the document at snapshot time. */\n revision: string\n /** Entry body per sanitized `serverName`, for the entries that parsed. */\n entries: Map<string, EntrySnapshot>\n}\n\n/**\n * Owns every project-scoped mount, the config watchers, and the rescan timer.\n * One instance per plugin fiber; `attach()` binds it to the agent service.\n */\nexport class ProjectMcpRuntime {\n private readonly states = new Map<string, AgentState>()\n /** Projects with a live shared scope, keyed by project root. */\n private readonly projects = new Map<string, ProjectState>()\n private readonly documents = new Map<string, CachedDocument>()\n /** Cached credentials document, re-read only when mtime/size change. */\n private secrets: { mtimeMs: number; size: number; values: Record<string, string> } | undefined\n /**\n * Dotenv values per project document, re-read only when mtime/size change.\n * Every pass of every session resolves `${...}` references, so an uncached\n * read here would cost one stat plus parse per file per session per pass.\n */\n private readonly envFiles = new Map<\n string,\n { mtimeMs: number; size: number; values: Record<string, string> }\n >()\n private readonly watchers = new Map<string, FSWatcher[]>()\n /** Config directories currently watched per project root. */\n private readonly watchedDirs = new Map<string, WatchTarget[]>()\n private readonly watchedRoots = new Set<string>()\n private timer: ReturnType<typeof setInterval> | undefined\n private debounce: ReturnType<typeof setTimeout> | undefined\n private chain: Promise<void> = Promise.resolve()\n /** The host's live-session registry, once `attach()` has bound one. */\n private listAgents: (() => AgentLike[]) | undefined\n /** `undefined` until a recursive watch has been attempted. */\n private recursiveWatch: boolean | undefined = undefined\n private ready = false\n private disposed = false\n /** Panels watching the picture through the status channel. */\n private readonly listeners = new Set<(change: SnapshotChange) => void>()\n /** Changes announced so far; the picture a stream opens on is revision `0`. */\n private revision = 0\n /** JSON of the last announced picture, so an unchanged pass announces nothing. */\n private announced: string | undefined\n /**\n * Disposer of the DSH-log subscriber this runtime installs on the notification\n * service in {@link ProjectMcpRuntime.attach}. One subscription per live\n * runtime, dropped in {@link ProjectMcpRuntime.disposeAll}, so a re-mount\n * cannot leave a second logger reading the same events.\n */\n private detachLog: (() => void) | undefined\n\n /**\n * @param ctx - the plugin's own context (host/root scope).\n * @param config - resolved plugin configuration.\n * @param options - mount overrides (tests only).\n */\n constructor(\n private readonly ctx: Context,\n private readonly config: RuntimeConfig,\n private readonly options: RuntimeOptions = {},\n ) {}\n\n /** Bind to the agent service: existing agents, lifecycle events, rescan timer. */\n attach(scope: AgentScopeLike): void {\n this.ready = true\n // The DSH log is a consumer of the notification service, not a second write\n // path: this runtime's own logger subscribes here, once, and is told every\n // event the runtime publishes.\n this.detachLog ??= subscribeEvent(logConsumer(this.ctx.logger))\n this.listAgents = () => scope.agents.list()\n scope.on('agent/created', ({ agent }) => {\n if (this.disposed) return\n this.states.set(agent.id, this.newState(agent))\n // The scope is owned by this plugin, but the agent may also be disposed\n // without a matching event reaching us first; this keeps teardown ordered.\n agent.ctx.effect(\n () => () => {\n this.dropAgent(agent.id)\n },\n 'project-mcp: session',\n )\n this.schedule('agent/created')\n })\n scope.on('agent/disposed', ({ agent }) => {\n if (this.disposed) return\n this.dropAgent(agent.id)\n })\n scope.on('agent/status', (event) => {\n this.onStatus(event)\n })\n scope.on('agent/pre-step', (event, next) => this.onPreStep(event, next))\n for (const agent of scope.agents.list()) this.states.set(agent.id, this.newState(agent))\n scope.effect(\n () => () => {\n void this.disposeAll()\n },\n 'project-mcp: lifecycle',\n )\n // The safety-net tick also drives idle release, so it runs whenever either\n // of the two needs it.\n if (this.config.watch || this.config.idleTimeoutMs > 0) {\n this.timer = setInterval(() => this.schedule('rescan'), this.config.rescanIntervalMs)\n // A rescan timer must not keep a headless DSH process alive on its own.\n this.timer.unref?.()\n }\n this.schedule('attach')\n }\n\n /**\n * Merge one live-edited config into the running one.\n *\n * A DSH ≥ 0.1.7 host serves the volatile config keys as a profile-backed\n * form and re-resolves them on `loader/volatile-update` instead of\n * restarting the entry. Only those keys are taken from `next` — every other\n * key (documents, markers, credentials, the watch switch) stays whatever the\n * entry booted with, because nothing here re-reads it safely at runtime.\n * All volatile keys are consumed at use time, so the merge alone moves the\n * behavior.\n *\n * The one exception is the safety-net tick: it is armed once in\n * {@link ProjectMcpRuntime.attach}, yet its need — `watch || idleTimeoutMs\n * > 0` — flips with a live edit of `idleTimeoutMs`, so it is re-armed or\n * cleared here. Arming is reserved to an attached runtime: before\n * `attach()` the merge alone is enough, because `attach()` arms from the\n * merged values; after disposal nothing may come back.\n *\n * @param next - the freshly resolved config; only the volatile keys are read.\n */\n applyLiveConfig(next: RuntimeConfig): void {\n const target = this.config as Record<keyof RuntimeConfig, unknown>\n for (const key of VOLATILE_CONFIG_KEYS) {\n const value = next[key]\n if (value !== undefined) target[key] = value\n }\n if (this.timer !== undefined && !this.config.watch && this.config.idleTimeoutMs === 0) {\n clearInterval(this.timer)\n this.timer = undefined\n } else if (\n this.timer === undefined &&\n this.ready &&\n !this.disposed &&\n (this.config.watch || this.config.idleTimeoutMs > 0)\n ) {\n this.timer = setInterval(() => this.schedule('rescan'), this.config.rescanIntervalMs)\n // A rescan timer must not keep a headless DSH process alive on its own.\n this.timer.unref?.()\n }\n }\n\n /**\n * Current snapshot: projects with live agents, their rows, and watched roots.\n *\n * Each project carries both a merge and the per-session split. The merge is\n * deliberately not \"first session wins\": sessions of one project mount\n * independently, so the same server can be mounted for one and idle for\n * another, and the panel must not report a running server as idle (or hide a\n * failing one) just because the idle session was registered first.\n *\n * A session that mounted tools also carries what it offers the model right\n * now (see {@link sessionTools}); the row is derived per call, never stored,\n * so a panel that polls after an activation sees it.\n */\n snapshot(): McpSnapshot {\n const byProject = new Map<string, ProjectSnapshot>()\n for (const state of this.states.values()) {\n if (state.projectRoot === undefined) continue\n let project = byProject.get(state.projectRoot)\n if (project === undefined) {\n project = { projectRoot: state.projectRoot, sessionIds: [], rows: [], issues: [], sessions: [], conflicts: [] }\n byProject.set(state.projectRoot, project)\n }\n project.sessionIds.push(state.agent.id)\n project.sessions.push(this.sessionSnapshot(state, state.projectRoot))\n mergeRows(project.rows, this.liveRows(state))\n for (const issue of state.issues) {\n if (!project.issues.some((existing) => existing.message === issue.message)) {\n project.issues.push(issue)\n }\n }\n // Conflicts merge exactly like issues do: every session of one root reads\n // the same documents and the same profile, so one name gets one report and\n // the first session to name it keeps it. The list is published even when\n // empty — that is the panel's \"no conflicts\", not a field it guesses about.\n if (state.conflicts.length > 0) {\n const merged: ServerConflict[] = [...(project.conflicts ?? [])]\n for (const conflict of state.conflicts) {\n if (!merged.some((existing) => existing.server === conflict.server)) merged.push(conflict)\n }\n // Code-unit order, the rule the rest of the plugin sorts names by, so a\n // project of two sessions reports one stable list.\n merged.sort((left, right) =>\n left.server < right.server ? -1 : left.server > right.server ? 1 : 0,\n )\n project.conflicts = merged\n }\n }\n // Counters outlive the sessions that produced them, so they are read from\n // the durable store instead of accumulated per session. The policy is\n // published for every project, stored or not: the panel reads a project's\n // mode and pins from here, and an absent field is meant for a host older\n // than the policy store rather than for a project that never changed one.\n for (const project of byProject.values()) {\n const usage = this.options.usage?.forProject(project.projectRoot)\n if (usage !== undefined) project.usage = usage\n project.policy = this.policyFor(project.projectRoot)\n // Which documents this project reads is a config fact, not a row fact, and\n // the panel needs it to number a row's priority: publish it per project so\n // the number matches the read order of this deployment.\n project.files = this.readFiles(project.projectRoot)\n // The tab is drawn from the snapshot, so the newest page rides here and the\n // ring's size says how much more the route can page. A project that never\n // recorded an event carries neither field — no empty array.\n const logs = latest(project.projectRoot, LOG_PAGE_SIZE)\n if (logs.length > 0) {\n project.logs = logs\n project.logCount = countOf(project.projectRoot)\n }\n }\n // A second presentation owner belongs to the loaded profile, not to one\n // project, so the scan runs once per snapshot and the record rides every\n // project. Absent means this plugin assembles alone, which is what keeps a\n // panel from drawing a coexistence notice that is not true.\n const presentation = this.presentationOwner()\n if (presentation !== undefined) {\n for (const project of byProject.values()) project.presentation = presentation\n }\n return {\n ready: this.ready,\n projects: [...byProject.values()],\n sources: { local: [...this.config.localFiles], global: [...this.config.globalFiles] },\n watchedFiles: [...this.watchedRoots],\n }\n }\n\n /**\n * Watch the picture instead of asking for it: the listener is told the current\n * state at once, then once per change that actually changes something — a pass\n * that committed, a mount that appeared or connected, a release, a save, a\n * policy write. A rescan that found the same servers announces nothing, so an\n * open panel receives no traffic for a project nothing is happening in.\n * @param listener - told the revision and the whole snapshot it belongs to.\n * @returns a disposer that stops watching.\n */\n subscribe(listener: (change: SnapshotChange) => void): () => void {\n this.listeners.add(listener)\n try {\n listener({ revision: this.revision, snapshot: this.snapshot() })\n } catch (error) {\n this.ctx.logger.warn(`project-mcp: announcing the first snapshot failed: ${errorText(error)}`)\n }\n return () => {\n this.listeners.delete(listener)\n }\n }\n\n /**\n * Announce the picture if it differs from the last one announced.\n *\n * The comparison is what keeps the status channel quiet: a pass runs on every\n * watcher event and every rescan tick, and almost all of them re-derive the\n * same rows. With no listener attached nothing is built at all — a headless\n * host pays nothing for a channel nobody reads.\n */\n private notify(): void {\n if (this.listeners.size === 0 || this.disposed) return\n const snapshot = this.snapshot()\n const digest = JSON.stringify(snapshot)\n if (digest === this.announced) return\n this.announced = digest\n this.revision += 1\n const change: SnapshotChange = { revision: this.revision, snapshot }\n for (const listener of [...this.listeners]) {\n try {\n listener(change)\n } catch (error) {\n this.ctx.logger.warn(`project-mcp: announcing a change failed: ${errorText(error)}`)\n }\n }\n }\n\n /**\n * One session's snapshot row, carrying its live tool presentation only when\n * the host has mounted tools for it, and how much of the project's log history\n * belongs to it when there is any.\n * @param state - the session's own runtime state.\n * @param projectRoot - the project the session works in.\n * @returns the row; `tools` stays absent for an unmounted session, and\n * `logCount` for a session that recorded nothing.\n */\n private sessionSnapshot(state: AgentState, projectRoot: string): SessionSnapshot {\n const session: SessionSnapshot = {\n id: state.agent.id,\n rows: this.liveRows(state),\n issues: state.issues,\n }\n const tools = this.sessionTools(state)\n if (tools !== undefined) session.tools = tools\n const logCount = countForSession(projectRoot, state.agent.id)\n if (logCount > 0) session.logCount = logCount\n session.conflicts = state.conflicts\n return session\n }\n\n /**\n * What one session offers the model, measured from its live state at call\n * time.\n *\n * The mounted set is the whole visible MCP surface — this plugin's project\n * mounts plus the profile plane and any F-19 forwarders — the same surface\n * the activation wiring measures against the budget, so the counts cannot\n * describe a different catalog than the one the request is built from. Total\n * on purpose: a probe that fails leaves the row out and warns instead of\n * failing the snapshot.\n * @param state - the session's own runtime state.\n * @returns the presentation row, or `undefined` when nothing is mounted.\n */\n private sessionTools(state: AgentState): SessionTools | undefined {\n try {\n const mounted = this.visibleSchemas(state)\n if (mounted.length === 0) return undefined\n const activationEnabled = this.config.activationEnabled ?? DEFAULT_ACTIVATION_ENABLED\n return toolsFor({\n sessionId: state.agent.id,\n mounted,\n activation: activationEnabled ? this.seedActivation(state) : state.activation,\n auto: state.auto,\n activationEnabled,\n policy: this.policyFor(state.projectRoot),\n steps: state.steps,\n ...(state.step === 0 ? {} : { step: state.step }),\n ...(this.config.activationToolBudgetChars === undefined\n ? {}\n : { budgetChars: this.config.activationToolBudgetChars }),\n })\n } catch (error) {\n this.ctx.logger.warn(\n `project-mcp: reading the tool presentation of session ${state.agent.id} failed: ${errorText(error)}`,\n )\n return undefined\n }\n }\n\n /**\n * One tool's on-demand detail, answered for a row a panel opened.\n *\n * A read, never a rescan: the definition comes from the same mount home the\n * snapshot's session row was measured from, so a **deferred** name answers\n * exactly like an offered one — the home's catalog carries the whole mounted\n * surface, and only the request's own deferral decision leaves a name out of\n * it. That is also what makes the reason honest: `budget` is reported exactly\n * when the session's own row lists the name in `deferred`, and every figure on\n * it is a host measurement — {@link schemaChars} of this definition, the\n * session's `budgetChars` and its `visibleChars`. A number the host does not\n * have is omitted rather than guessed.\n *\n * The published fields are the schema's top-level `parameters.properties`\n * only: a nested object or array is drawn as its type and never expanded, and\n * a property's `default` is never published — the schema a model reads is the\n * definition's, and this record is a *view* of it, not a second copy with\n * defaults baked in.\n *\n * @param projectRoot - project root the panel read the row from.\n * @param sessionId - live agent id the row belongs to.\n * @param name - public registry name, as the panel drew it.\n * @returns the tool's facts, or the `not-found` refusal the route maps to 404.\n */\n toolFactsOf(projectRoot: string, sessionId: string, name: string): ToolFactsOutcome {\n const state = this.states.get(sessionId)\n if (state === undefined || state.projectRoot !== projectRoot) {\n return {\n ok: false,\n code: 'not-found',\n message: `no live session ${sessionId} in ${projectRoot}`,\n }\n }\n const home = this.homeOf(state)\n if (home === undefined) {\n return {\n ok: false,\n code: 'not-found',\n message: `no live session ${sessionId} in ${projectRoot}`,\n }\n }\n const schema = this.schemasOf(home, state.agent.id).find(\n (candidate) => candidate.name === name,\n )\n if (schema === undefined) {\n return {\n ok: false,\n code: 'not-found',\n message: `${name} is not mounted in ${projectRoot}`,\n }\n }\n const fields = toolFieldsOf(schema.parameters)\n const description = schema.description === '' ? undefined : schema.description\n // Only a name the session's own row hides is unexplained by the request, so\n // only such a name carries a reason; an offered one has nothing to explain.\n const deferred = this.sessionTools(state)?.deferred ?? []\n const reason = deferred.includes(name) ? this.budgetReason(state, schema) : undefined\n return {\n ok: true,\n value: {\n name: schema.name,\n ...(description === undefined ? {} : { description }),\n fields,\n ...(reason === undefined ? {} : { reason }),\n },\n }\n }\n\n /**\n * Why the budget left one definition out of this session's request: the host's\n * own numbers, each omitted when the row that carries it did not measure it.\n * @param state - the session whose row and budget are read.\n * @param schema - the definition the row does not offer.\n * @returns the `budget` reason, carrying only figures the host holds.\n */\n private budgetReason(state: AgentState, schema: ToolSchemaLike): ToolReason {\n const tools = this.sessionTools(state)\n return {\n kind: 'budget',\n chars: schemaChars(schema),\n ...(tools === undefined\n ? {}\n : {\n budget: tools.budgetChars,\n ...(tools.visibleChars === undefined ? {} : { used: tools.visibleChars }),\n }),\n }\n }\n\n /**\n * What this plugin currently mounts for one live agent: the project root the\n * agent resolved to and the server names it mounted there. `undefined` when\n * the agent is unknown or resolved to no project, so a tool call from it is\n * simply not counted.\n * @param agentId - agent (session) id a tool call ran for.\n */\n mountsFor(agentId: string): AgentMounts | undefined {\n const state = this.states.get(agentId)\n if (state === undefined || state.projectRoot === undefined) return undefined\n return { projectRoot: state.projectRoot, servers: this.runtimeNamesOf(state) }\n }\n\n /**\n * Pin or unpin one tool of one project.\n *\n * The project must be one this host currently has a live session in: the panel\n * only ever names a root it read from a snapshot, so anything else is a stale\n * click and is refused rather than stored for a project nothing would show. No\n * rescan follows — the policy is part of no declaring document — so the answer\n * carries the current snapshot with the fresh pin list.\n * @param request - project root, public tool name and the wanted pin state.\n * @returns the fresh snapshot, or the refusal code the route maps to a status.\n */\n setPin(request: PinRequest): PolicyOutcome {\n const policy = this.options.policy\n if (policy === undefined) {\n return {\n ok: false,\n code: 'failed',\n message: 'this host has no tool-policy store',\n messageCode: 'save.noPolicyStore',\n }\n }\n if (!this.projectKnown(request.projectRoot)) {\n return {\n ok: false,\n code: 'not-found',\n message: `no live session in ${request.projectRoot}`,\n messageCode: 'save.noLiveSession',\n messageParams: { projectRoot: request.projectRoot },\n }\n }\n policy.setPin(request.projectRoot, request.tool, request.pinned)\n this.refreshPresentation(request.projectRoot)\n this.notify()\n return { ok: true, snapshot: this.snapshot() }\n }\n\n /**\n * Store one project's tool mode.\n *\n * The same two refusals as {@link setPin}, plus a mode no assembly knows: the\n * mode is read on every assembly, so a stored change applies to the next model\n * step without re-minting the session scope.\n * @param request - project root and the mode to store.\n * @returns the fresh snapshot, or the refusal code the route maps to a status.\n */\n setPolicy(request: PolicyRequest): PolicyOutcome {\n if (!isToolMode(request.mode)) {\n return {\n ok: false,\n code: 'invalid',\n message: `unknown tool mode ${JSON.stringify(request.mode)}`,\n messageCode: 'save.unknownMode',\n messageParams: { mode: JSON.stringify(request.mode) },\n }\n }\n const policy = this.options.policy\n if (policy === undefined) {\n return {\n ok: false,\n code: 'failed',\n message: 'this host has no tool-policy store',\n messageCode: 'save.noPolicyStore',\n }\n }\n if (!this.projectKnown(request.projectRoot)) {\n return {\n ok: false,\n code: 'not-found',\n message: `no live session in ${request.projectRoot}`,\n messageCode: 'save.noLiveSession',\n messageParams: { projectRoot: request.projectRoot },\n }\n }\n policy.setMode(request.projectRoot, request.mode)\n this.refreshPresentation(request.projectRoot)\n this.notify()\n return { ok: true, snapshot: this.snapshot() }\n }\n\n /**\n * Choose which declaration of one contested `serverName` this project shows.\n *\n * The same two refusals as {@link setPin}, plus an answer no build knows. The\n * choice is stored first and the project reconciled right away, because a\n * choice is a mount changing name: the row it produces must be the row the\n * registry ends up carrying, not one that waits for the next turn.\n *\n * Nothing is refused for a name the project does not conflict over: the store\n * keeps a choice for a name that is not contested yet, so a declaration that\n * comes back — or a profile entry that is added later — finds the answer the\n * user already gave.\n * @param request - project root, contested name and the declaration to show.\n * @returns the fresh snapshot, or the refusal code the route maps to a status.\n */\n setConflictChoice(request: ConflictRequest): PolicyOutcome {\n if (!isConflictChoice(request.choice)) {\n return {\n ok: false,\n code: 'invalid',\n message: `unknown conflict choice ${JSON.stringify(request.choice)}`,\n messageCode: 'save.unknownChoice',\n messageParams: { choice: JSON.stringify(request.choice) },\n }\n }\n if (!this.projectKnown(request.projectRoot)) {\n return {\n ok: false,\n code: 'not-found',\n message: `no live session in ${request.projectRoot}`,\n messageCode: 'save.noLiveSession',\n messageParams: { projectRoot: request.projectRoot },\n }\n }\n const policy = this.options.policy\n if (policy === undefined) {\n return {\n ok: false,\n code: 'failed',\n message: 'this host has no tool-policy store',\n messageCode: 'save.noPolicyStore',\n }\n }\n policy.setConflictChoice(request.projectRoot, request.server, request.choice)\n this.notify()\n // The pass that follows the click is what moves the entry between a\n // conflict report and a mount, and it is not awaited: an operator click\n // must not wait for a server to start.\n void this.syncNow(request.projectRoot)\n return { ok: true, snapshot: this.snapshot() }\n }\n\n /**\n * The policy in force for one project root.\n *\n * Read at snapshot and assembly time — never captured — so a stored change is\n * visible to the next model step and to the next panel poll. A host built\n * without a store follows the shipped default for every project.\n * @param projectRoot - project root, or `undefined` before a session resolves one.\n * @returns the stored policy, or {@link DEFAULT_TOOL_POLICY} when there is none.\n */\n private policyFor(projectRoot: string | undefined): ToolPolicy {\n if (projectRoot === undefined) return DEFAULT_TOOL_POLICY\n return this.options.policy?.forProject(projectRoot) ?? DEFAULT_TOOL_POLICY\n }\n\n /**\n * Re-apply the presentation of every session working in one project.\n *\n * A pin or a mode is read live by the panel and by the guidance, but the\n * forwarders carry their `deferLoading` flag from the pass that registered\n * them, so the sessions of that project have to run one — off the caller's\n * stack, like every other change note.\n * @param projectRoot - the project whose policy just moved.\n */\n private refreshPresentation(projectRoot: string): void {\n for (const state of this.states.values()) {\n if (state.projectRoot !== projectRoot) continue\n state.bridge?.batch.note()\n }\n }\n\n /**\n * The names one session's presentation offers the model right now.\n *\n * The counterpart of the assembly wiring's own `offeredNames`, read where the\n * presentation lives outside that assembly — in the bridge's forwarders. It is\n * the counter-seeded baseline, the session's activations, the context tier's\n * window, and the project's pins; the same four sources the assembly-side\n * `wanted` set is built from, so the two cannot drift.\n * @param state - the session to read.\n * @returns the offered public names.\n */\n private offeredNamesOf(state: AgentState): ReadonlySet<string> {\n const names = new Set<string>(presentedNames(this.seedActivation(state)))\n const auto = state.auto\n if (auto !== undefined) for (const name of autoPresentedNames(auto)) names.add(name)\n for (const pin of this.policyFor(state.projectRoot).pins) names.add(pin)\n return names\n }\n\n /**\n * The names one session presents as deferred: what it mounts that it does not\n * offer.\n *\n * Empty when there is nothing to defer — activation off, `direct`, or a\n * surface that fits the budget — because deferring a schema the request would\n * have carried anyway only makes the declaration list harder to read, and the\n * prefix-cache argument for it is gone. The budget is the same\n * {@link surfaceChars} reading the panel and the assembly gate use, so the\n * deferred set and the \"hidden\" number a panel shows are one decision.\n * @param state - the session whose presentation is being registered.\n * @returns the names whose forwarders carry `deferLoading`, in registry order.\n */\n private deferredNamesOf(state: AgentState): readonly string[] {\n if (!(this.config.activationEnabled ?? DEFAULT_ACTIVATION_ENABLED)) return []\n const policy = this.policyFor(state.projectRoot)\n if (policy.mode === 'direct') return []\n // The home's catalog, read without {@link mountedSchemas}: this runs inside a\n // bridge pass, and that read syncs the very batch the pass is building.\n const home = this.homeOf(state)\n const mounted = home === undefined ? [] : this.schemasOf(home, state.agent.id)\n if (policy.mode === 'disclosure') {\n const budget = this.config.activationToolBudgetChars ?? DEFAULT_TOOL_BUDGET_CHARS\n if (!overToolBudget(surfaceChars(mounted), budget)) return []\n }\n const offered = this.offeredNamesOf(state)\n return mounted.map((schema) => schema.name).filter((name) => !offered.has(name))\n }\n\n /**\n * Whether one project root has a live session on this host.\n * @param projectRoot - project root a policy request names.\n * @returns `true` when a bound session resolved to that root.\n */\n private projectKnown(projectRoot: string): boolean {\n for (const state of this.states.values()) {\n if (state.projectRoot === projectRoot) return true\n }\n return false\n }\n\n /**\n * Write one edited entry back to the document that declares it.\n *\n * The checks run in the contract's order and every one of them must pass\n * before a byte is written: the row must still exist, its declaring document\n * must belong to the project or to the (consented, enabled) global tier, the\n * revision must be the one the editor read, and the resulting entry must pass\n * the same parse path the mount uses. The document is then replaced by\n * {@link writeDocument} (`.bak`, then temp file, then rename) and rescanned,\n * so the answer carries a fresh snapshot.\n * @param request - the entry body, its declaring document and the read revision.\n * @returns the fresh snapshot, or the refusal code the route maps to a status.\n */\n async saveEntry(request: SaveRequest): Promise<SaveOutcome> {\n const states = [...this.states.values()].filter((state) => state.projectRoot === request.projectRoot)\n const row = states\n .flatMap((state) => state.rows)\n .find((candidate) => candidate.name === request.server)\n if (row === undefined) {\n return {\n ok: false,\n code: 'not-found',\n message: `server \"${request.server}\" is not declared for ${request.projectRoot}`,\n messageCode: 'save.serverNotDeclared',\n messageParams: { server: request.server, projectRoot: request.projectRoot },\n }\n }\n const document = row.source\n if (document === undefined) {\n return {\n ok: false,\n code: 'blocked',\n message: `server \"${request.server}\" has no declaring document to write`,\n messageCode: 'save.noDeclaringDocument',\n messageParams: { server: request.server },\n }\n }\n const scope = writeScopeFor(document, request.projectRoot, {\n projectDocuments: localConfigPaths(request.projectRoot, this.config.localFiles),\n globalDocuments: this.globalFiles(),\n allowGlobalWrite: this.config.allowGlobalWrite === true,\n })\n if (scope.scope === 'readonly') {\n // The scope's own reason already carries its write.blocked.* code; the\n // save.notWritable fallback is for the reason-less shape alone.\n return {\n ok: false,\n code: 'blocked',\n message: scope.reason ?? `${document} is not writable`,\n messageCode: scope.blockedCode ?? 'save.notWritable',\n messageParams: scope.blockedParams ?? { document },\n }\n }\n if (scope.scope === 'global' && request.consent !== true) {\n return {\n ok: false,\n code: 'blocked',\n message: `writing ${document} needs explicit consent`,\n messageCode: 'save.needsConsent',\n messageParams: { document },\n }\n }\n if (scope.scope === 'global' && this.config.allowGlobalWrite !== true) {\n return {\n ok: false,\n code: 'blocked',\n message: `writing the global tier is disabled by this deployment (allowGlobalWrite: false)`,\n messageCode: 'save.globalDisabled',\n }\n }\n if (request.document !== document) {\n return {\n ok: false,\n code: 'not-found',\n message: `server \"${request.server}\" is now declared by ${document}`,\n messageCode: 'save.declaredElsewhere',\n messageParams: { server: request.server, document },\n }\n }\n let text: string\n try {\n text = readFileSync(document, 'utf8')\n } catch {\n return {\n ok: false,\n code: 'not-found',\n message: `the declaring document ${document} is gone`,\n messageCode: 'save.documentGone',\n messageParams: { document },\n }\n }\n if (documentRevision(text) !== request.revision) {\n return {\n ok: false,\n code: 'conflict',\n message: `${document} changed since the entry was read; reload it and edit again`,\n messageCode: 'save.documentChanged',\n messageParams: { document },\n }\n }\n let root: unknown\n try {\n root = JSON.parse(text) as unknown\n } catch (error) {\n return {\n ok: false,\n code: 'invalid',\n message: `the declaring document is not valid JSON: ${error instanceof Error ? error.message : String(error)}`,\n messageCode: 'save.invalidJson',\n messageParams: { document, error: error instanceof Error ? error.message : String(error) },\n }\n }\n const servers = isRecord(root) ? root.mcpServers : undefined\n if (!isRecord(servers)) {\n return {\n ok: false,\n code: 'blocked',\n message: `${document} does not use an \"mcpServers\" object, so this editor cannot rewrite it`,\n messageCode: 'save.noMcpServers',\n messageParams: { document },\n }\n }\n // The panel edits the sanitized `serverName`; the document key may differ\n // (`my server` vs `my-server`), so the declaration goes back under the key\n // the document actually holds.\n const key = Object.keys(servers).find(\n (candidate) => candidate === request.server || slugifyServerName(candidate) === request.server,\n )\n if (key === undefined) {\n return {\n ok: false,\n code: 'not-found',\n message: `server \"${request.server}\" is no longer declared in ${document}`,\n messageCode: 'save.noLongerDeclared',\n messageParams: { server: request.server, document },\n }\n }\n let next: string\n try {\n next = applyEntry(text, key, entryToDeclaration(request.entry, servers[key]))\n } catch (error) {\n // A WriteDocError already carries the refusal's wire code; anything else\n // crosses as prose alone.\n return {\n ok: false,\n code: 'invalid',\n message: error instanceof Error ? error.message : String(error),\n ...(error instanceof WriteDocError\n ? {\n messageCode: error.code,\n ...(error.params === undefined ? {} : { messageParams: error.params }),\n }\n : {}),\n }\n }\n // Same parse path the mount uses: what the host would not mount, it does\n // not write either.\n const parsed = parseDocument(next, document, this.resolveContext(request.projectRoot))\n const candidate = parsed.entries.find((entry) => entry.name === request.server)\n if (candidate === undefined || candidate.error !== undefined || candidate.config === undefined) {\n // A parse failure's prose already has its own parse.* code (Task 2);\n // save.entryNotParsed names only the shapeless fallback.\n return {\n ok: false,\n code: 'invalid',\n message: candidate?.error ?? `the edited entry \"${request.server}\" did not parse`,\n messageCode: candidate?.errorCode ?? 'save.entryNotParsed',\n ...(candidate?.errorCode === undefined\n ? { messageParams: { server: request.server } }\n : candidate.errorParams === undefined\n ? {}\n : { messageParams: candidate.errorParams }),\n }\n }\n try {\n writeDocument(document, next)\n } catch (error) {\n return {\n ok: false,\n code: 'failed',\n message: `writing ${document} failed: ${error instanceof Error ? error.message : String(error)}`,\n messageCode: 'save.writeFailed',\n messageParams: { document, error: error instanceof Error ? error.message : String(error) },\n }\n }\n // Drop the read cache and the pass digest for this project: a write that\n // only reformats the document keeps the same mounted config, so the digest\n // alone would skip the row rebuild the editor needs.\n this.documents.delete(document)\n for (const state of states) state.digest = undefined\n // An edit belongs to the project that declares the entry: reconcile it as an\n // operator request for *its* sessions — so the change reaches a live mount —\n // and never as a request for another project, whose sessions must not start\n // a server because an entry moved here.\n await this.enqueue(new Set(states.map((state) => state.agent.id)))\n return { ok: true, snapshot: this.snapshot() }\n }\n\n /**\n * Run one reconciliation pass and await it.\n *\n * The operator call: it requests every listed session — or, with a\n * `projectRoot`, only that project's — so a session whose declaration was\n * never mounted (or whose mount was dropped) may start here without a turn.\n * Every other pass — a turn, an event, the rescan tick — requests only the\n * sessions that asked. Scripted reconciliation uses this awaiting form; the\n * panel's `Sync` uses {@link syncSoon}.\n * @param projectRoot - restricts the pass to one project's sessions.\n */\n async syncNow(projectRoot?: string): Promise<void> {\n await this.enqueue(this.requestsFor(projectRoot))\n }\n\n /**\n * Ask for the same pass and return at once — the panel's `Sync`.\n *\n * Waiting for the pass is what turned a `Sync` on a project whose server was\n * still connecting into a hang: the HTTP answer, and with it the panel's busy\n * flag, stayed open for `connectTimeoutMs`. The pass runs in the background,\n * and the panel watches its outcome on the status channel.\n * @param projectRoot - restricts the pass to one project's sessions.\n */\n syncSoon(projectRoot?: string): void {\n this.kick(projectRoot)\n }\n\n /**\n * Queue the operator pass without awaiting it, containing a rejection the way\n * every other background pass does: by the time either operator route\n * answers, the pass is nobody's request to wait for.\n * @param projectRoot - restricts the pass to one project's sessions.\n */\n private kick(projectRoot: string | undefined): void {\n void this.enqueue(this.requestsFor(projectRoot)).catch((error: unknown) => {\n this.ctx.logger.warn(`project-mcp: operator pass failed: ${errorText(error)}`)\n })\n }\n\n /**\n * The sessions one operator pass may mount: every listed one, or the sessions\n * of a single project when the call came from a surface that shows one. The\n * project is named, not resolved here: {@link syncAgent} matches it against\n * each session's own working directory, so the very first operator call for a\n * session reaches the project it named.\n * @param projectRoot - the project the caller named, when it named one.\n * @returns the request the pass takes.\n */\n private requestsFor(projectRoot: string | undefined): PassRequests {\n return projectRoot === undefined ? 'all' : { projectRoot }\n }\n\n /** Queue one pass behind whatever is already running. */\n private enqueue(requests: PassRequests): Promise<void> {\n this.chain = this.chain.then(\n () => this.runPass(requests),\n () => this.runPass(requests),\n )\n return this.chain\n }\n\n /**\n * Drop the mounts currently in an `error` state and ask for a pass that mounts\n * them again, so a server that was fixed outside the plugin is picked up\n * without editing its declaration. A stalled mount is restarted from scratch.\n *\n * The drop is awaited — it is local and quick, and the answer the route sends\n * back must already show those rows as unmounted rather than failed. The pass\n * is not: a server that boots slowly would otherwise hold the `POST retry`\n * answer open for `connectTimeoutMs`, which the panel showed as a hang. A\n * `projectRoot` keeps both the drop and the pass inside that one project, so\n * retrying a row never starts a server for another one.\n *\n * The drop is per project: one failed instance is shared by every session of\n * its project, so retrying it must not try to unmount it once per session.\n * @param projectRoot - restricts the drop and the pass to one project.\n */\n async retry(projectRoot?: string): Promise<void> {\n // Every instance a session renders lives in its project's shared home — one\n // home per project, bridged or joined — so the project records are the whole\n // list of homes a retry has to walk.\n const homes: MountHome[] = [...this.projects.values()]\n for (const home of homes) {\n if (projectRoot !== undefined && home.projectRoot !== projectRoot) continue\n let dropped = false\n for (const [name, mount] of [...home.mounts]) {\n if (mount.status !== 'error') continue\n await this.unmount(home, name, { code: 'unmount.reason.operatorRetry', text: 'an operator retry replaces it' })\n dropped = true\n }\n // The documents are unchanged, so the pass below would take its steady\n // state shortcut — the dropped mount is exactly why it must not. Every\n // session that renders this home's rows must rebuild them. (A lazy\n // declaration that was never mounted needs no nudge: the operator pass\n // mounts it by itself, see the merge pass.)\n if (!dropped) continue\n for (const state of this.states.values()) {\n if (state.projectRoot === home.projectRoot) state.digest = undefined\n }\n }\n // The rows the drop just freed are visible now; the pass that mounts them\n // again reports for itself, one mount at a time.\n this.notify()\n this.kick(projectRoot)\n }\n\n /** Dispose every mount, scope, watcher and timer owned by this runtime. */\n async disposeAll(): Promise<void> {\n this.disposed = true\n if (this.timer !== undefined) clearInterval(this.timer)\n if (this.debounce !== undefined) clearTimeout(this.debounce)\n this.timer = undefined\n this.debounce = undefined\n for (const watchers of this.watchers.values()) {\n for (const watcher of watchers) watcher.close()\n }\n this.watchers.clear()\n this.watchedDirs.clear()\n this.watchedRoots.clear()\n const states = [...this.states.values()]\n this.states.clear()\n this.documents.clear()\n this.secrets = undefined\n this.envFiles.clear()\n // Sessions first — each hands its hold back — then whatever no session names\n // any more, so a shared project is released exactly once either way.\n await Promise.all(states.map((state) => this.disposeState(state, { code: 'unmount.reason.unloading', text: 'the plugin is unloading' })))\n for (const project of [...this.projects.values()]) {\n await this.releaseProject(project, { code: 'unmount.reason.unloading', text: 'the plugin is unloading' })\n }\n this.projects.clear()\n // Last, so the teardown events above still reach the log: this runtime stops\n // being a consumer once it has nothing left to report.\n this.detachLog?.()\n this.detachLog = undefined\n }\n\n private newState(agent: AgentLike): AgentState {\n return {\n agent,\n cwd: agent.session.header?.cwd,\n projectRoot: undefined,\n digest: undefined,\n scope: undefined,\n project: undefined,\n bridge: undefined,\n parentLinked: false,\n detachedKey: undefined,\n rows: [],\n issues: [],\n conflicts: [],\n lastActivityAt: undefined,\n busy: false,\n activationPending: false,\n activation: undefined,\n step: 0,\n steps: new Map(),\n activationDispose: undefined,\n guidanceDispose: undefined,\n auto: undefined,\n }\n }\n\n private dropAgent(id: string): void {\n const state = this.states.get(id)\n this.states.delete(id)\n if (state !== undefined) void this.disposeState(state, { code: 'unmount.reason.sessionGone', text: 'the session went away' })\n this.sweepProjects()\n this.syncWatchers()\n this.notify()\n }\n\n /**\n * Release the sessions the host registry no longer lists.\n *\n * A finished or abandoned session produces no further event — no\n * `agent/status`, no `idle` transition to clear the busy flag, nothing for\n * the idle sweep to time out from. The pass is the path that exists: whatever\n * the registry still lists is live, and anything else hands its servers back\n * here, even with the idle sweep disabled.\n */\n private async releaseAbandoned(): Promise<void> {\n const listed = this.listAgents?.()\n if (listed === undefined) return\n const live = new Set(listed.map((agent) => agent.id))\n for (const id of [...this.states.keys()]) {\n if (live.has(id)) continue\n const state = this.states.get(id)\n this.states.delete(id)\n if (state !== undefined) await this.disposeState(state, { code: 'unmount.reason.sessionUnlisted', text: 'the registry no longer lists the session' })\n }\n }\n\n /**\n * Whether one session is running a turn right now.\n *\n * The host's own status wins where it publishes one: `busy` only ever\n * reflects the events this plugin happened to see, so a session whose `idle`\n * transition never arrives would pin its mounts forever behind a stale flag.\n * @param state - the session to judge.\n * @returns true while the session must keep its mounts unconditionally.\n */\n private working(state: AgentState): boolean {\n const live = state.agent.status\n return live === undefined ? state.busy : live === 'running'\n }\n\n /**\n * Forget everything one session presented. The session's project is gone with\n * the scope (or the session is over), so a baseline seeded from that project's\n * counters must not leak into a different one. An idle release goes through\n * `releaseMounts`, not here.\n *\n * The hold on the old project's shared servers is given back here too: a\n * session that moves to another project — or disappears — must not keep the\n * project it left running for nobody.\n * @param state - the session state to clear.\n */\n private async disposeState(state: AgentState, reason: CodedText): Promise<void> {\n state.digest = undefined\n state.rows = []\n state.issues = []\n state.activation = undefined\n state.auto = undefined\n await this.detach(state, reason)\n }\n\n /**\n * Take one session's hold on a project: link its scope key to the project's\n * so the shared layer resolves for it, or install the forwarding bridge when\n * that link is impossible, then mint its own scope and install the session\n * wiring on it. Idempotent while the hold is unchanged.\n *\n * The link comes first because it is what makes the project's already-running\n * servers visible to this session from its first request on. A key the\n * harness already parented cannot be linked again — `dsh-scope` binds a key\n * once, and the agent-preset roster binds every composed agent to its\n * standing scope before the agent is published — so that session holds the\n * SAME project home and gets a forwarding bridge instead: thin definitions in\n * its own layer whose calls run the project's one instance (`src/bridge.ts`).\n * One process per project is the whole point; the alternative was one process\n * per session, which is what the panel showed in the web GUI.\n * @param state - the session taking the hold.\n * @param project - the project whose mounts it shares.\n * @returns the home the session now holds.\n */\n private async holdProject(state: AgentState, project: ProjectState): Promise<MountHome> {\n const held = this.homeOf(state)\n if (held !== undefined && held.projectRoot === project.projectRoot) return held\n if (held !== undefined) await this.detach(state, { code: 'unmount.reason.sessionMoved', text: 'the session moved to another project' })\n // The session's own layer key is private to this session, so the link either\n // succeeds (this runtime just bound it, or owns the binding) or another\n // composition already parented that key — a foreign hold this runtime must\n // not move. The session still holds the project — the servers run once for\n // the whole project — and the bridge carries their tools into this session's\n // own layer, where the registry resolves them for exactly this key.\n state.parentLinked = linkScopeParent(state.agent, project.key)\n if (!state.parentLinked) {\n this.ctx.logger.debug?.(\n `project-mcp: session ${state.agent.id} keeps a foreign scope parent, so its tools are forwarded from ${project.projectRoot}`,\n )\n }\n state.project = project\n const home: MountHome = project\n this.ensureSessionScope(state.agent, state)\n if (state.parentLinked) this.dropBridge(state)\n else this.installBridge(state, project)\n return home\n }\n\n /**\n * Give one session's hold back. Its own scope and wiring go away, its scope\n * key is unlinked from the project so the shared servers stop resolving for\n * it, and the project's instance is released exactly when this was the last\n * holder — a session that goes idle or leaves while another one still works\n * must not stop the servers that one is using.\n * @param state - the session releasing its hold.\n * @param reason - why the hold is going back; every instance this drops is\n * logged with it, so the log says why a server stopped, not only that it did.\n */\n private async detach(state: AgentState, reason: CodedText): Promise<void> {\n const project = state.project\n state.project = undefined\n this.dropBridge(state)\n if (project !== undefined && state.parentLinked) {\n state.parentLinked = false\n state.detachedKey ??= {}\n if (!linkScopeParent(state.agent, state.detachedKey)) {\n this.ctx.logger.warn(\n `project-mcp: unlinking session ${state.agent.id} from its project failed: its session key is held by another composition`,\n )\n }\n }\n await this.disposeSessionScope(state, reason)\n if (project !== undefined && !this.hasHolders(project)) await this.releaseProject(project, reason)\n }\n\n /** Drop the session scope and the wiring installed on it. Idempotent. */\n private async disposeSessionScope(state: AgentState, reason: CodedText): Promise<void> {\n const scope = state.scope\n state.scope = undefined\n this.releaseWiring(state)\n if (scope === undefined) return\n try {\n await scope.dispose()\n } catch (error) {\n this.ctx.logger.warn(`project-mcp: disposing session scope failed: ${errorText(error)}`)\n }\n }\n\n /**\n * Whether any live session still holds one project's shared mounts.\n * @param project - the project to look for.\n * @returns `true` while at least one session keeps the instance alive.\n */\n private hasHolders(project: ProjectState): boolean {\n for (const state of this.states.values()) {\n if (state.project === project) return true\n }\n return false\n }\n\n /**\n * Release one project's shared servers and the scope that owns them.\n *\n * Runs when the project's last holder lets go, so a shared instance goes away\n * on exactly the trigger a per-session one did: the project's last session\n * releasing it (idle release, request, disposal, a move to another project, or\n * a declaration that mounts nothing any more). Idempotent.\n * @param project - the project to tear down.\n */\n private async releaseProject(project: ProjectState, reason: CodedText): Promise<void> {\n for (const name of [...project.mounts.keys()]) await this.unmount(project, name, reason)\n const scope = project.scope\n project.scope = undefined\n if (scope !== undefined) {\n try {\n await scope.dispose()\n } catch (error) {\n this.ctx.logger.warn(\n `project-mcp: disposing the shared scope of ${project.projectRoot} failed: ${errorText(error)}`,\n )\n }\n }\n // The record itself stays while a session is still bound to this root: a\n // pass mounting concurrently (a session disposed while another one turns)\n // would otherwise create a second record — and a second instance — for one\n // root. `sweepProjects` forgets it once nothing is bound any more.\n this.sweepProjects()\n }\n\n /**\n * Forget the project records no live session is bound to any more. A record\n * with mounts or a scope is never dropped: either one means someone still\n * holds the project.\n */\n private sweepProjects(): void {\n for (const [projectRoot, project] of this.projects) {\n if (project.scope !== undefined || project.mounts.size > 0) continue\n if (this.hasRootSessions(projectRoot)) continue\n this.projects.delete(projectRoot)\n }\n }\n\n /** Whether any live session resolved its working directory to one root. */\n private hasRootSessions(projectRoot: string): boolean {\n for (const state of this.states.values()) {\n if (state.projectRoot === projectRoot) return true\n }\n return false\n }\n\n /**\n * The project record one root's sessions share, created with its first holder\n * and forgotten when its last one lets go.\n * @param projectRoot - resolved project root.\n * @returns the live record.\n */\n private ensureProject(projectRoot: string): ProjectState {\n const existing = this.projects.get(projectRoot)\n if (existing !== undefined) return existing\n const project: ProjectState = {\n projectRoot,\n key: { projectRoot },\n scope: undefined,\n mounts: new Map(),\n shared: true,\n }\n this.projects.set(projectRoot, project)\n return project\n }\n\n /**\n * The home one session mounts in: the project it holds, bridged or joined.\n * `undefined` while it holds nothing.\n * @param state - the session to read.\n * @returns the session's mount home, or `undefined` when it holds none.\n */\n private homeOf(state: AgentState): MountHome | undefined {\n return state.project\n }\n\n /**\n * The mounts one session renders right now: its own home's when it has one for\n * this root, otherwise the project's shared set, so a session that holds\n * nothing still notices another session's mounts and re-renders its rows.\n * @param state - the session to read.\n * @param projectRoot - the project root the pass is reconciling.\n * @returns the mount map whose changes this session's digest tracks.\n */\n private visibleMounts(state: AgentState, projectRoot: string): ReadonlyMap<string, MountedInstance> {\n const home = this.homeOf(state)\n if (home !== undefined && home.projectRoot === projectRoot) return home.mounts\n return this.projects.get(projectRoot)?.mounts ?? NO_MOUNTS\n }\n\n /**\n * The live mounts one session currently holds. Empty for a session that holds\n * nothing: the servers run for their project, and only a holder shares them.\n * @param state - the session to read.\n * @returns the shared mount map, or a shared empty one.\n */\n private mountsOf(state: AgentState): ReadonlyMap<string, MountedInstance> {\n return this.homeOf(state)?.mounts ?? NO_MOUNTS\n }\n\n /**\n * The `serverName` every one of the session's mounts registers under.\n *\n * The registry — and every name it publishes — is keyed by this, not by the\n * declared name: a shadowed declaration registers as its local alias, and a\n * lookup by the contested name would read as \"this project mounts nothing\".\n * @param state - the session to read.\n * @returns the runtime names, one per live mount.\n */\n private runtimeNamesOf(state: AgentState): Set<string> {\n return new Set([...this.mountsOf(state).values()].map((mount) => mount.runtimeName))\n }\n\n /**\n * Unregister everything the current scope's session wiring installed. The\n * scope fiber disposes the same registrations with the real services, while a\n * host that publishes plain `systemPrompt`/`tools` stubs has only this path.\n * Idempotent.\n */\n private releaseWiring(state: AgentState): void {\n this.releaseGuidance(state)\n this.releaseActivation(state)\n }\n\n /**\n * Unregister the guidance section of the current scope, if one is installed.\n * Released exactly where the scope is — an idle release and agent disposal —\n * so no section ever describes mounts that are gone.\n */\n private releaseGuidance(state: AgentState): void {\n const dispose = state.guidanceDispose\n state.guidanceDispose = undefined\n if (dispose === undefined) return\n try {\n dispose()\n } catch (error) {\n this.ctx.logger.warn(\n `project-mcp: releasing guidance for session ${state.agent.id} failed: ${errorText(error)}`,\n )\n }\n }\n\n /**\n * Unregister the activation wiring of the current scope. Idempotent: the\n * scope fiber disposes the same registrations with the real registry, while a\n * host that publishes a plain `tools` stub has only this path.\n */\n private releaseActivation(state: AgentState): void {\n const dispose = state.activationDispose\n state.activationDispose = undefined\n if (dispose === undefined) return\n try {\n dispose()\n } catch (error) {\n this.ctx.logger.warn(\n `project-mcp: releasing activation for session ${state.agent.id} failed: ${errorText(error)}`,\n )\n }\n }\n\n /**\n * Ask for a pass. A pending pass is kept instead of being pushed back: the\n * rescan tick is often shorter than the debounce, and restarting the timer on\n * every tick would starve reconciliation forever. Bursts of watcher events\n * still collapse into the one queued pass, and each pass re-reads the\n * documents through the digest, so a late event costs one cheap pass.\n */\n private schedule(reason: string): void {\n if (this.disposed) return\n this.ctx.logger.debug?.(`project-mcp: sync scheduled (${reason})`)\n if (this.debounce !== undefined) return\n this.debounce = setTimeout(() => {\n this.debounce = undefined\n void this.enqueue(NO_REQUESTS)\n }, this.config.debounceMs)\n this.debounce.unref?.()\n }\n\n /**\n * Turn boundary. `running` is the moment a session becomes active, which is\n * what `lazy` waits for; `idle` closes the busy window that idle release\n * watches. A plain notification, so it never delays a turn.\n */\n private onStatus(event: AgentEventLike): void {\n if (this.disposed) return\n const state = this.states.get(event.agent.id)\n if (state === undefined) return\n // Both transitions are an activity boundary: a tool that has not been called\n // for `toolIdleMs` falls out here, before the turn that follows can see it.\n this.pruneActivation(state)\n if (event.status === 'running') {\n this.touch(state, { activate: true, busy: true })\n return\n }\n this.touch(state, { activate: false, busy: false })\n }\n\n /**\n * Before every step of a turn: keep this session's project mounted, waiting\n * for a pending activation so that the step's request already sees the\n * project's tools. The waterfall always continues — a project MCP server is\n * never a reason to hold up an agent step.\n */\n private async onPreStep(event: AgentEventLike, next: () => Promise<unknown>): Promise<unknown> {\n try {\n const state = this.states.get(event.agent.id)\n if (state !== undefined) {\n // This hook is the harness's own step boundary, so it is where the\n // per-session counter advances: an activation made during this step,\n // and the row a panel reads after it, both carry the number of the step\n // they belong to instead of a placeholder.\n state.step += 1\n if (!this.disposed) {\n this.touch(state, { activate: true })\n await this.awaitActivation(state)\n }\n }\n } catch (error) {\n this.ctx.logger.warn(`project-mcp: activation before a step failed: ${errorText(error)}`)\n }\n return next()\n }\n\n /** Record activity and, with nothing mounted, ask for an activation pass. */\n private touch(state: AgentState, options: { activate: boolean; busy?: boolean }): void {\n state.lastActivityAt = Date.now()\n if (options.busy !== undefined) state.busy = options.busy\n if (!options.activate || this.mountsOf(state).size > 0) return\n state.activationPending = true\n this.schedule('activity')\n }\n\n /**\n * Wait (bounded) for the activation pass a turn asked for.\n *\n * The pass carries no operator request on purpose: the caller's\n * `activationPending` is what entitles this session to mount, and leaving the\n * request empty is what keeps the pass from starting servers in every other\n * project whose sessions happen to be live.\n */\n private async awaitActivation(state: AgentState): Promise<void> {\n if (!state.activationPending) return\n const pass = this.enqueue(NO_REQUESTS).catch(() => undefined)\n const waitMs = this.config.activationWaitMs\n if (waitMs <= 0) return\n await Promise.race([pass, delay(waitMs)])\n }\n\n /**\n * Reconcile every known session once, then the sweep and the watchers.\n * @param requests - the sessions that may mount without their own turn asking.\n */\n private async runPass(requests: PassRequests): Promise<void> {\n if (this.disposed) return\n // A session the host no longer lists is finished: no later event will ever\n // report it, so this pass is the path that hands its mounts back.\n await this.releaseAbandoned()\n // Sessions are independent: one slow connect must not serialize the rest.\n await Promise.all(\n [...this.states.values()].map(async (state) => {\n try {\n await this.syncAgent(state, requests)\n } catch (error) {\n this.ctx.logger.warn(\n `project-mcp: sync failed for session ${state.agent.id}: ${errorText(error)}`,\n )\n }\n }),\n )\n await this.evictIdle()\n this.sweepProjects()\n this.syncWatchers()\n this.notify()\n }\n\n /**\n * Release the mounts of sessions that have been quiet for `idleTimeoutMs`.\n * Their rows stay visible as `idle`, so the project's declaration remains\n * discoverable while not a single child process is running for it.\n */\n private async evictIdle(): Promise<void> {\n const timeout = this.config.idleTimeoutMs\n if (timeout <= 0) return\n const now = Date.now()\n for (const state of [...this.states.values()]) {\n if (this.mountsOf(state).size === 0 || this.working(state)) continue\n const since = state.lastActivityAt\n if (since === undefined || now - since < timeout) continue\n await this.releaseMounts(\n state,\n (count) => ({\n code: 'idle.releasedInactive',\n text: `released after ${formatSeconds(now - since)} without activity — ${count} server(s) stopped; the next turn mounts them again`,\n params: { seconds: formatSeconds(now - since), count: String(count) },\n }),\n { code: 'unmount.reason.sessionIdle', text: 'the session went idle' },\n )\n }\n }\n\n /**\n * Give one session's servers back now, or every mounted session's when no id\n * is given. Drives the panel's \"release\" action; the rows stay as `idle` and\n * the next turn mounts them again. A session that releases the last hold on a\n * project takes the shared instance down with it, and one that releases while\n * another session of the project holds leaves it running for that session.\n */\n async release(agentId?: string): Promise<void> {\n for (const state of [...this.states.values()]) {\n if (agentId !== undefined && state.agent.id !== agentId) continue\n if (this.mountsOf(state).size === 0) continue\n await this.releaseMounts(\n state,\n (count) => ({\n code: 'idle.releasedRequest',\n text: `released on request — ${count} server(s) stopped; the next turn mounts them again`,\n params: { count: String(count) },\n }),\n { code: 'unmount.reason.operatorReleased', text: 'an operator released it' },\n )\n }\n this.notify()\n }\n\n /**\n * Give one session's hold back, keeping its rows as `idle`.\n *\n * The shared servers themselves follow the last holder: this detaches the\n * session (its scope, wiring and parent link) and releases the project only\n * when no other session holds it, so releasing one session of a project that\n * another session is still working in leaves that session's servers running.\n * @param state - the session releasing.\n * @param describe - reason for its rows, given the number of servers it held.\n */\n private async releaseMounts(\n state: AgentState,\n describe: (count: number) => CodedText,\n reason: CodedText,\n ): Promise<void> {\n const held = this.homeOf(state)\n const mounted = new Set(held === undefined ? [] : held.mounts.keys())\n const diagnostics = new Set(\n [...(held?.mounts.values() ?? [])].flatMap((mount) =>\n mount.detail === undefined ? [] : [mount.detail],\n ),\n )\n state.activationPending = false\n state.busy = false\n await this.detach(state, reason)\n const summary = describe(mounted.size)\n state.rows = state.rows.map((row) => (mounted.has(row.name) ? idleRow(row, summary) : row))\n state.issues = state.issues.filter((issue) => !diagnostics.has(issue.message))\n this.ctx.logger.debug?.(`project-mcp: session ${state.agent.id}: ${summary.text}`)\n }\n\n /**\n * Re-read one agent's project and reconcile its mounts.\n * @param state - the session to reconcile.\n * @param operatorRequested - an operator pass named this exact session.\n */\n async syncAgent(state: AgentState, requests: PassRequests = NO_REQUESTS): Promise<void> {\n const agent = state.agent\n const cwd = agent.session.header?.cwd\n state.cwd = cwd\n const projectRoot =\n cwd === undefined || cwd === ''\n ? undefined\n : findProjectRoot(cwd, this.config.projectMarkers, this.config.fileMarkers)\n // An operator asks for a session directly, or for a project — the second\n // only matches once the session's own working directory has been read,\n // which is why it is decided here rather than before the pass.\n const operatorRequested =\n requests === 'all' ||\n ('projectRoot' in requests\n ? requests.projectRoot === projectRoot\n : requests.has(state.agent.id))\n\n if (projectRoot === undefined) {\n // The root was just read and none was found. A session's working directory\n // cannot stop being inside its project without the session changing, so\n // this is a stale read — a concurrent sweep of the working tree, a temp\n // directory removed under a test. Either way the session keeps the hold it\n // has: a release here would tear down live mounts that the next read finds\n // again, and a session that genuinely has no project holds nothing to\n // release. A pending first mount still has to be cleared, because no turn\n // should wait for a pass that has nothing to do.\n state.activationPending = false\n return\n }\n // A session that moved to another project starts from a clean scope.\n if (projectRoot !== state.projectRoot) {\n await this.disposeState(state, { code: 'unmount.reason.sessionMoved', text: 'the session moved to another project' })\n state.projectRoot = projectRoot\n }\n\n const { entries, issues, documents, sources } = this.readProject(projectRoot)\n const reserved = this.config.profileWins ? this.profileServerNames() : new Set<string>()\n // The local names this project's shadowed declarations would take, resolved\n // once for the whole pass: the row, the mount and the conflict report all\n // read this one answer, so the alias the panel offers is the alias the\n // registry ends up carrying.\n const policy = this.policyFor(projectRoot)\n const aliases = resolveConflictNames({\n entries: entries.map((entry) => ({ name: entry.name, reserved: reserved.has(entry.name) })),\n prefix: this.config.localPrefix,\n projectRoot,\n })\n /**\n * The shadowed names this pass actually mounts, and under which name.\n *\n * A name whose user kept the profile's copy is deliberately absent: it is a\n * conflict report, not a mount. `local` mounts this project's entry under the\n * alias the panel offers; `native` mounts it under the name it declares,\n * where it is the nearer declaration for this project's own sessions and so\n * shadows the profile instance's tools of that name there. The profile\n * instance itself is never touched: it keeps running, and every other project\n * keeps resolving it. A `native` entry is therefore mapped to `undefined` and\n * is still a chosen mount — `has` is the question, never the value.\n */\n const choices = aliasesOf(policy)\n const chosen = new Map<string, string | undefined>()\n for (const [name, alias] of aliases) {\n const choice = choices[name] ?? 'profile'\n if (choice === 'local') chosen.set(name, alias)\n else if (choice === 'native') chosen.set(name, undefined)\n }\n state.conflicts = conflictsFor(entries, sources, reserved, aliases, policy)\n\n const rows: ServerRow[] = []\n const desired = new Map<string, ParsedEntry>()\n for (const entry of entries) {\n const base = baseRow(entry, projectRoot, documents.get(entry.source))\n if (entry.error !== undefined) {\n rows.push({\n ...base,\n status: 'error',\n detail: entry.error,\n ...(entry.errorCode === undefined ? {} : { detailCode: entry.errorCode }),\n ...(entry.errorParams === undefined ? {} : { detailParams: entry.errorParams }),\n })\n continue\n }\n if (!entry.enabled) {\n rows.push({ ...base, status: 'disabled', detail: 'declared with enabled: false', detailCode: 'idle.disabled' })\n continue\n }\n if (reserved.has(entry.name)) {\n const alias = aliases.get(entry.name)\n // The user chose this project's copy, and the pass has a name to mount it\n // under: the local alias, or the contested name itself when they opted to\n // shadow the profile's instance in this project's sessions. Either way the\n // declaration mounts like any other, and the profile's instance is left\n // running for every other project.\n if (chosen.has(entry.name)) {\n desired.set(entry.name, entry)\n // The row is `active` and carries no detail of its own: `decorate` drops\n // a row's detail while it has a mount, so a line explaining the choice\n // would never reach a surface. The conflict report below is where a\n // mounted name still says which of the three readings it is.\n const detail = conflictDetail(entry.name, alias)\n rows.push({\n ...base,\n detail: detail.text,\n detailCode: detail.code,\n ...(detail.params === undefined ? {} : { detailParams: detail.params }),\n })\n continue\n }\n const detail = conflictDetail(entry.name, alias)\n rows.push({\n ...base,\n status: 'conflict',\n detail: detail.text,\n detailCode: detail.code,\n ...(detail.params === undefined ? {} : { detailParams: detail.params }),\n })\n continue\n }\n desired.set(entry.name, entry)\n rows.push(base)\n }\n\n const documentIssues: SnapshotIssue[] = issues.map((issue) => ({\n source: issue.source,\n ...(issue.server === undefined ? {} : { server: issue.server }),\n level: issue.level,\n message: issue.message,\n ...(issue.code === undefined ? {} : { code: issue.code }),\n ...(issue.params === undefined ? {} : { params: issue.params }),\n }))\n\n // The project's shared instance, if it already has one. Its mounts are what\n // this session holds when it is already attached, and what it is about to\n // share when it attaches below — both are read live, never copied.\n const existing = this.projects.get(projectRoot)\n // The mounts whose changes this session's digest tracks: its own home's\n // when it has one, otherwise the project's shared set. A session that holds\n // nothing must still notice another session mounting, settling or dropping\n // a server, because its rows are a rendering of exactly those mounts.\n const mounts = this.visibleMounts(state, projectRoot)\n\n // Steady state: the documents, their resolved configs, the profile\n // reservations and the published state of the shared mounts are identical\n // and every mount has settled, so this pass has nothing to reconcile — no\n // merge, no tool-catalog scan, no remount. The shared-mount part of the\n // digest matters because another session of this project can have mounted,\n // settled or dropped a server without any document changing, and this\n // session's rows are a rendering of exactly those mounts.\n //\n // One state is *not* settled even so: a session whose project declares\n // something mountable and which `lazy` has mounted nothing for. Its inputs\n // are byte-identical to the pass that only published the declaration, so the\n // digest cannot tell them apart — an operator pass (`syncNow`, `retry`) has\n // to mount it now instead of waiting for a turn that may never come.\n const mountable = desired.size > 0\n // Whether *this* session already holds mounts. The project can be running\n // for another session of it while this one holds nothing, and such a\n // session must not be attached by a pass of its own: holding would make it\n // keep an instance it never asked for alive past its last real holder, and\n // would put the project's tools into a session that never turned.\n const held = this.mountsOf(state).size > 0\n // What this session is allowed to start in this pass, and why. `undefined`\n // is the answer for every session that is not working in its project: it is\n // live, it declares servers, and none of them may run.\n const trigger = mountTrigger({\n lazy: this.config.lazy,\n activationPending: state.activationPending,\n mounted: held,\n operatorRequested,\n })\n const awaitedMount = trigger === 'operator' && this.config.lazy && !held && mountable\n /**\n * Identity of this pass's inputs, recomputed once the mounts settled — a\n * mount created or dropped by this very pass is then part of it, so the\n * next pass recognizes the steady state instead of rebuilding one more time.\n */\n const settle = (): void => {\n state.digest = digestOf(entries, reserved, this.visibleMounts(state, projectRoot), chosen)\n }\n /**\n * The project record; only a session that may run something takes a hold,\n * and minting the record is what lets every other session of the root share\n * the instance it starts.\n */\n const project = trigger === undefined || desired.size === 0 ? existing : this.ensureProject(projectRoot)\n const digest = digestOf(entries, reserved, mounts, chosen)\n if (!awaitedMount && state.digest === digest && this.settled(state) && !state.activationPending) return\n\n // `lazy` defers a session's *first* mount to its first turn. Removals and\n // edits are always reconciled below; an operator call (`syncNow`, `retry`)\n // and a pending activation mount regardless.\n //\n // `mounted` in the decision above makes `undefined` unreachable while this\n // session holds servers, so publishing rows here never hides a live mount.\n if (trigger === undefined) {\n // Nothing runs for this session: publish what the project declares (it is\n // what the next turn will mount) without starting a single server.\n state.rows = rows.map((row) => (desired.has(row.name) ? idleRow(row, LAZY_DETAIL) : row))\n state.issues = documentIssues\n settle()\n return\n }\n\n // A session that may mount takes its hold first: the parent link is what\n // makes the project's already running servers visible to it, and minting\n // the session scope is what carries the session wiring. A session whose\n // scope key the harness already parented cannot take that link at all and\n // gets a home of its own, which is why the hold returns the home the pass\n // reconciles instead of the pass assuming the project's. A project that\n // declares nothing mountable mints no session scope at all — the\n // declarations below are published and nothing runs.\n let home: MountHome | undefined\n if (desired.size > 0 && project !== undefined) {\n home = await this.holdProject(state, project)\n } else {\n home = this.homeOf(state) ?? existing\n }\n\n if (home !== undefined) {\n // One home is reconciled, not one session's share of it: an edit or a\n // removal in the document is every holder's business, and a declaration\n // either exists for all sessions that resolve the home or for none.\n for (const [name, mount] of [...home.mounts]) {\n const entry = desired.get(name)\n if (entry?.config === undefined) {\n // A reserved name this project was mounting leaves for one of two\n // reasons — the declaration is gone, or the user went back to the\n // profile's copy — and the lifecycle log is where a reader tells them\n // apart.\n await this.unmount(\n home,\n name,\n reserved.has(name)\n ? { code: 'unmount.reason.profileShown', text: 'this project shows the profile-level copy instead' }\n : { code: 'unmount.reason.undeclared', text: 'the documents no longer declare it' },\n )\n continue\n }\n // A mount that no longer carries the local name this pass chose is\n // remounted, not kept: the alias is the whole of what the user changed,\n // and a registration is only ever created under one name.\n if (mount.runtimeName !== runtimeNameOf(entry, chosen.get(name))) {\n await this.unmount(home, name, { code: 'unmount.reason.nameChanged', text: 'its local name changed' })\n continue\n }\n if (mount.fingerprint !== fingerprint(entry.config)) {\n await this.unmount(home, name, { code: 'unmount.reason.declarationChanged', text: 'its declaration changed' })\n }\n }\n\n // Registration only: no `mount` here waits for its server, so this loop\n // is what a pass costs per declaration, not the handshake behind it.\n for (const [name, entry] of desired) {\n if (entry.config === undefined || home.mounts.has(name)) continue\n this.mount(state, home, name, entry, trigger, chosen.get(name))\n }\n if (home.mounts.size === 0) {\n // Nothing is mounted by design: this session keeps no hold, and a\n // shared scope goes with its last holder, so no server outlives the\n // session that asked for it.\n await this.detach(state, { code: 'unmount.reason.nothingMountable', text: 'nothing it declares is mountable any more' })\n if (home.shared && !this.hasHolders(home as ProjectState)) {\n await this.releaseProject(home as ProjectState, { code: 'unmount.reason.nothingMountable', text: 'nothing it declares is mountable any more' })\n }\n }\n }\n\n // The declarations as the documents give them. A mounted server keeps its\n // declared row here: the mount's own status is applied when the picture is\n // read ({@link liveRows}), so a drop, a new mount or a connect that happens\n // between two passes is visible without waiting for the next one.\n state.rows = rows.map((row) =>\n desired.has(row.name) && home?.mounts.has(row.name) !== true\n // A declaration that `lazy` has not mounted yet, or a newly added one.\n ? idleRow(row, LAZY_DETAIL)\n : row,\n )\n state.issues = documentIssues\n state.activationPending = false\n // Start the idle clock for a session that never reported activity, so an\n // unused one still releases its servers.\n state.lastActivityAt ??= Date.now()\n this.refreshStatuses(agent, state)\n // After the status scan, so a mount the watchdog has just flagged reports\n // its stall in the same pass that turned its row into an error.\n state.issues.push(...this.mountDiagnostics(state, projectRoot))\n settle()\n // The rows this session contributes are what they are now: announce them\n // before the pass moves on, so a mount that needed its full connect window\n // does not hold the whole picture back.\n this.notify()\n }\n\n /**\n * Start one declared server in the session's mount home and record the mount,\n * which every session that home serves then resolves.\n *\n * Exactly one `info` line is written per created process — never on a rescan\n * that re-derives the same mount, and never when another session of the\n * project attaches to a shared instance that is already running — so an\n * operator can tell which session caused a server to start, in which project,\n * and what asked for it.\n *\n * The registration is the whole of what this pass does here: the fiber's\n * activation is *watched*, never awaited, so a server that never answers\n * costs the pass — and with it every turn waiting on that pass — nothing.\n * The mount is recorded before the wait, so a later pass finds it in place\n * and mounts nothing a second time; the outcome reaches the row through\n * {@link observeActivation} on failure and through {@link refreshStatuses}\n * on success.\n * @param state - the session whose pass creates the instance.\n * @param home - the scope the instance belongs to: the project's shared one,\n * or the session's own when it could not join the project's chain.\n * @param name - declared `serverName`.\n * @param entry - the parsed declaration to mount.\n * @param trigger - why this pass was allowed to start it.\n * @param alias - local name to register under, when a profile instance owns\n * the declared one and the user chose to see the project's copy too.\n */\n private mount(\n state: AgentState,\n home: MountHome,\n name: string,\n entry: ParsedEntry,\n trigger: MountTrigger,\n alias?: string,\n ): void {\n const config = entry.config\n if (config === undefined) return\n const runtimeName = runtimeNameOf(entry, alias)\n const mount: MountedInstance = {\n name,\n runtimeName,\n projectRoot: home.projectRoot,\n fingerprint: fingerprint(config),\n fiber: undefined,\n status: 'connecting',\n detail: undefined,\n detailCode: undefined,\n detailParams: undefined,\n source: entry.source,\n transport: config.transport,\n endpoint: describeEndpoint(config),\n startedAt: Date.now(),\n stalled: false,\n failed: false,\n }\n home.mounts.set(name, mount)\n // The row turns `connecting` the moment the mount exists; announcing it here\n // is what makes a `Retry` visible in the panel while the server is still\n // booting, instead of only when the pass that started it returns.\n this.notify()\n try {\n const scope = this.ensureProjectScope(home as ProjectState)\n if (scope === undefined) {\n throw new Error('the project scope could not be minted, so the instance has no scope to register in')\n }\n const plugin = this.options.plugin ?? mcpClient\n // Call through the receiver: `ctx.plugin` is a context-bound method and\n // an extracted reference would lose `this`.\n const target = scope.ctx as unknown as {\n plugin(plugin: unknown, config: unknown): MountFiber\n }\n const fiber = target.plugin(plugin, clientConfig(runtimeConfigOf(config, runtimeName)))\n mount.fiber = fiber\n const sharing: CodedText = state.parentLinked\n ? { code: 'mount.sharingShared', text: 'one shared instance for every session of this project' }\n : {\n code: 'mount.sharingForwarded',\n text: \"one shared instance for this project, forwarded into this session's own layer\",\n }\n this.logLifecycle({\n at: Date.now(),\n level: 'info',\n logLevel: 'info',\n projectRoot: mount.projectRoot,\n sessionId: state.agent.id,\n server: name,\n message: `mounting for session ${state.agent.id} (trigger: ${trigger}; ${sharing.text})`,\n code: 'mount.starting',\n params: { sessionId: state.agent.id, trigger, sharingCode: sharing.code },\n line: `mounting ${name}${runtimeName === name ? '' : ` as ${runtimeName}`} for session ${state.agent.id} in ${home.projectRoot} (trigger: ${trigger}; ${sharing.text})`,\n })\n // Not awaited: the pass returns with the mount recorded and `connecting`,\n // and whatever the activation turns out to be is written from behind it.\n this.observeActivation(home, mount, `activation of ${name}`, fiber)\n } catch (error) {\n this.recordMountFailure(home, mount, error)\n }\n }\n\n /**\n * Publish one lifecycle event, and announce it.\n *\n * The plugin's five lifecycle facts — mounting, `is up`, a stall, a failed\n * mount, unmounting — leave the runtime through this one method and no other,\n * and the snapshot announcement follows every one of them, as it did when each\n * site kept the three writes in step by hand. What the DSH log prints and what\n * the ring holds are the subscribers' business now: the runtime only says what\n * happened (`src/notifications.ts`).\n * @param event - the fact, already carrying its level, session and server.\n */\n private logLifecycle(event: PluginEvent): void {\n emitEvent(event)\n this.notify()\n }\n\n /**\n * Watch one mount's activation in the background, so the registering pass\n * never waits for it.\n *\n * A failure is the one outcome the pass used to report itself, and it is\n * written exactly as it was when it did: the row turns `error`, `failed`\n * keeps {@link refreshStatuses} from polling a dead fiber, and the detail is\n * {@link failureDetail}. A success and a timeout write nothing — a mount\n * whose tools became visible is turned `active` by the status scan of the\n * next pass, which logs the `is up` line, and a mount that is merely slow is\n * the watchdog's stall to report.\n *\n * Nothing awaits the returned promise, so it must never reject: `waitFor`\n * already answers a rejected fiber with `{ kind: 'failed' }`, and the final\n * `catch` is the backstop for the recorder itself.\n * @param home - the home the mount was recorded in, read to see it is current.\n * @param mount - the mount whose activation this watches.\n * @param label - the wait label, as `waitFor` names it in the debug line.\n * @param fiber - the fiber whose activation this watches.\n */\n private observeActivation(\n home: MountHome,\n mount: MountedInstance,\n label: string,\n fiber: MountFiber,\n ): void {\n void this.settleActivation(home, mount, label, fiber).catch((error: unknown) => {\n this.ctx.logger.warn(\n `project-mcp: watching the activation of ${mount.name} failed: ${errorText(error)}`,\n )\n })\n }\n\n /**\n * The watched wait itself: one activation to its outcome, then the failure\n * written if it had one.\n * @param home - the home the mount was recorded in.\n * @param mount - the mount whose activation this waits for.\n * @param label - the wait label, as `waitFor` names it in the debug line.\n * @param fiber - the fiber whose activation this waits for.\n */\n private async settleActivation(\n home: MountHome,\n mount: MountedInstance,\n label: string,\n fiber: MountFiber,\n ): Promise<void> {\n const outcome = await this.waitFor(label, activation(fiber))\n // A later pass may already have dropped or replaced this mount — an operator\n // retry, an edited declaration, a teardown. The fiber going down with its\n // home is not a failure of a mount nobody serves any more.\n if (home.mounts.get(mount.name) !== mount) return\n if (outcome.kind === 'failed') {\n this.recordMountFailure(home, mount, outcome.error)\n this.announceHome(home)\n return\n }\n // The server's tools exist as of this moment, so this is where the sessions\n // that read the project through the bridge actually receive them: the mount\n // was registered before its fiber had published anything, and a session whose\n // key predates that registration has no other signal. On a real registry the\n // `tools/change` subscription carries the same news.\n this.syncBridgesOf(home)\n // Success: the tools may have appeared long after the pass that registered\n // the mount returned, and a deployment with `watch: false` and no idle sweep\n // has no rescan timer to notice. Announcing here is what turns `connecting`\n // into `active` — and logs `is up` — the moment it is true, instead of up to\n // `rescanIntervalMs` later.\n this.announceHome(home)\n }\n\n /**\n * Re-read one home's mounts for every session that holds it, then tell the\n * panels.\n *\n * Called from behind a pass — a mount settles after its pass has returned —\n * so for a deployment without a rescan timer this is the only moment that\n * moves a row off `connecting`. Idempotent: the transition log fires on a\n * change, so a second call for the same mount writes nothing.\n * @param home - the home whose instances settled.\n */\n private announceHome(home: MountHome): void {\n if (this.disposed) return\n for (const state of this.states.values()) {\n if (this.homeOf(state) !== home) continue\n this.refreshStatuses(state.agent, state)\n }\n this.notify()\n }\n\n /**\n * Record a mount that could not be activated: the row's `error`, the detail\n * an operator reads, and the one warning line. Shared by the synchronous\n * registration failures and the watched activations above, so both report\n * the same three facts in the same words.\n * @param home - the home the failed instance belongs to.\n * @param mount - the mount to mark failed.\n * @param error - what the fiber or the registration failed with.\n */\n private recordMountFailure(home: MountHome, mount: MountedInstance, error: unknown): void {\n mount.status = 'error'\n mount.failed = true\n const failure = failureDetail(mount, error)\n mount.detail = failure.text\n mount.detailCode = failure.code\n mount.detailParams = failure.params\n // The Logs tab gets the same three facts, first line as the row's message and\n // the whole detail for its second line. The instance serves every session of\n // its project, so the failure is a project event and names no session.\n this.logLifecycle({\n at: Date.now(),\n level: 'error',\n logLevel: 'warn',\n projectRoot: mount.projectRoot,\n server: mount.name,\n message: `mount failed — ${errorText(error)}`,\n code: 'mount.failed',\n params: { error: errorText(error) },\n detail: mount.detail,\n detailCode: failure.code,\n ...(failure.params === undefined ? {} : { detailParams: failure.params }),\n line: mount.detail,\n })\n }\n\n /**\n * The session-scope context the bridge registers through: the minted scope's\n * context carries the session's scope tag, so a registration made through it\n * lands in exactly this session's layer.\n */\n private bridgeContextOf(scope: Pick<Scope, 'ctx' | 'dispose'>): BridgeContextLike {\n if (this.options.bridgeContext !== undefined) return this.options.bridgeContext(scope)\n return {\n get: (name) => (scope.ctx as unknown as { get(service: string): unknown }).get(name),\n }\n }\n\n /** The registry surface the bridge reads; defaults to the plugin's own. */\n private bridgeRegistry(): BridgeRegistryLike {\n if (this.options.registry !== undefined) return this.options.registry\n const ctx = this.ctx as unknown as {\n tools: {\n get(name: string, scope?: object): ReturnType<BridgeRegistryLike['get']>\n schemas(scope?: object): ReturnType<BridgeRegistryLike['schemas']>\n }\n }\n // Bound through the receiver: an extracted `ctx.tools.get` reference would\n // lose the registry's `this`.\n return {\n get: (name, scope) => ctx.tools.get(name, scope),\n schemas: (scope) => ctx.tools.schemas(scope),\n }\n }\n\n /**\n * Install the forwarding bridge on one session: thin definitions in the\n * session's own layer over the project's live tools.\n *\n * Idempotent while the session keeps its project. The `tools/change`\n * subscription is what keeps the bridge level with a server that publishes\n * its tools long after the pass that registered the mount returned — the\n * session's layer is brought up to date before the next turn reads it.\n * A failure is contained: the session keeps its hold on the project's servers\n * and gets no tools from them until the next pass retries the sync.\n * @param state - the session taking the bridge.\n * @param project - the project whose tools are forwarded.\n */\n private installBridge(state: AgentState, project: ProjectState): void {\n if (state.bridge !== undefined || state.scope === undefined) return\n const context = this.bridgeContextOf(state.scope)\n const registry = this.bridgeRegistry()\n const servers = (): ReadonlySet<string> => this.runtimeNamesOf(state)\n const batch = new ForwardBatch({\n names: () => {\n const project = state.project\n // No project, nothing to probe. An empty key here would read the\n // *global* view instead — every tool any scope registered — and each\n // pass would forward names this session's project never published.\n if (project === undefined) return undefined\n try {\n return projectToolNames(\n project.key,\n (scope) => this.bridgeSchemas(scope),\n servers(),\n )\n } catch (error) {\n // A probe that failed says nothing about the project's set: the batch\n // it could not describe is the batch that stays live.\n this.ctx.logger.warn(\n `project-mcp: reading the tools to forward to session ${state.agent.id} failed: ${errorText(error)}`,\n )\n return undefined\n }\n },\n deferred: () => this.deferredNamesOf(state),\n register: (names, deferred) => {\n const project = state.project\n if (project === undefined) return () => undefined\n return forwardProjectTools({\n ctx: context,\n project: project.key,\n names,\n deferred: (name) => deferred.has(name),\n registry,\n })\n },\n onError: (error) => this.reportBridgeFailure(state, error),\n })\n const bridge: BridgeForwarders = {\n batch,\n detach: () => undefined,\n }\n // The listener lives on the session scope and is dropped with it, so a\n // released session never keeps syncing against a project it left. It only\n // *notes* the change: the registry emits this once per entry registered and\n // once per entry disposed, and a pass per event is what held the event loop.\n const detach = state.scope.ctx.on('tools/change', () => this.noteBridge(state))\n bridge.detach = typeof detach === 'function' ? (detach as () => void) : () => undefined\n state.bridge = bridge\n this.syncBridge(state)\n }\n\n /**\n * Bring one session's forwarders level with the project's live tools.\n *\n * The pass itself — including the re-entry its own registrations force on it\n * through `tools/change` — belongs to the session's {@link ForwardBatch}; this\n * is where a failure is contained and reported. A failed pass leaves the\n * session with no forwarder until the next pass retries (`namesIn` stays\n * unset), and never takes the session's hold on the project down.\n * @param state - the session whose bridge to sync.\n */\n private syncBridge(state: AgentState): void {\n const bridge = state.bridge\n if (bridge === undefined) return\n try {\n bridge.batch.sync()\n } catch (error) {\n this.reportBridgeFailure(state, error)\n }\n }\n\n /**\n * Note one registry change for one session's bridge, off the emitter's stack.\n *\n * The event this answers is emitted synchronously from inside the registry's\n * own insertion and removal — once per entry in, once per entry out — so one\n * MCP generation swap is a burst of thousands. Running the pass here would\n * make whoever registered a tool pay for every session watching the project,\n * and each pass projects the project's whole catalog. The batch folds the\n * burst into one queued pass instead, which is also why this is not\n * {@link syncBridge}: the read paths, the mount settle and the scope wiring\n * all bring the batch level synchronously, before anything reads the layer.\n * @param state - the session whose bridge noticed the change.\n */\n private noteBridge(state: AgentState): void {\n state.bridge?.batch.note()\n }\n\n /**\n * Write the one warning line a failed bridge pass is allowed.\n *\n * Shared by the synchronous pass and by the one a batch runs on its own: a\n * scheduled pass has no caller left to propagate its failure to, so the batch\n * hands it here through `onError` rather than swallowing it.\n * @param state - the session whose bridge failed.\n * @param error - what the pass threw.\n */\n private reportBridgeFailure(state: AgentState, error: unknown): void {\n this.ctx.logger.warn(\n `project-mcp: forwarding the tools of ${state.project?.projectRoot ?? 'the project'} into session ${state.agent.id} failed: ${errorText(error)}`,\n )\n }\n\n /** The project scope's visible schemas, as {@link projectToolNames} reads them. */\n private bridgeSchemas(scope: object): ReturnType<BridgeRegistryLike['schemas']> {\n return this.bridgeRegistry().schemas(scope)\n }\n\n /** Drop one session's bridge: its forwarders and its subscription. Idempotent. */\n private dropBridge(state: AgentState): void {\n const bridge = state.bridge\n if (bridge === undefined) return\n state.bridge = undefined\n try {\n bridge.batch.drop()\n } catch (error) {\n this.ctx.logger.warn(\n `project-mcp: dropping the forwarded tools of session ${state.agent.id} failed: ${errorText(error)}`,\n )\n }\n try {\n bridge.detach()\n } catch {\n // The scope disposal that follows drops the same subscription; a throw\n // here must not keep the session's hold from being released.\n }\n }\n\n /**\n * The project's shared scope, minted with its first mount. One scope per\n * project is what makes mcp-client's `serverName` reservation per project\n * rather than per session, and it is disposed when the project's last holder\n * lets go, so the instance lifetime matches a per-session mount's.\n * @param project - the project to mount into.\n * @returns the scope, reused when the project already has one.\n */\n private ensureProjectScope(project: ProjectState): Pick<Scope, 'ctx' | 'dispose'> {\n const existing = project.scope\n if (existing !== undefined) return existing\n const scope = this.mintScope(project.key)\n project.scope = scope\n return scope\n }\n\n /**\n * Wait for one fiber operation, bounded by `connectTimeoutMs`. A server that\n * never answers must not hold a pass (or a project's teardown) open forever;\n * the fiber stays alive and later passes keep watching it.\n */\n private async waitFor<T>(label: string, wait: Promise<T>): Promise<WaitOutcome<T>> {\n const limit = this.config.connectTimeoutMs\n const settled = wait.then(\n (value): WaitOutcome<T> => ({ kind: 'settled', value }),\n (error): WaitOutcome<T> => ({ kind: 'failed', error }),\n )\n if (limit <= 0) return await settled\n const outcome = await Promise.race([\n settled,\n delay(limit).then((): WaitOutcome<T> => ({ kind: 'timeout' })),\n ])\n if (outcome.kind === 'timeout') {\n this.ctx.logger.debug?.(\n `project-mcp: ${label} did not settle within ${formatSeconds(limit)}; the pass continues without it`,\n )\n }\n return outcome\n }\n\n /**\n * Whether every mount has settled, so a rescan can return without work. A\n * stalled mount keeps the pass alive on purpose: only a fresh status scan can\n * notice that the client's background retry finally connected.\n */\n private settled(state: AgentState): boolean {\n for (const mount of this.mountsOf(state).values()) {\n if (mount.stalled) return false\n if (mount.status !== 'active' && mount.status !== 'error') return false\n }\n return true\n }\n\n /**\n * Mint one scope through the injected factory, or through the module itself.\n * The parent link of a session key is established by {@link holdProject} before\n * this runs and deliberately not passed as `createScope`'s own `parent`\n * option: binding twice on one key throws, and the retained binding is what\n * makes a release and a project change re-linkable.\n * @param key - session key or project key the scope's registrations own.\n * @returns the minted scope.\n */\n private mintScope(key: AgentLike | ProjectScopeKey): Pick<Scope, 'ctx' | 'dispose'> {\n if (this.options.createScope !== undefined) return this.options.createScope(this.ctx, key)\n return createScope(this.ctx, key)\n }\n\n /**\n * Mint the session scope on first use and install the session wiring on it:\n * the project-MCP guidance section and, when activation is on, the wiring\n * that lets a project's MCP tools be *found* (`mcp_search_tools`) and put\n * back into an assembly a presentation plugin filtered.\n *\n * Both are installed once per scope and both read the project's live state, so\n * a rescan that changes the mounted set changes what they say without\n * re-registering anything. `detach` disposes the scope and releases the wiring\n * explicitly, and the next attach installs a fresh one over the surviving\n * session state.\n *\n * A failed mint is contained: the session keeps its hold on the shared mounts\n * (they are registered on the project scope, which is unaffected) and only\n * loses its own wiring, instead of failing the pass.\n */\n private ensureSessionScope(agent: AgentLike, state: AgentState): void {\n if (state.scope !== undefined) return\n let scope: Pick<Scope, 'ctx' | 'dispose'>\n try {\n scope = this.mintScope(state.agent)\n } catch (error) {\n this.ctx.logger.warn(\n `project-mcp: minting the scope of session ${agent.id} failed: ${errorText(error)}`,\n )\n return\n }\n state.scope = scope\n // The guidance section is independent of activation: with activation off\n // every tool is listed and the section only names the mount, so it stays a\n // true statement either way.\n if (this.config.guidanceEnabled ?? DEFAULT_GUIDANCE_ENABLED) {\n try {\n state.guidanceDispose = installGuidance({\n ctx: scope.ctx as unknown as GuidanceContextLike,\n text: () => this.guidanceText(agent, state),\n onError: (error) => {\n this.ctx.logger.warn(\n `project-mcp: guidance section failed for session ${agent.id}: ${errorText(error)}`,\n )\n },\n })\n } catch (error) {\n this.ctx.logger.warn(\n `project-mcp: guidance wiring failed for session ${agent.id}: ${errorText(error)}`,\n )\n }\n }\n if (!(this.config.activationEnabled ?? DEFAULT_ACTIVATION_ENABLED)) return\n try {\n state.activationDispose = installActivation({\n ctx: scope.ctx as unknown as ActivationContextLike,\n state: () => this.seedActivation(state),\n setState: (next) => {\n state.activation = next\n },\n available: () => this.activationCandidates(state),\n visible: () => this.visibleSchemas(state),\n foreign: () => this.foreignNamesOf(state),\n // The policy is read at every assembly rather than captured here, so a\n // mode or pin stored from the panel applies from the next model step on\n // without re-minting the scope the listener lives in.\n policy: () => this.policyFor(state.projectRoot),\n // The presentation lives in this session's own forwarders (they carry\n // `deferLoading`), so every move of the offered set re-applies it there.\n // `note` and not `sync`: the pass belongs off the caller's stack, and a\n // burst of activation settles in one queued pass.\n onOfferedChanged: () => state.bridge?.batch.note(),\n // The step the session is on, read when a search activates names: the\n // wiring keeps no counter of its own, because an activation outlives\n // the scope the wiring lives in and its stamp has to outlive it too.\n step: () => state.step,\n onActivated: (names, step) => {\n for (const name of names) state.steps.set(name, step)\n },\n onCompaction: () => {\n // A step record belongs to the activation it was made for, so the ones\n // a compaction just dropped go with them — while a tool the session\n // really used keeps the step its offer happened on.\n this.pruneStepRecords(state)\n },\n autoState: state.auto ?? createAutoOfferState(),\n setAutoState: (next) => {\n state.auto = next\n },\n ...(this.config.activationAutoLimit === undefined\n ? {}\n : { autoLimit: this.config.activationAutoLimit }),\n ...(this.config.activationAutoStickySteps === undefined\n ? {}\n : { autoStickySteps: this.config.activationAutoStickySteps }),\n ...(this.config.activationToolBudgetChars === undefined\n ? {}\n : { toolBudgetChars: this.config.activationToolBudgetChars }),\n onError: (error) => {\n this.ctx.logger.warn(\n `project-mcp: activation failed for session ${agent.id}: ${errorText(error)}`,\n )\n },\n })\n } catch (error) {\n this.ctx.logger.warn(\n `project-mcp: activation wiring failed for session ${agent.id}: ${errorText(error)}`,\n )\n }\n }\n\n /**\n * The session's activation state, seeded from its project's counters on first\n * use. Later scopes of the same session keep it; only a project change or a\n * teardown drops it.\n */\n private seedActivation(state: AgentState): ActivationState {\n const existing = state.activation\n if (existing !== undefined) return existing\n const projectRoot = state.projectRoot\n const usage = projectRoot === undefined ? undefined : this.options.usage?.forProject(projectRoot)\n const seeded = createActivationState(\n seedFromUsage(usage, {\n count: this.config.activationSeeded ?? DEFAULT_ACTIVATION_SEEDED,\n minCalls: this.config.activationMinCalls ?? DEFAULT_ACTIVATION_MIN_CALLS,\n }),\n )\n state.activation = seeded\n return seeded\n }\n\n /**\n * The schemas this plugin may offer this session: exactly the tools whose\n * public name belongs to a server it mounted for this agent's project. A\n * profile-level or other-project tool is never a candidate, and the prefix is\n * never parsed blindly — the runtime's own mount records decide.\n */\n private activationCandidates(state: AgentState): ToolSchemaLike[] {\n const servers = this.runtimeNamesOf(state)\n if (servers.size === 0) return []\n return this.mountedSchemas(state)\n .filter((schema) => matchServer(schema.name, servers) !== undefined)\n }\n\n /**\n * The schemas the session's own mount home publishes, read through the home's\n * scope key rather than the session's.\n *\n * The two are the same catalog by construction: a session that joined the\n * project's chain resolves the project's layer, and a session that could not\n * gets exactly those tools forwarded into its own layer. Reading the home's\n * view is what keeps this probe independent of the forwarding timing — a\n * server is up as soon as its tools are registered on the project scope, and\n * a bridge sync that has not run yet must not read as \"not up\".\n * @param state - the session whose home is probed.\n * @returns the visible schemas of its home, or none while it holds nothing.\n */\n private mountedSchemas(state: AgentState): ToolSchemaLike[] {\n const home = this.homeOf(state)\n if (home === undefined) return []\n // A bridge is kept level by the mount, activation and `tools/change`\n // signals; this is the same sync on the read path, so a session's own layer\n // can never lag behind the catalog this probe returns. Unchanged names\n // short-circuit inside, so the cost is one name comparison.\n this.syncBridge(state)\n return this.schemasOf(home, state.agent.id)\n }\n\n /**\n * The visible catalog of one mount home, read through the home's scope key.\n *\n * The single read both callers share: the activation probe asks for the whole\n * catalog, and the on-demand detail route asks it for one definition — reading\n * through the same key is what makes a deferred name answer exactly like an\n * offered one, because the home's catalog carries the whole mounted surface\n * and the deferral decision only lives in the request.\n *\n * @param home - the mount home whose registrations are read.\n * @param agentId - the session the read is attributed to, for the warning.\n * @returns the home's schemas, or none when the read fails.\n */\n private schemasOf(home: MountHome, agentId: string): ToolSchemaLike[] {\n try {\n return this.ctx.tools.schemas(home.key)\n } catch (error) {\n this.ctx.logger.warn(\n `project-mcp: reading the tool catalog of session ${agentId} failed: ${errorText(error)}`,\n )\n return []\n }\n }\n\n /**\n * Every MCP schema the session's own scope chain resolves beyond this\n * plugin's project mounts: the profile plane and any F-19 forwarders. Read\n * through the session's key rather than the home's, so the deferral budget\n * and the discovery tool measure the whole surface the request actually\n * carries. Only `mcp__`-prefixed names enter, and the discovery tool is left\n * out by value — not by prefix — so the activation wiring can offer it on its\n * own. The per-server usage counters stay on the project plane: this probe\n * reads the catalog, never the counters.\n *\n * @param state - the session whose visible surface is probed.\n * @returns the visible MCP schemas, or none when the read fails.\n */\n private visibleSchemas(state: AgentState): ToolSchemaLike[] {\n try {\n return this.ctx.tools.schemas(state.agent).filter(\n (schema) => schema.name.startsWith('mcp__') && schema.name !== SEARCH_TOOL_NAME,\n )\n } catch (error) {\n this.ctx.logger.warn(\n `project-mcp: reading the visible MCP surface of session ${state.agent.id} failed: ${errorText(error)}`,\n )\n return []\n }\n }\n\n /**\n * The MCP tool names this session must never be offered: everything another\n * project mounted in this process publishes. The union is read through each\n * other project's own scope key — not the session's — so a name the host\n * defect leaked into the session's chain is caught here by provenance rather\n * than by prefix. Conservative, so a name the session may legitimately see is\n * never marked foreign: the set subtracts the session's own project's runtime\n * names and every profile-level server name (a profile entry is none of this\n * plugin's business even when another project declares the same name).\n * @param state - the session whose request is being assembled.\n * @returns the foreign tool names, or none when the read fails.\n */\n private foreignNamesOf(state: AgentState): ReadonlySet<string> {\n const own = this.runtimeNamesOf(state)\n const profile = this.profileServerNames()\n const legitimate = new Set<string>([...own, ...profile])\n const foreign = new Set<string>()\n for (const project of this.projects.values()) {\n if (project.projectRoot === state.projectRoot) continue\n let schemas: ToolSchemaLike[]\n try {\n schemas = this.ctx.tools.schemas(project.key)\n } catch (error) {\n this.ctx.logger.warn(\n `project-mcp: reading another project's catalog for session ${state.agent.id} failed: ${errorText(error)}`,\n )\n continue\n }\n for (const schema of schemas) {\n if (!schema.name.startsWith('mcp__')) continue\n if (matchServer(schema.name, legitimate) !== undefined) continue\n foreign.add(schema.name)\n }\n }\n return foreign\n }\n\n /**\n * The live text of the session's guidance section.\n *\n * It reads the mount records and the registry at every assembly, so a rescan\n * that mounted or dropped a server — and a search that activated a tool — are\n * reflected without re-registering the section. Total: any failure returns the\n * empty string, because a section that throws would fail the model request\n * that asked for the assembly.\n */\n private guidanceText(agent: AgentLike, state: AgentState): string {\n try {\n const projectRoot = state.projectRoot\n if (projectRoot === undefined || this.mountsOf(state).size === 0) return ''\n const activationEnabled = this.config.activationEnabled ?? DEFAULT_ACTIVATION_ENABLED\n // With activation on, the presented set is the session's counter baseline\n // plus its activations; with it off, the registry lists every tool.\n const presented = activationEnabled ? presentedNames(this.seedActivation(state)) : undefined\n // Matched by the name each mount registers under, never by its declared\n // one: a shadowed declaration carries a local alias, and a registry lookup\n // by the contested name would drop its tools from the count.\n const mounted = new Set([...this.mountsOf(state).values()].map((mount) => mount.runtimeName))\n const toolsByServer = new Map<string, string[]>()\n const offered: string[] = []\n const deferred: string[] = []\n for (const schema of this.mountedSchemas(state)) {\n const server = matchServer(schema.name, mounted)\n if (server === undefined) continue\n const name = schema.name.slice(`mcp__${server}__`.length)\n const tools = toolsByServer.get(server)\n if (tools === undefined) toolsByServer.set(server, [name])\n else tools.push(name)\n if (presented === undefined || presented.has(schema.name)) offered.push(name)\n else deferred.push(name)\n }\n const servers: GuidanceServer[] = [...this.mountsOf(state).values()].map((mount) => ({\n name: mount.name,\n status: mount.status,\n ...(mount.transport === undefined ? {} : { transport: mount.transport }),\n tools: toolsByServer.get(mount.runtimeName) ?? [],\n }))\n // The seeded baseline's insertion order is the usage rank order\n // (most-called first); keep it and strip the server prefix, so the\n // guidance names the session's hot tools like every other short name.\n const mostUsed: string[] = []\n if (activationEnabled) {\n for (const fullName of this.seedActivation(state).baseline) {\n const server = matchServer(fullName, mounted)\n if (server !== undefined) mostUsed.push(fullName.slice(`mcp__${server}__`.length))\n }\n }\n return buildGuidance({\n project: projectLabel(projectRoot, homedir()),\n servers,\n offered,\n deferred,\n mostUsed,\n activationEnabled,\n })\n } catch (error) {\n this.ctx.logger.warn(\n `project-mcp: building guidance for session ${agent.id} failed: ${errorText(error)}`,\n )\n return ''\n }\n }\n\n /**\n * Record a call against the session's activation state: it refreshes the\n * freshness of a session-activated tool, and it is the evidence a later\n * compaction keeps that activation by. It rides the same `tools/result`\n * subscription the counters use, so no second observer exists.\n * @param agentId - calling agent, when the call was agent-scoped.\n * @param toolName - public registry name of the call.\n */\n noteToolUse(agentId: string | undefined, toolName: string): void {\n if (agentId === undefined) return\n const state = this.states.get(agentId)\n if (state?.activation === undefined) return\n state.activation = noteUse(state.activation, toolName, Date.now())\n }\n\n /** Drop the session-activated tools that outlived `toolIdleMs` without a call. */\n private pruneActivation(state: AgentState): void {\n const current = state.activation\n if (current === undefined) return\n state.activation = pruneIdle(current, Date.now(), this.config.toolIdleMs ?? DEFAULT_TOOL_IDLE_MS)\n // A step record belongs to the activation it was made for, so a name that\n // fell out of the window takes its record with it; one that returns is\n // stamped again with the step it returns on.\n if (state.activation !== current) this.pruneStepRecords(state)\n }\n\n /**\n * Drop the step records whose activation the session no longer holds.\n *\n * Called wherever activations end — the idle sweep and a compaction — so a\n * record never outlives the offer it was made for, and a name the session\n * still offers keeps the step its offer happened on.\n * @param state - the session whose records are reconciled.\n */\n private pruneStepRecords(state: AgentState): void {\n const active = state.activation?.active\n for (const name of [...state.steps.keys()]) {\n if (active === undefined || !active.has(name)) state.steps.delete(name)\n }\n }\n\n private async unmount(home: MountHome, name: string, reason: CodedText): Promise<void> {\n const mount = home.mounts.get(name)\n if (mount === undefined) return\n home.mounts.delete(name)\n this.logUnmount(home, mount, reason)\n await this.disposeFiber(mount)\n }\n\n /**\n * The line that closes a mount's life, the pair of the `mounting` line.\n *\n * The reason is the part a reader cannot infer from the log's order: an edit,\n * an idle release, an operator retry and a session teardown all unmount, and\n * only some of them are followed by a mount of the same server. The run time\n * tells a server that never came up from one that served and was replaced.\n * @param home - the home the instance lived in.\n * @param mount - the instance going away.\n * @param reason - why it is going away: the operator's sentence and its wire\n * code (F-48), nested two-level into the `unmounting` event as `reasonCode`.\n */\n private logUnmount(home: MountHome, mount: MountedInstance, reason: CodedText): void {\n const now = Date.now()\n const ran = formatDuration(now - mount.startedAt)\n // `unmounting` after a failure is the tail of that failure, so the tab keeps\n // it red; every other release is a warning. The instance serves every session\n // of its project, so its release is a project event that names no session.\n this.logLifecycle({\n at: now,\n level: mount.failed ? 'error' : 'warn',\n logLevel: 'info',\n projectRoot: mount.projectRoot,\n server: mount.name,\n message: `unmounting — ${reason.text} (it ran for ${ran})`,\n code: 'unmounting',\n params: { reasonCode: reason.code, ran },\n ...(mount.detail === undefined ? {} : { detail: mount.detail }),\n ...(mount.detailCode === undefined ? {} : { detailCode: mount.detailCode }),\n ...(mount.detailParams === undefined ? {} : { detailParams: mount.detailParams }),\n line: `unmounting ${mount.name} in ${home.projectRoot} — ${reason.text} (it ran for ${ran})`,\n })\n }\n\n /**\n * Bring every foreign holder of one home level with its live tools.\n *\n * The mount and unmount sites call this because they are the moments the\n * project's tool set actually changes: a session's own pass can run before the\n * server it shares has published anything (its own mount is only registered\n * after the hold), and this is what fills its forwarders in behind it. The\n * `tools/change` subscription and the read-path sync cover the same event on\n * a real registry; a third trigger costs nothing, because an unchanged name\n * set short-circuits.\n * @param home - the home whose tools changed.\n */\n private syncBridgesOf(home: MountHome): void {\n for (const state of this.states.values()) {\n if (state.bridge !== undefined && state.project === home) this.syncBridge(state)\n }\n }\n\n private async disposeFiber(mount: MountedInstance): Promise<void> {\n const fiber = mount.fiber\n mount.fiber = undefined\n if (fiber === undefined) return\n const outcome = await this.waitFor(\n `disposal of ${mount.name}`,\n Promise.resolve().then(() => fiber.dispose()),\n )\n if (outcome.kind === 'failed') {\n this.ctx.logger.warn(`project-mcp: disposing ${mount.name} failed: ${errorText(outcome.error)}`)\n }\n }\n\n /**\n * Refresh `active`/`connecting` from the tools actually visible to the agent,\n * and turn a mount that never produced a tool into a detailed `error` row.\n * The watchdog is strictly read-only: it never disposes a slow server, and a\n * mount that connects later returns to `active` on its own.\n */\n private refreshStatuses(agent: AgentLike, state: AgentState): void {\n const timeout = this.config.connectTimeoutMs\n const now = Date.now()\n for (const mount of this.mountsOf(state).values()) {\n // Activation failed outright: the fiber is dead, so there is nothing to\n // poll and nothing to revive without a new mount (`projectMcp.retry()`).\n if (mount.failed) continue\n if (this.hasTools(state, mount.runtimeName)) {\n if (mount.status !== 'active') {\n const elapsed = formatDuration(now - mount.startedAt)\n // Success is an event of its own level: the tab draws it green, not as\n // one more info line, and the line names the session that sees it.\n this.logLifecycle({\n at: now,\n level: 'up',\n logLevel: 'info',\n projectRoot: mount.projectRoot,\n sessionId: agent.id,\n server: mount.name,\n message: `is up — tools visible to session ${agent.id} after ${elapsed}`,\n code: 'mount.up',\n params: { sessionId: agent.id, elapsed },\n line: `${mount.name} is up in ${state.projectRoot ?? 'the project'} — its tools are visible to session ${agent.id} after ${elapsed}`,\n })\n }\n mount.status = 'active'\n mount.detail = undefined\n mount.detailCode = undefined\n mount.detailParams = undefined\n mount.stalled = false\n continue\n }\n const elapsed = now - mount.startedAt\n if (timeout > 0 && elapsed >= timeout) {\n const firstReport = !mount.stalled\n mount.status = 'error'\n mount.stalled = true\n const stall = stallDetail(mount, elapsed)\n mount.detail = stall.text\n mount.detailCode = stall.code\n mount.detailParams = stall.params\n if (firstReport) {\n // Reported once per stall (the watchdog re-reads it every pass), with\n // the three facts the row shows and no retry advice.\n this.logLifecycle({\n at: now,\n level: 'warn',\n logLevel: 'warn',\n projectRoot: mount.projectRoot,\n sessionId: agent.id,\n server: mount.name,\n message: `no tool appeared in ${formatDuration(elapsed)}`,\n code: 'mount.stalled',\n params: { elapsed: formatDuration(elapsed) },\n detail: stall.text,\n detailCode: stall.code,\n ...(stall.params === undefined ? {} : { detailParams: stall.params }),\n line: stall.text,\n })\n }\n continue\n }\n mount.status = 'connecting'\n mount.stalled = false\n mount.detail = undefined\n mount.detailCode = undefined\n mount.detailParams = undefined\n }\n }\n\n /**\n * The session's rows with their live mount state applied.\n *\n * Read-time, not stored: a mount that appears, connects or fails between two\n * passes changes what a panel must show, while the row belongs to the pass\n * that last re-derived it. Decorating here is what lets the status channel\n * report a mount the moment the pass creates it, rather than when that pass\n * finally returns.\n * @param state - the session whose rows to read.\n * @returns one row per declaration, in document order.\n */\n private liveRows(state: AgentState): ServerRow[] {\n const mounts = this.mountsOf(state)\n return state.rows.map((row) => decorate(row, mounts.get(row.name)))\n }\n\n /** Mount failures of this pass, published as first-class snapshot issues. */\n private mountDiagnostics(state: AgentState, projectRoot: string): SnapshotIssue[] {\n const diagnostics: SnapshotIssue[] = []\n for (const mount of this.mountsOf(state).values()) {\n if (mount.status !== 'error' || mount.detail === undefined) continue\n diagnostics.push({\n source: mount.source ?? projectRoot,\n server: mount.name,\n level: 'error',\n message: mount.detail,\n // The detail's wire companions ride along, so the issue translates the\n // same way the event's detail does (F-48).\n ...(mount.detailCode === undefined ? {} : { code: mount.detailCode }),\n ...(mount.detailParams === undefined ? {} : { params: mount.detailParams }),\n })\n }\n return diagnostics\n }\n\n private hasTools(state: AgentState, serverName: string): boolean {\n const prefix = `mcp__${serverName}__`\n return this.mountedSchemas(state).some((schema) => schema.name.startsWith(prefix))\n }\n\n /**\n * Global documents of this deployment, lowest priority first. Read before a\n * project's own documents, so a project declaration always wins.\n */\n private globalFiles(): string[] {\n return globalConfigPaths(this.config.globalFiles)\n }\n\n /**\n * Every document one project is configured to read, in priority order — the\n * order they are read in, which is what the panel's `priority n/total` counts.\n */\n private readFiles(projectRoot: string): ConfiguredFile[] {\n return [\n ...this.globalFiles().map((path): ConfiguredFile => ({ path, scope: 'global' })),\n ...localConfigPaths(projectRoot, this.config.localFiles).map(\n (path): ConfiguredFile => ({ path, scope: 'project' }),\n ),\n ]\n }\n\n private readProject(projectRoot: string): {\n entries: ParsedEntry[]\n issues: ParseIssue[]\n documents: Map<string, DocumentInfo>\n /**\n * Every document that declared each `serverName`, in declaration order —\n * lowest priority first, exactly the order {@link mergeEntries} applies, so\n * the winner of a duplicated name is the last path recorded here.\n */\n sources: Map<string, string[]>\n } {\n const paths = [...this.globalFiles(), ...localConfigPaths(projectRoot, this.config.localFiles)]\n const resolveContext = this.resolveContext(projectRoot)\n const groups: ParsedEntry[][] = []\n const issues: ParseIssue[] = []\n const documents = new Map<string, DocumentInfo>()\n const sources = new Map<string, string[]>()\n for (const path of paths) {\n const document = this.readDocument(path, resolveContext)\n if (document === undefined) continue\n groups.push(document.entries)\n issues.push(...document.issues)\n documents.set(path, this.documentInfo(path, projectRoot, document, resolveContext))\n for (const entry of document.entries) {\n const declared = sources.get(entry.name)\n if (declared === undefined) sources.set(entry.name, [path])\n else if (!declared.includes(path)) declared.push(path)\n }\n }\n const { entries, overridden } = mergeEntries(groups)\n for (const name of new Set(overridden)) {\n issues.push({\n source: projectRoot,\n server: name,\n level: 'warning',\n message: `serverName \"${name}\" was declared in more than one document; the highest-priority definition wins`,\n // The code the client's file grouping compares — never the prose,\n // which the client may have translated.\n code: 'parse.server.multiDocument',\n params: { name },\n })\n }\n return { entries, issues, documents, sources }\n }\n\n /**\n * Everything the editor needs about one declaring document: its revision and\n * write tier, plus the entry body of each server that parsed.\n */\n private documentInfo(\n path: string,\n projectRoot: string,\n document: CachedDocument,\n resolveContext: ResolveContext,\n ): DocumentInfo {\n const entries = new Map<string, EntrySnapshot>()\n const declared = document.raw\n if (declared !== undefined) {\n const byName = new Map<string, unknown>()\n for (const [key, value] of Object.entries(declared)) {\n const name = SERVER_NAME_PATTERN.test(key) ? key : slugifyServerName(key)\n if (name !== '') byName.set(name, value)\n }\n for (const entry of document.entries) {\n if (entry.config === undefined) continue\n const raw = byName.get(entry.name)\n entries.set(entry.name, buildEntrySnapshot(raw, entry.config.transport, credentialKeys(raw, resolveContext)))\n }\n }\n const scope = writeScopeFor(path, projectRoot, {\n projectDocuments: localConfigPaths(projectRoot, this.config.localFiles),\n globalDocuments: this.globalFiles(),\n allowGlobalWrite: this.config.allowGlobalWrite === true,\n })\n return { revision: documentRevision(document.text), entries, ...scope }\n }\n\n private readDocument(path: string, resolveContext: ResolveContext): CachedDocument | undefined {\n let stats\n try {\n stats = statSync(path)\n } catch {\n this.documents.delete(path)\n return undefined\n }\n const cached = this.documents.get(path)\n if (\n cached !== undefined &&\n cached.mtimeMs === stats.mtimeMs &&\n cached.size === stats.size &&\n cached.stamp === (resolveContext.stamp ?? '')\n ) {\n return cached\n }\n let text: string\n try {\n text = readFileSync(path, 'utf8')\n } catch {\n return undefined\n }\n const parsed = parseDocument(text, path, resolveContext)\n let raw: Record<string, unknown> | undefined\n try {\n raw = extractServerMap(JSON.parse(text) as unknown) ?? undefined\n } catch {\n // Invalid JSON: `parseDocument` already reported it per entry.\n raw = undefined\n }\n const document: CachedDocument = {\n mtimeMs: stats.mtimeMs,\n size: stats.size,\n text,\n stamp: resolveContext.stamp ?? '',\n raw,\n entries: parsed.entries,\n issues: parsed.issues,\n }\n this.documents.set(path, document)\n return document\n }\n\n private resolveContext(projectRoot: string): ResolveContext {\n const dotenv = this.readProjectEnv(projectRoot)\n const secrets = this.readSecrets()\n return {\n env: process.env,\n dotenv: dotenv.values,\n inputs: this.config.inputs,\n secrets: secrets.values,\n stamp: `${dotenv.stamp}\\u0001${secrets.stamp}`,\n projectRoot,\n toolCallTimeoutMs: this.config.toolCallTimeoutMs,\n failOnStartupError: this.config.failOnStartupError,\n }\n }\n\n /**\n * The project's own dotenv values, plus the identity of the files they came\n * from. Documents are merged lowest priority first, so `<project>/.dsh/.env`\n * overrides the plain `<project>/.env`; each file is re-read only when its\n * mtime/size changes, and a file that is gone leaves both the map and the\n * stamp (so deleting `.env` un-resolves its references on the next pass).\n */\n private readProjectEnv(projectRoot: string): { values: Record<string, string>; stamp: string } {\n const values: Record<string, string> = {}\n if (this.config.envFiles === false) return { values, stamp: '' }\n const parts: string[] = []\n for (const path of projectEnvPaths(projectRoot)) {\n let stats\n try {\n stats = statSync(path)\n } catch {\n this.envFiles.delete(path)\n continue\n }\n const cached = this.envFiles.get(path)\n const entry =\n cached !== undefined && cached.mtimeMs === stats.mtimeMs && cached.size === stats.size\n ? cached\n : { mtimeMs: stats.mtimeMs, size: stats.size, values: readEnvFile(path) }\n this.envFiles.set(path, entry)\n Object.assign(values, entry.values)\n parts.push(`${path}:${entry.mtimeMs}:${entry.size}`)\n }\n return { values, stamp: parts.join('|') }\n }\n\n /**\n * Credentials, re-read only when the document changes. Every pass of every\n * session resolves `${input:NAME}` references, so an uncached read here cost\n * one synchronous stat plus YAML parse per session per pass. The stamp is the\n * same identity the document cache compares.\n */\n private readSecrets(): { values: Record<string, string>; stamp: string } {\n const path = this.config.credentialsFile\n let stats\n try {\n stats = statSync(path)\n } catch {\n this.secrets = undefined\n return { values: {}, stamp: '' }\n }\n const stamp = `${stats.mtimeMs}:${stats.size}`\n const cached = this.secrets\n if (cached !== undefined && cached.mtimeMs === stats.mtimeMs && cached.size === stats.size) {\n return { values: cached.values, stamp }\n }\n const values = readSecrets(path)\n this.secrets = { mtimeMs: stats.mtimeMs, size: stats.size, values }\n return { values, stamp }\n }\n\n private profileServerNames(): Set<string> {\n const names = new Set<string>()\n let entries: LoaderEntryLike[] = []\n try {\n const loader = (this.ctx as unknown as { get(name: string): unknown }).get('loader') as\n | LoaderLike\n | undefined\n entries = loader?.entries?.() ?? []\n } catch {\n return names\n }\n for (const entry of entries) {\n const options = entry.options ?? {}\n if (options.disabled === true) continue\n if (!MCP_CLIENT_ENTRY_NAMES.has(String(options.name))) continue\n const name = options.config?.serverName\n if (typeof name !== 'string') continue\n if (entry.fiber?.state === FIBER_ACTIVE) names.add(name)\n }\n return names\n }\n\n /**\n * The other loaded plugin that owns the assembled tool list, if the profile\n * has one.\n *\n * Read from the same `loader.entries()` this plugin already consults for the\n * reserved `serverName`s, for the same reason: the profile is where a second\n * owner is mounted, and a running entry is the only kind that shapes a\n * request. An entry named like a known presentation plugin but not active is\n * mounted-and-stopped, which shapes nothing, so it is reported no more than an\n * absent one is.\n *\n * @returns the owner, or `undefined` when this plugin assembles alone.\n */\n private presentationOwner(): PresentationOwner | undefined {\n let entries: LoaderEntryLike[] = []\n try {\n const loader = (this.ctx as unknown as { get(name: string): unknown }).get('loader') as\n | LoaderLike\n | undefined\n entries = loader?.entries?.() ?? []\n } catch {\n return undefined\n }\n for (const entry of entries) {\n const options = entry.options ?? {}\n if (options.disabled === true) continue\n if (!PRESENTATION_OWNER_ENTRY_NAMES.has(String(options.name))) continue\n if (entry.fiber?.state !== FIBER_ACTIVE) continue\n // The module specifier is what the profile wrote down, so it is the most\n // useful label; the entry id disambiguates two mounts of one module and\n // stands in when a hand-written profile names the plugin by path.\n const name =\n typeof options.name === 'string' && options.name !== ''\n ? options.name\n : typeof options.id === 'string'\n ? options.id\n : ''\n return { name, note: PRESENTATION_OWNER_NOTE, noteCode: 'present.ownerNote' }\n }\n return undefined\n }\n\n /**\n * Keep one watcher set per project with live agents. Only the project's own\n * document directories are watched recursively: an unrelated file storm\n * (install caches, build output, git metadata) never reaches this plugin, so\n * it costs no events and no passes. A flat watch on the project root notices\n * a config directory appearing or disappearing, and the rescan timer is the\n * safety net for anything else.\n */\n private syncWatchers(): void {\n const roots = new Set<string>()\n for (const state of this.states.values()) {\n if (state.projectRoot !== undefined) roots.add(state.projectRoot)\n }\n for (const [root, watchers] of [...this.watchers]) {\n if (roots.has(root)) continue\n this.closeWatchers(root, watchers)\n }\n if (!this.config.watch) return\n for (const root of roots) {\n const existing = this.watchers.get(root)\n if (existing !== undefined) {\n const desired = this.watchTargets(root)\n if (sameTargets(this.watchedDirs.get(root) ?? [], desired)) continue\n this.closeWatchers(root, existing)\n }\n const targets = this.watchTargets(root)\n const watchers = this.watchProject(root, targets)\n if (watchers.length === 0) continue\n this.watchers.set(root, watchers)\n this.watchedDirs.set(root, targets)\n this.watchedRoots.add(root)\n }\n }\n\n private closeWatchers(root: string, watchers: FSWatcher[]): void {\n for (const watcher of watchers) watcher.close()\n this.watchers.delete(root)\n this.watchedDirs.delete(root)\n this.watchedRoots.delete(root)\n }\n\n /** Directories (and document files) worth watching for one root. */\n private watchTargets(root: string): WatchTarget[] {\n const targets: WatchTarget[] = []\n for (const directory of configDirectories(root, this.config.localFiles)) {\n if (directory !== root) targets.push({ path: directory, directory: true })\n }\n // A global document is watched as a file: watching its whole home directory\n // would put the watcher on every unrelated write under `$HOME`.\n for (const file of this.globalFiles()) targets.push({ path: file, directory: false })\n return targets\n }\n\n private watchProject(root: string, targets: readonly WatchTarget[]): FSWatcher[] {\n const onChange = (): void => this.schedule('watch')\n const watchers: FSWatcher[] = []\n const add = (path: string, recursive: boolean): void => {\n try {\n const watcher = watch(path, { recursive, persistent: false }, onChange)\n watcher.on('error', () => undefined)\n watchers.push(watcher)\n } catch {\n // The target can disappear between the existence check and the watch.\n }\n }\n // Flat: catches a config directory appearing or disappearing.\n add(root, false)\n for (const target of targets) {\n if (!target.directory) {\n add(target.path, false)\n continue\n }\n if (this.recursiveWatch !== false) {\n try {\n const watcher = watch(target.path, { recursive: true, persistent: false }, onChange)\n watcher.on('error', () => undefined)\n watchers.push(watcher)\n this.recursiveWatch = true\n continue\n } catch (error) {\n this.recursiveWatch = false\n this.ctx.logger.debug?.(\n `project-mcp: recursive watch unavailable for ${target.path} (${errorText(error)}); using flat watches`,\n )\n }\n }\n add(target.path, false)\n }\n return watchers\n }\n}\n\n/**\n * The real `serverName` conflicts of one reconciled pass, in a stable order.\n *\n * Two declarations fight over a name and only one of them mounts, so a panel\n * that shows the surviving row alone would hide the loss:\n *\n * - `profile` — a profile-level `mcp-client` instance already owns the name. The\n * project's entry does not mount under it while the profile's copy is the one\n * shown (the default); it mounts under a name this project chose otherwise —\n * the local alias, or the contested name itself, where it is the nearer\n * declaration and shadows the profile instance's tools in this project's\n * sessions. It is a conflict only where the profile is allowed to win\n * ({@link RuntimeConfig.profileWins}); the row carries `status: 'conflict'`\n * for exactly the names this project does not mount.\n * - `duplicate` — two documents of one project declare the same name and\n * {@link mergeEntries} keeps the highest-priority declaration, so the other\n * one is silently ignored.\n *\n * Only names defined for this project are reported: a source recorded for a name\n * the merge dropped (a document that reappeared between passes) is a document\n * detail, not a conflict this row set can explain.\n *\n * @param entries - merged entries, one per resolved name.\n * @param sources - declaring documents per name, lowest priority first.\n * @param reserved - profile-reserved names that shadow the project's entry.\n * @param aliases - the local name each shadowed declaration would take, when\n * this project has one to give ({@link resolveConflictNames}); a project with\n * none can still answer `native`, which needs no prefix.\n * @param policy - the project's policy: what the user already chose about each\n * contested name.\n * @returns one report per name, sorted by name; empty when nothing conflicts.\n */\nfunction conflictsFor(\n entries: readonly ParsedEntry[],\n sources: ReadonlyMap<string, string[]>,\n reserved: ReadonlySet<string>,\n aliases: ReadonlyMap<string, string>,\n policy: ToolPolicy,\n): ServerConflict[] {\n const conflicts: ServerConflict[] = []\n for (const entry of entries) {\n const name = entry.name\n // The winner is listed first in both kinds: the profile instance that owns\n // the name, or the document the merge kept, which is the last one to\n // declare it.\n const declared = [...(sources.get(name) ?? [])]\n const winner = declared[declared.length - 1] ?? entry.source\n const others = declared.slice(0, -1).reverse()\n if (reserved.has(name)) {\n const alias = aliases.get(name)\n const choice = aliasesOf(policy)[name] ?? 'profile'\n // The choice is published even where this project has no alias to offer:\n // `native` needs no prefix, so an alias-less project still has two answers\n // and a panel that hid the choice would offer it none.\n conflicts.push({\n server: name,\n kind: 'profile',\n sources: [winner, ...others],\n ...(alias === undefined ? {} : { alias }),\n choice,\n // The prose is byte-identical to what the site always emitted; the\n // code and its flat params ride beside it for the client to translate\n // (F-48).\n ...(alias === undefined\n ? { code: 'conflict.profile', params: { name } }\n : { code: 'conflict.profileAlias', params: { name, alias } }),\n message:\n alias === undefined\n ? `\"${name}\" is owned by a profile-level mcp-client instance, so the project entry does not mount under it; remove the profile entry to use the project one everywhere, or let this project's copy take the name in this project's sessions alone.`\n : `\"${name}\" is owned by a profile-level mcp-client instance; this project's copy mounts as \"${alias}\" when chosen beside it, or under the contested name when chosen to shadow it in this project's sessions, and does not mount at all while the profile's copy is the one shown.`,\n })\n continue\n }\n if (others.length === 0) continue\n conflicts.push({\n server: name,\n kind: 'duplicate',\n sources: [winner, ...others],\n code: 'conflict.documents',\n // Numbers stringify at emission: params are flat strings end to end.\n params: { name, count: String(declared.length), winner },\n message: `\"${name}\" is declared in ${declared.length} documents; ${winner} wins and the other declaration is not mounted.`,\n })\n }\n // Code-unit order, the same rule the rest of the plugin sorts tool names by.\n return conflicts.sort((left, right) =>\n left.server < right.server ? -1 : left.server > right.server ? 1 : 0,\n )\n}\n\nfunction baseRow(entry: ParsedEntry, projectRoot: string, document: DocumentInfo | undefined): ServerRow {\n const snapshot = document?.entries.get(entry.name)\n return {\n name: entry.name,\n status: 'error',\n projectRoot,\n source: entry.source,\n ...(entry.config === undefined ? {} : { transport: entry.config.transport }),\n ...(document === undefined\n ? {}\n : {\n ...(snapshot === undefined ? {} : { entry: snapshot }),\n writeScope: document.scope,\n ...(document.reason === undefined ? {} : { writeBlockedReason: document.reason }),\n // The wire companions ride beside the prose: the client translates\n // the code and falls back to the byte-identical reason.\n ...(document.blockedCode === undefined ? {} : { blockedCode: document.blockedCode }),\n ...(document.blockedParams === undefined ? {} : { blockedParams: document.blockedParams }),\n documentRevision: document.revision,\n }),\n }\n}\n\n/** `env`/`headers` keys of one declared entry whose value comes from credentials. */\nfunction credentialKeys(declared: unknown, resolveContext: ResolveContext): CredentialKeys {\n const record = isRecord(declared) ? declared : {}\n return { env: credentialKeySet(record.env, resolveContext), headers: credentialKeySet(record.headers, resolveContext) }\n}\n\nfunction credentialKeySet(section: unknown, resolveContext: ResolveContext): ReadonlySet<string> {\n const keys = new Set<string>()\n if (!isRecord(section)) return keys\n for (const [key, value] of Object.entries(section)) {\n if (typeof value === 'string' && referencesCredentials(value, resolveContext)) keys.add(key)\n }\n return keys\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\n/** Row of a declared server that is not mounted, with the reason in `detail`. */\nfunction idleRow(row: ServerRow, reason: CodedText): ServerRow {\n // Strip a previous detail's companions too, or a recycled error row would\n // keep a stale code under the new prose.\n const { detail: _stale, detailCode: _staleCode, detailParams: _staleParams, ...rest } = row\n return {\n ...rest,\n status: 'idle',\n detail: reason.text,\n detailCode: reason.code,\n ...(reason.params === undefined ? {} : { detailParams: reason.params }),\n }\n}\n\nfunction formatSeconds(ms: number): string {\n return `${(ms / 1000).toFixed(1)}s`\n}\n\n/**\n * Duration as an operator reads it: milliseconds under a second, seconds under\n * a minute, then minutes and seconds. A watchdog that fires at 40 ms must not\n * print `0.0s`, and a mount that has been waiting for four and a half minutes\n * should not print `266.7s`.\n */\nfunction formatDuration(ms: number): string {\n if (ms < 1000) return `${Math.round(ms)}ms`\n if (ms < 60_000) return `${(ms / 1000).toFixed(1)}s`\n const minutes = Math.floor(ms / 60_000)\n const seconds = Math.round((ms - minutes * 60_000) / 1000)\n return seconds === 60 ? `${minutes + 1}m` : `${minutes}m ${seconds}s`\n}\n\n/** Unref'd timer, so a bounded wait never keeps a process alive on its own. */\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => {\n const timer = setTimeout(resolve, ms)\n timer.unref?.()\n })\n}\n\n/**\n * Endpoint label for an error message. Arguments and query strings are the two\n * places a declared entry can carry a secret (`--api-key=…`, `?token=…`), so\n * neither ever reaches a row, a log line or the snapshot.\n */\nfunction describeEndpoint(config: NonNullable<ParsedEntry['config']>): string {\n if (config.transport === 'streamable-http') return `streamable-http ${visibleUrl(config.url)}`\n return `stdio ${config.command}`\n}\n\n/**\n * Detail of a mount whose activation failed, including the underlying error and\n * the exact declaration to look at.\n *\n * Multi-line on purpose: the row's detail is the only place an operator sees\n * why a server is not there, and a run-on sentence that starts with the error\n * and ends with the file path reads as prose instead of the three facts it is.\n */\nfunction failureDetail(mount: MountedInstance, error: unknown): CodedText {\n const params = {\n name: mount.name,\n error: errorText(error),\n endpoint: mount.endpoint,\n // The `{source}` fallback stays English under zh/ru: params are flat strings,\n // so a translatable fragment would need the wire extension Ruling 4 names.\n // Accepted partial — F-48 ledger Ruling 5 (same class as parse.ref.failedInKey).\n source: mount.source ?? 'the project document',\n }\n return {\n code: 'mount.failedDetail',\n text: [\n `${params.name}: mount failed — ${params.error}`,\n `endpoint: ${params.endpoint}`,\n `declared in: ${params.source}`,\n ].join('\\n'),\n params,\n }\n}\n\n/**\n * Detail of a mount that has produced no tool inside `connectTimeoutMs`. The\n * server is left running: a slow start (an `npx` cold fetch, a container pull)\n * is not an error, only a condition the operator needs to see.\n *\n * Facts only — the name and the wait, the endpoint, the declaring document. The\n * row already carries the status, the transport chip and a `Retry` button, and\n * a stdio server's own reason is on its stderr, in the DSH log; anything more\n * here is text an operator has to read past to find the three lines that matter.\n */\nfunction stallDetail(mount: MountedInstance, elapsedMs: number): CodedText {\n const params = {\n name: mount.name,\n elapsed: formatDuration(elapsedMs),\n endpoint: mount.endpoint,\n // See failureDetail: the `{source}` fallback is an accepted English fragment\n // under zh/ru (F-48 ledger Ruling 5).\n source: mount.source ?? 'the project document',\n }\n return {\n code: 'mount.stalledDetail',\n text: [\n `${params.name}: no tool appeared in ${params.elapsed}`,\n `endpoint: ${params.endpoint}`,\n `declared in: ${params.source}`,\n ].join('\\n'),\n params,\n }\n}\n\n/** Row + live mount state; the mount is authoritative for `status` and `detail`. */\nfunction decorate(row: ServerRow, mount: MountedInstance | undefined): ServerRow {\n if (mount === undefined) return row\n // Drop any detail a previous pass wrote, so a mount that recovered stops\n // reporting a stale stall — companions included, or a recycled row would\n // keep a code under prose it does not belong to.\n const { detail: _stale, detailCode: _staleCode, detailParams: _staleParams, ...rest } = row\n return {\n ...rest,\n status: mount.status,\n ...(mount.detail === undefined ? {} : { detail: mount.detail }),\n ...(mount.detailCode === undefined ? {} : { detailCode: mount.detailCode }),\n ...(mount.detailParams === undefined ? {} : { detailParams: mount.detailParams }),\n ...(mount.transport === undefined ? {} : { transport: mount.transport }),\n }\n}\n\n/**\n * Which of two rows describing the same server a project-level merge keeps. The\n * most actionable state wins, so a session that mounted the server — or failed\n * to — is never hidden behind a session that has not started a turn yet.\n */\nconst STATUS_PRIORITY: Record<ServerStatus, number> = {\n error: 5,\n active: 4,\n connecting: 3,\n conflict: 2,\n idle: 1,\n disabled: 0,\n}\n\n/**\n * Merge one session's rows into a project's merged list. The first session to\n * declare a server fixes its position (document order); the status with the\n * highest {@link STATUS_PRIORITY} seen so far supplies the row itself.\n */\nfunction mergeRows(target: ServerRow[], rows: readonly ServerRow[]): void {\n for (const row of rows) {\n const index = target.findIndex((existing) => existing.name === row.name)\n if (index === -1) {\n target.push(row)\n continue\n }\n const current = target[index]\n if (current !== undefined && STATUS_PRIORITY[row.status] > STATUS_PRIORITY[current.status]) {\n target[index] = row\n }\n }\n}\n\n/**\n * Identity of one reconciliation input set: the declarations, the profile\n * reservations, and the published state of the project's shared mounts. Equal\n * digests mean this session has nothing to reconcile.\n *\n * The shared mounts belong in it because a project's servers are one instance\n * for all of its sessions: another session's pass can mount, settle, stall or\n * drop one of them without touching any document, and this session's rows are a\n * rendering of exactly that instance.\n * @param entries - parsed declarations of the session's project.\n * @param reserved - `serverName`s a profile-level instance already owns.\n * @param mounts - the session's current shared mounts, live.\n * @param chosen - shadowed names this pass mounts, and under which name: a local\n * alias, or `undefined` for the contested name itself.\n * @returns a stable identity string.\n */\nfunction digestOf(\n entries: ParsedEntry[],\n reserved: ReadonlySet<string>,\n mounts: ReadonlyMap<string, MountedInstance>,\n chosen: ReadonlyMap<string, string | undefined>,\n): string {\n const parts = entries.map(\n (entry) =>\n `${entry.name}\\u0000${entry.enabled ? '1' : '0'}\\u0000${entry.error ?? ''}\\u0000${\n entry.config === undefined ? '' : fingerprint(entry.config)\n }`,\n )\n parts.push(`reserved:${[...reserved].sort().join(',')}`)\n // The local names this pass chose. They belong in the identity because a\n // choice the user just made moves a declaration between \"conflict report\" and\n // \"mount\", with no document and no mount touched yet — without them, the pass\n // that follows the click would find its inputs unchanged and do nothing.\n for (const [name, mountedAs] of [...chosen].sort(([left], [right]) => (left < right ? -1 : 1))) {\n // `native` is its own part rather than a `local` with an empty name: a choice\n // that mounts under the declared name has to move this identity exactly as a\n // choice that mounts under a local one does, or the pass after the click finds\n // its inputs unchanged and mounts nothing.\n parts.push(mountedAs === undefined ? `native:${name}` : `local:${name}\\u0000${mountedAs}`)\n }\n for (const [name, mount] of mounts) {\n parts.push(\n `mount:${name}\\u0000${mount.status}\\u0000${mount.detail ?? ''}\\u0000${mount.stalled ? '1' : '0'}\\u0000${mount.runtimeName}`,\n )\n }\n return parts.join('\\u0001')\n}\n\nfunction fingerprint(config: unknown): string {\n return JSON.stringify(config)\n}\n\n/**\n * The name one declaration registers under this pass: its local alias, or the\n * name it declared.\n *\n * @param entry - parsed declaration.\n * @param alias - local name the pass chose, when it chose one.\n * @returns the `serverName` to hand `@deepseek-ai/dsh-mcp-client`.\n */\nfunction runtimeNameOf(entry: ParsedEntry, alias: string | undefined): string {\n return alias ?? entry.name\n}\n\n/**\n * One declaration's config as it is mounted: the same body, under the name this\n * registration actually takes.\n *\n * A fresh object on purpose — the parsed entry is shared with every other\n * session and with the editor, and rewriting its `serverName` in place would\n * make the alias look like the declared name everywhere else.\n *\n * @param config - the parsed mcp-client config.\n * @param runtimeName - the `serverName` to reserve.\n * @returns the config to mount.\n */\nfunction runtimeConfigOf(\n config: NonNullable<ParsedEntry['config']>,\n runtimeName: string,\n): NonNullable<ParsedEntry['config']> {\n if (config.serverName === runtimeName) return config\n return { ...config, serverName: runtimeName }\n}\n\n/**\n * The one line a shadowed declaration carries.\n *\n * Two readings, and the row has to say which one it is: the profile's copy is the\n * one shown and this project's entry is a conflict, or the entry has a local name\n * to be mounted under and the choice is the question. A mounted row carries no\n * detail at all ({@link decorate}), so a chosen answer is explained by the\n * conflict report, which a mounted name still publishes.\n *\n * @param name - the contested `serverName`.\n * @param alias - the local name this project could give it, when it has one.\n * @returns the row's detail line, with its wire code and params (F-48).\n */\nfunction conflictDetail(name: string, alias: string | undefined): CodedText {\n const base = `serverName \"${name}\" is already provided by a profile-level mcp-client instance`\n return alias === undefined\n ? {\n text: `${base} — remove that entry from the profile to use the project one everywhere, or choose this project's copy to let it take the name in this project's sessions`,\n code: 'conflict.profileDetail',\n params: { name },\n }\n : {\n text: `${base} — choose this project's copy to mount it as \"${alias}\", or under the contested name to shadow the profile instance here`,\n code: 'conflict.profileAliasDetail',\n params: { name, alias },\n }\n}\n\nasync function activation(fiber: MountFiber): Promise<void> {\n if (typeof fiber.await === 'function') {\n await fiber.await()\n return\n }\n await Promise.resolve(fiber as unknown)\n}\n\nfunction errorText(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\n/**\n * The fields one tool definition accepts, read from its top-level\n * `parameters.properties` in schema order.\n *\n * A declared object or array is drawn as its own `type` and never expanded:\n * the record answers \"what does this tool take\", and a nested graph is what the\n * model-facing schema already carries. A property published without a `type` —\n * the JSON Schema case of `oneOf` or `$ref` — reads as `any`, the same word the\n * row vocabulary uses for \"the schema names none\". A property's `default` is\n * deliberately not part of the record: it is the host's own default for a call,\n * never a value the tool publishes.\n *\n * @param parameters - the definition's JSON Schema object arguments.\n * @returns one field per declared property; empty when the schema declares none.\n */\nfunction toolFieldsOf(parameters: Record<string, unknown>): ToolField[] {\n const properties = parameters.properties\n if (!isRecord(properties)) return []\n const required = new Set(stringArray(parameters.required))\n return Object.entries(properties).map(([name, declared]) => {\n const field = isRecord(declared) ? declared : {}\n const type = field.type\n const description = field.description\n return {\n name,\n type: typeof type === 'string' && type !== '' ? type : 'any',\n required: required.has(name),\n ...(typeof description === 'string' && description !== '' ? { description } : {}),\n }\n })\n}\n\n/** The strings of one array value; empty for anything that is not one. */\nfunction stringArray(value: unknown): string[] {\n return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : []\n}\n\n/**\n * One path the watcher stack covers and what kind it is.\n *\n * The kind comes from the config, not from the name: a document is watched as a\n * file — watching its whole directory would put the watcher on unrelated writes\n * — while a directory that holds a project document is watched (recursively when\n * the platform allows) so a document appearing there is seen.\n */\ninterface WatchTarget {\n /** Absolute path. */\n readonly path: string\n /** `true` for a directory, `false` for a document file. */\n readonly directory: boolean\n}\n\n/** Same targets, in the same order — what decides a watcher rebuild. */\nfunction sameTargets(left: readonly WatchTarget[], right: readonly WatchTarget[]): boolean {\n return (\n left.length === right.length &&\n left.every((value, index) => value.path === right[index]?.path && value.directory === right[index]?.directory)\n )\n}\n","/**\n * Contract shared by the host half and the browser half of the panel.\n *\n * Import-free on purpose: the client bundle must not pull host code in, and the\n * right sidebar exists only in the browser half, so the two halves meet at these\n * routes over HTTP.\n *\n * @module dsh-project-mcp/shared\n */\n\nimport type { ConflictChoice, EntrySnapshot, ToolMode } from './types.ts'\n\n/** Route prefix the host serves and the sidebar panel fetches. */\nexport const ROUTE_PREFIX = '/project-mcp'\n\n/** Sidebar tab id; also the `SidebarTab.type` the panel opens as. */\nexport const TAB_ID = 'dsh-project-mcp:servers'\n\n/** Plugin name, shared by both halves. */\nexport const PACKAGE_NAME = 'dsh-project-mcp'\n\n/** Actions the host serves under {@link ROUTE_PREFIX}, and the panel fetches. */\nexport const ROUTE_ACTIONS = {\n /** `GET`: the current snapshot. */\n snapshot: 'snapshot',\n /** `POST`: ask for a rescan; answers as soon as the request is accepted. */\n sync: 'sync',\n /** `POST`: drop this project's failed mounts and re-mount them; answers once they are dropped. */\n retry: 'retry',\n /** `GET`: the status channel — one pushed frame per change, held open. */\n events: 'events',\n /** `GET`: one page of a project's log ring, oldest first, for \"show older\". */\n logs: 'logs',\n /**\n * `GET`: one tool's detail — its description, its accepted fields, its\n * measured size and the reason it is not offered — read once per opened row\n * so that neither the snapshot nor a change frame carries it.\n */\n tool: 'tool',\n /** `POST`: release this session's mounts. */\n release: 'release',\n /** `POST`: write one edited entry back to its declaring document. */\n save: 'save',\n /** `POST`: pin or unpin one tool of one project. */\n pin: 'pin',\n /** `POST`: set one project's tool mode. */\n policy: 'policy',\n /** `POST`: choose which declaration of a contested `serverName` shows. */\n conflict: 'conflict',\n} as const\n\n/**\n * One operator request: the body of `POST sync` and `POST retry`.\n *\n * `projectRoot` scopes the action, so a surface that shows one project never\n * starts or restarts a server for another. `full` is the answer shape: a\n * single-project surface leaves it out and gets that project's slice back, while\n * a surface that lists every project — the settings page — asks for the whole\n * snapshot, since narrowing would empty the list it renders.\n */\nexport interface OperatorRequest {\n /** Project the action applies to; omitted covers every project. */\n readonly projectRoot?: string\n /** Answer with the whole snapshot rather than `projectRoot`'s slice. */\n readonly full?: boolean\n}\n\n/** Pin or unpin one tool of one project. */\nexport interface PinRequest {\n /** Project root the tool belongs to. */\n readonly projectRoot: string\n /** Public registry name, eg `mcp__tglider__workspace`. */\n readonly tool: string\n /** `true` pins it, `false` unpins it. */\n readonly pinned: boolean\n}\n\n/** Set one project's tool mode. Pins travel in their own request. */\nexport interface PolicyRequest {\n /** Project root the mode applies to. */\n readonly projectRoot: string\n /** The mode to store. */\n readonly mode: ToolMode\n}\n\n/**\n * Choose which declaration of one contested `serverName` a project shows.\n *\n * The name stays the profile's either way; the answer decides whether the\n * project's own entry mounts beside it under a local namespace. The name is\n * carried as declared — the sanitized `mcpServers` key — because that is what\n * the conflict report names, and the local name is the plugin's to compute.\n */\nexport interface ConflictRequest {\n /** Project root the name belongs to. */\n readonly projectRoot: string\n /** Contested `serverName`, as the project declared it. */\n readonly server: string\n /** The declaration to show. */\n readonly choice: ConflictChoice\n}\n\n/**\n * One entry a save writes.\n *\n * The panel submits the {@link EntrySnapshot} it was given, with the fields the\n * user changed. A masked `env`/`headers` key submitted without a `value` keeps\n * whatever the document declares for it; a key the submission omits is removed.\n */\nexport interface SaveRequest {\n /** Project root the edited row belongs to. */\n readonly projectRoot: string\n /** `serverName` being edited. */\n readonly server: string\n /** Absolute path of the document the entry came from. */\n readonly document: string\n /** `documentRevision` the edit was built from; a mismatch refuses the write. */\n readonly revision: string\n /** `true` acknowledges a write to the global tier; required only there. */\n readonly consent?: boolean\n /** The entry body to write. */\n readonly entry: EntrySnapshot\n}\n\n/** Error codes a save answers with, each with its own sentence in the panel. */\nexport type SaveErrorCode =\n /** The entry is not one this plugin would mount; nothing was written. */\n | 'invalid'\n /** The document may not be written: profile, `<DSH_HOME>`, or no consent. */\n | 'blocked'\n /** The document changed since the snapshot was taken; nothing was written. */\n | 'conflict'\n /** The document or the server is no longer there. */\n | 'not-found'\n /** The write itself failed; the document is left as it was. */\n | 'failed'","/**\n * Host HTTP surface for the sidebar panel.\n *\n * The browser half of a DSH composition is a different process from this one, so\n * the panel cannot call the `projectMcp` service in process: it fetches these\n * routes, which is how every browser-facing service in DSH reaches its host.\n * Every response is `{ ok: true, value }` or `{ ok: false, error }`.\n *\n * @module dsh-project-mcp/ui\n */\n\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport type { ProjectMcpService } from './index.ts'\nimport { page } from './logs.ts'\nimport { isConflictChoice, isToolMode } from './policy.ts'\nimport type { PolicyOutcome } from './runtime.ts'\nimport type {\n ConflictRequest,\n OperatorRequest,\n PinRequest,\n PolicyRequest,\n SaveErrorCode,\n SaveRequest,\n} from './shared.ts'\nimport { ROUTE_PREFIX } from './shared.ts'\nimport type { EntrySnapshot, McpSnapshot, SnapshotChange } from './types.ts'\n\n/** The subset of the DSH web server this plugin registers on. */\nexport interface WebServerLike {\n /** Register one route and return its disposer, in whatever shape the server uses. */\n register(route: { kind: 'prefix'; path: string; handler: RouteHandler }): unknown\n}\n\n/** Node HTTP handler signature the web server expects. */\nexport type RouteHandler = (req: IncomingMessage, res: ServerResponse) => Promise<void>\n\n/** Largest request body accepted for a session id. */\nconst MAX_BODY_BYTES = 4_096\n\n/** Largest request body accepted for a save: one entry body plus its extras. */\nconst MAX_SAVE_BYTES = 64 * 1024\n\n/**\n * How often a quiet stream is poked.\n *\n * The channel can be silent for minutes — nothing happens in a project, so\n * nothing is announced — and an idle connection is what proxies and browsers\n * reap. A comment frame is not an event: the panel does not see it, the socket\n * stays warm. `unref`'d, so a headless host is never kept alive for it.\n */\nconst HEARTBEAT_MS = 15_000\n\n/**\n * The status channel: one open `GET events` response per panel, and a frame\n * whenever the picture changes.\n *\n * Server-Sent Events rather than polling: DSH's own web server hands a route the\n * raw response (\"owns the full response lifecycle, may hold the response open,\n * e.g. SSE\") and exempts `text/event-stream` from its gzip filter, and the\n * browser's `EventSource` reconnects on its own. The subscription is only held\n * while somebody is listening, and the heartbeat only runs with a stream open.\n */\nexport interface EventStream {\n /** Serve one `GET events`: the response stays open until the client leaves. */\n serve(req: IncomingMessage, res: ServerResponse): void\n /** Close every open stream and stop listening; the route's disposer calls it. */\n dispose(): void\n}\n\n/**\n * Build the status channel of one route registration.\n * @param service - the runtime's published service.\n * @returns the channel's `serve`/`dispose` pair.\n */\nexport function createEventStream(service: ProjectMcpService): EventStream {\n const streams = new Set<ServerResponse>()\n let heartbeat: ReturnType<typeof setInterval> | undefined\n let unsubscribe: (() => void) | undefined\n let latest: SnapshotChange | undefined\n\n /**\n * Write one frame, dropping a stream that has already gone: a dead socket\n * raises on `write`, and an exception here would reach the pass that\n * announced the change rather than the panel it was meant for.\n */\n const write = (res: ServerResponse, frame: string): void => {\n try {\n res.write(frame)\n } catch {\n streams.delete(res)\n }\n }\n\n const frame = (event: 'hello' | 'change', change: SnapshotChange): string =>\n `event: ${event}\\ndata: ${JSON.stringify(change)}\\n\\n`\n\n const stop = (): void => {\n if (heartbeat !== undefined) clearInterval(heartbeat)\n heartbeat = undefined\n unsubscribe?.()\n unsubscribe = undefined\n }\n\n /**\n * Start listening, if this is the first stream. The subscription answers with\n * the picture as it is now, which is also what a stream opened later replays:\n * every frame carries the whole snapshot, so the newest one is always current.\n */\n const start = (): void => {\n if (unsubscribe !== undefined) return\n unsubscribe = service.subscribe((change) => {\n latest = change\n for (const stream of [...streams]) write(stream, frame('change', change))\n })\n heartbeat = setInterval(() => {\n for (const stream of [...streams]) write(stream, ': ping\\n\\n')\n }, HEARTBEAT_MS)\n heartbeat.unref?.()\n }\n\n return {\n serve(req, res): void {\n res.writeHead(200, {\n 'content-type': 'text/event-stream; charset=utf-8',\n 'cache-control': 'no-cache, no-transform',\n connection: 'keep-alive',\n })\n // A comment first — DSH's own HMR stream does the same — so the browser\n // sees a live channel before anything happens, plus how fast to come back.\n res.write(': connected\\nretry: 2000\\n\\n')\n // Subscribe before joining the fan-out: the subscription answers with the\n // picture as it is, which is this stream's `hello` — a `change` frame for a\n // change that predates the panel would say the same thing twice.\n start()\n streams.add(res)\n if (latest !== undefined) write(res, frame('hello', latest))\n const leave = (): void => {\n streams.delete(res)\n if (streams.size === 0) stop()\n }\n req.on('close', leave)\n res.on('error', leave)\n },\n dispose(): void {\n stop()\n for (const stream of [...streams]) {\n streams.delete(stream)\n try {\n stream.end()\n } catch {\n // The socket is already gone; nothing to end.\n }\n }\n },\n }\n}\n\n/**\n * HTTP status each coded refusal answers with. The policy routes reuse the same\n * vocabulary as a save: `invalid`/`not-found` are the panel's 400s, `failed` a\n * 500.\n */\nconst SAVE_STATUS: Record<SaveErrorCode, number> = {\n invalid: 400,\n blocked: 400,\n 'not-found': 400,\n conflict: 409,\n failed: 500,\n}\n\n/**\n * HTTP status a `GET tool` refusal answers with: the same vocabulary, one\n * different reading.\n *\n * A save or a policy change names something the panel is looking at *and\n * edits*, so a name this host does not know is a malformed request there —\n * `400`. A tool read is a *fetch* of a row the panel already drew, so an\n * unknown project, session or name means the picture moved under it, which is\n * exactly what `404` says: `GET logs` answers the same question the same way.\n */\nconst TOOL_STATUS: Record<SaveErrorCode, number> = {\n ...SAVE_STATUS,\n 'not-found': 404,\n}\n\n/**\n * Read one numeric query parameter.\n *\n * The panel decides the window, so the host refuses rather than guesses: a\n * parameter the URL does not carry is absent, and one it carries as anything but\n * a finite number — `abc`, an empty value — is `'invalid'`, which the route\n * answers with `bad-request`.\n * @param raw - the raw value, `null` when the query string omits it.\n * @returns the number, `undefined` when absent, `'invalid'` when unusable.\n */\nfunction numberParam(raw: string | null): number | undefined | 'invalid' {\n if (raw === null) return undefined\n const value = Number(raw)\n return raw.trim() === '' || !Number.isFinite(value) ? 'invalid' : value\n}\n\n/**\n * Build the route handler for {@link ROUTE_PREFIX}.\n *\n * Both operator actions — `Sync` and `Retry` — answer as soon as they are\n * accepted, never once the servers they touch have settled: the pass they queue\n * runs in the background, and the panel reads the outcome from the status\n * channel. A response held open for a mount that is still connecting is exactly\n * the hang this route no longer produces.\n *\n * @param service - the runtime's published service.\n * @param events - the status channel to serve; built from the service when omitted.\n * @returns a handler for `GET snapshot|events|logs`, `POST sync|retry|release|save`.\n */\nexport function createRouteHandler(\n service: ProjectMcpService,\n events: EventStream = createEventStream(service),\n): RouteHandler {\n const send = (res: ServerResponse, status: number, body: unknown): void => {\n res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' })\n res.end(JSON.stringify(body))\n }\n const reply = async (\n res: ServerResponse,\n action: () => Promise<void>,\n request: OperatorRequest = {},\n ): Promise<void> => {\n try {\n await action()\n send(res, 200, { ok: true, value: operatorAnswer(service, request) })\n } catch (error) {\n send(res, 500, {\n ok: false,\n error: { code: 'failed', message: error instanceof Error ? error.message : String(error) },\n })\n }\n }\n\n /**\n * Answer a pin or mode change with the same envelope a save uses: the fresh\n * snapshot, or the refusal code's status. The service method is synchronous —\n * the policy is not part of any document, so no rescan follows — but a store\n * that still fails answers `500` rather than breaking the route.\n */\n const replyPolicy = (res: ServerResponse, change: () => PolicyOutcome): void => {\n try {\n const outcome = change()\n if (outcome.ok) {\n send(res, 200, { ok: true, value: outcome.snapshot })\n return\n }\n send(res, SAVE_STATUS[outcome.code], {\n ok: false,\n error: {\n code: outcome.code,\n message: outcome.message,\n // The F-48 companions ride the envelope only when the outcome has\n // them: an uncoded refusal's body is byte-identical to before.\n ...(outcome.messageCode === undefined\n ? {}\n : { messageCode: outcome.messageCode, messageParams: outcome.messageParams }),\n },\n })\n } catch (error) {\n send(res, 500, {\n ok: false,\n error: { code: 'failed', message: error instanceof Error ? error.message : String(error) },\n })\n }\n }\n return async (req, res) => {\n const url = new URL(req.url ?? '/', 'http://localhost')\n const action = url.pathname.slice(ROUTE_PREFIX.length).replace(/^\\/+|\\/+$/g, '')\n const method = req.method ?? 'GET'\n if (method === 'GET' && action === 'snapshot') {\n send(res, 200, { ok: true, value: service.snapshot() })\n return\n }\n if (method === 'POST' && action === 'sync') {\n const request = operatorRequestOf(await readJson(req))\n // The pass is background work from here on, so the answer is the picture\n // as it is now — the status channel carries the rest.\n service.syncSoon(request.projectRoot)\n send(res, 200, { ok: true, value: operatorAnswer(service, request) })\n return\n }\n if (method === 'GET' && action === 'events') {\n events.serve(req, res)\n return\n }\n // The tab is drawn from the snapshot, which carries the newest page of the\n // ring; this route is \"show older\". It reads the ring directly — the buffer\n // has one owner (`src/logs.ts`) and no runtime state to ask for — and it\n // answers even when the named project is unknown to the runtime: the ring\n // is keyed by the root, and an empty page is an answer, not a refusal.\n if (method === 'GET' && action === 'logs') {\n const projectRoot = url.searchParams.get('projectRoot')\n const before = numberParam(url.searchParams.get('before'))\n const limit = numberParam(url.searchParams.get('limit'))\n if (projectRoot === null || projectRoot === '' || before === 'invalid' || limit === 'invalid') {\n send(res, 400, {\n ok: false,\n error: {\n code: 'bad-request',\n message: 'GET logs needs a projectRoot, and before/limit as finite numbers',\n },\n })\n return\n }\n send(res, 200, {\n ok: true,\n value: page({\n projectRoot,\n ...(before === undefined ? {} : { before }),\n ...(limit === undefined ? {} : { limit }),\n }),\n })\n return\n }\n // One tool's detail, for a row the panel opened. On demand rather than in\n // the snapshot — descriptions and schemas are the expensive part, and every\n // change frame and poll carries the whole snapshot — so nothing grows on the\n // wire and the answer is fetched once per opened row. The same precedent as\n // `logs`: the route checks that it was given three names at all and refuses\n // a request missing one, while \"this host does not know that project,\n // session or tool\" is the service's `404` rather than the route's `400`.\n if (method === 'GET' && action === 'tool') {\n const projectRoot = url.searchParams.get('projectRoot')\n const sessionId = url.searchParams.get('sessionId')\n const name = url.searchParams.get('name')\n if (projectRoot === null || projectRoot === '') {\n send(res, 400, {\n ok: false,\n error: { code: 'bad-request', message: 'GET tool needs a projectRoot' },\n })\n return\n }\n if (sessionId === null || sessionId === '') {\n send(res, 400, {\n ok: false,\n error: { code: 'bad-request', message: 'GET tool needs a sessionId' },\n })\n return\n }\n if (name === null || name === '') {\n send(res, 400, {\n ok: false,\n error: { code: 'bad-request', message: 'GET tool needs a name' },\n })\n return\n }\n const outcome = service.toolFacts(projectRoot, sessionId, name)\n if (!outcome.ok) {\n send(res, TOOL_STATUS[outcome.code], {\n ok: false,\n error: { code: outcome.code, message: outcome.message },\n })\n return\n }\n send(res, 200, { ok: true, value: outcome.value })\n return\n }\n if (method === 'POST' && action === 'retry') {\n const request = operatorRequestOf(await readJson(req))\n await reply(res, () => service.retry(request.projectRoot), request)\n return\n }\n if (method === 'POST' && action === 'release') {\n const body = await readJson(req)\n const sessionId = typeof body.sessionId === 'string' ? body.sessionId : undefined\n await reply(res, () => service.release(sessionId))\n return\n }\n if (method === 'POST' && action === 'save') {\n const request = saveRequestOf(await readJson(req, MAX_SAVE_BYTES))\n if (request === undefined) {\n send(res, 400, {\n ok: false,\n error: { code: 'invalid', message: 'the save body is not a well-formed entry request' },\n })\n return\n }\n try {\n const outcome = await service.save(request)\n if (outcome.ok) {\n send(res, 200, { ok: true, value: outcome.snapshot })\n return\n }\n send(res, SAVE_STATUS[outcome.code], {\n ok: false,\n error: {\n code: outcome.code,\n message: outcome.message,\n // The F-48 companions ride the envelope only when the outcome has\n // them: an uncoded refusal's body is byte-identical to before.\n ...(outcome.messageCode === undefined\n ? {}\n : { messageCode: outcome.messageCode, messageParams: outcome.messageParams }),\n },\n })\n } catch (error) {\n send(res, 500, {\n ok: false,\n error: { code: 'failed', message: error instanceof Error ? error.message : String(error) },\n })\n }\n return\n }\n // A pin and a mode are durable plugin state, not document edits: neither\n // route rescans, and both answer with the snapshot rebuilt on the spot.\n if (method === 'POST' && action === 'pin') {\n const request = pinRequestOf(await readJson(req))\n if (request === undefined) {\n send(res, 400, {\n ok: false,\n error: { code: 'invalid', message: 'the pin body is not a well-formed pin request' },\n })\n return\n }\n replyPolicy(res, () => service.setPin(request))\n return\n }\n if (method === 'POST' && action === 'policy') {\n const request = policyRequestOf(await readJson(req))\n if (request === undefined) {\n send(res, 400, {\n ok: false,\n error: { code: 'invalid', message: 'the policy body is not a well-formed mode request' },\n })\n return\n }\n replyPolicy(res, () => service.setPolicy(request))\n return\n }\n if (method === 'POST' && action === 'conflict') {\n const request = conflictRequestOf(await readJson(req))\n if (request === undefined) {\n send(res, 400, {\n ok: false,\n error: {\n code: 'invalid',\n message: 'the conflict body is not a well-formed conflict request',\n },\n })\n return\n }\n replyPolicy(res, () => service.setConflictChoice(request))\n return\n }\n send(res, 404, {\n ok: false,\n error: { code: 'not-found', message: `unknown route ${method} ${url.pathname}` },\n })\n }\n}\n\n/**\n * The operator request a `sync` or `retry` body carries. A body that is not an\n * operator request at all — a surface that predates the field, a `{}`, a\n * malformed value — reads as the global call it used to be.\n * @param body - the parsed request body.\n * @returns the project the action applies to, and the answer shape asked for.\n */\nexport function operatorRequestOf(body: Record<string, unknown>): OperatorRequest {\n const projectRoot = body.projectRoot\n return {\n ...(typeof projectRoot === 'string' && projectRoot !== '' ? { projectRoot } : {}),\n ...(body.full === true ? { full: true } : {}),\n }\n}\n\n/**\n * The snapshot an operator route answers with.\n *\n * A single-project surface (the sidebar tab, a row's own `Retry`) gets that\n * project's slice: it shows one project, and answering with every project made a click in one of them look like it had touched all of them. A\n * surface that lists every project asks for `full`, because a narrowed answer\n * would empty the list it renders.\n * @param service - the runtime's published service.\n * @param request - the operator request the caller sent.\n * @returns the snapshot, narrowed when the caller asked for one project.\n */\nexport function operatorAnswer(service: ProjectMcpService, request: OperatorRequest): McpSnapshot {\n const snapshot = service.snapshot()\n if (request.full === true || request.projectRoot === undefined) return snapshot\n return projectSlice(snapshot, request.projectRoot)\n}\n\n/**\n * One project's slice of a snapshot: its own project record and the root the\n * panel prints as watched, with the other projects dropped.\n * @param snapshot - the whole snapshot.\n * @param projectRoot - the project to keep.\n * @returns the narrowed snapshot.\n */\nexport function projectSlice(snapshot: McpSnapshot, projectRoot: string): McpSnapshot {\n return {\n ...snapshot,\n projects: snapshot.projects.filter((project) => project.projectRoot === projectRoot),\n watchedFiles: snapshot.watchedFiles.filter((file) => file === projectRoot),\n }\n}\n\n/**\n * Register the panel routes on the DSH web server.\n * @param webServer - the injected web server service.\n * @param service - the runtime's published service.\n * @returns the disposer: it closes the open status streams, then the routes.\n */\nexport function registerRoutes(webServer: WebServerLike, service: ProjectMcpService): () => void {\n const events = createEventStream(service)\n const registration = webServer.register({\n kind: 'prefix',\n path: ROUTE_PREFIX,\n handler: createRouteHandler(service, events),\n })\n return () => {\n events.dispose()\n disposeRegistration(registration)\n }\n}\n\n/**\n * Run one registration's disposer, whichever shape the web server hands back:\n * Cordis only ever calls a disposer *function* for an effect, and the server may\n * return a `{ dispose() }` object instead.\n * @param registration - the value `registerRoutes` returned.\n */\nexport function disposeRegistration(registration: unknown): void {\n if (typeof registration === 'function') {\n ;(registration as () => void)()\n return\n }\n if (typeof registration !== 'object' || registration === null) return\n const dispose = (registration as { dispose?: unknown }).dispose\n if (typeof dispose === 'function') (dispose as () => void).call(registration)\n}\n\n/**\n * Read a bounded JSON body; anything unparseable, oversized or non-object stays\n * an empty object.\n * @param req - the incoming request.\n * @param limit - largest body accepted, in bytes.\n * @returns the parsed object body, or `{}` when there is none.\n */\nasync function readJson(req: IncomingMessage, limit: number = MAX_BODY_BYTES): Promise<Record<string, unknown>> {\n const chunks: Buffer[] = []\n let size = 0\n for await (const chunk of req) {\n const buffer = chunk as Buffer\n size += buffer.length\n if (size > limit) return {}\n chunks.push(buffer)\n }\n try {\n const parsed: unknown = JSON.parse(Buffer.concat(chunks).toString('utf8'))\n return typeof parsed === 'object' && parsed !== null ? (parsed as Record<string, unknown>) : {}\n } catch {\n return {}\n }\n}\n\n/**\n * Shape one `POST save` body into a {@link SaveRequest}.\n *\n * Only the envelope is checked here: whether the entry itself parses, and\n * whether the document may be written, is the runtime's decision and comes back\n * as a coded refusal.\n * @param body - parsed request body.\n * @returns the request, or `undefined` when a required field is missing.\n */\nfunction saveRequestOf(body: Record<string, unknown>): SaveRequest | undefined {\n const { projectRoot, server, document, revision, entry } = body\n if (typeof projectRoot !== 'string' || projectRoot === '') return undefined\n if (typeof server !== 'string' || server === '') return undefined\n if (typeof document !== 'string' || document === '') return undefined\n if (typeof revision !== 'string' || revision === '') return undefined\n if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) return undefined\n return {\n projectRoot,\n server,\n document,\n revision,\n ...(body.consent === true ? { consent: true } : {}),\n entry: entry as EntrySnapshot,\n }\n}\n\n/**\n * Shape one `POST pin` body into a {@link PinRequest}.\n *\n * Only the envelope is checked here: whether the project has a live session is\n * the runtime's decision and comes back as a coded refusal.\n * @param body - parsed request body.\n * @returns the request, or `undefined` when a required field is missing.\n */\nfunction pinRequestOf(body: Record<string, unknown>): PinRequest | undefined {\n const { projectRoot, tool, pinned } = body\n if (typeof projectRoot !== 'string' || projectRoot === '') return undefined\n if (typeof tool !== 'string' || tool === '') return undefined\n if (typeof pinned !== 'boolean') return undefined\n return { projectRoot, tool, pinned }\n}\n\n/**\n * Shape one `POST policy` body into a {@link PolicyRequest}.\n *\n * The mode is validated here as well as in the runtime, so a switch carrying a\n * mode this build does not know is a `400` and never reaches the store.\n * @param body - parsed request body.\n * @returns the request, or `undefined` when a required field is missing.\n */\nfunction policyRequestOf(body: Record<string, unknown>): PolicyRequest | undefined {\n const { projectRoot, mode } = body\n if (typeof projectRoot !== 'string' || projectRoot === '') return undefined\n if (!isToolMode(mode)) return undefined\n return { projectRoot, mode }\n}\n\n/**\n * Shape one `POST conflict` body into a {@link ConflictRequest}.\n *\n * The answer is checked here as well as in the runtime, so a request carrying a\n * choice this build does not know is a `400` and never reaches the store. The\n * name itself is not checked against anything: a project that does not conflict\n * over it yet may still be given an answer, which is what makes the choice\n * survive a declaration that comes and goes.\n * @param body - parsed request body.\n * @returns the request, or `undefined` when a required field is missing.\n */\nfunction conflictRequestOf(body: Record<string, unknown>): ConflictRequest | undefined {\n const { projectRoot, server, choice } = body\n if (typeof projectRoot !== 'string' || projectRoot === '') return undefined\n if (typeof server !== 'string' || server === '') return undefined\n if (!isConflictChoice(choice)) return undefined\n return { projectRoot, server, choice }\n}\n","/**\n * `dsh-project-mcp` — per-project MCP servers for DeepSeek Harness.\n *\n * The host half reads a project's own MCP documents and mounts the declared\n * servers on the Cordis context of every session (`agent`) whose working\n * directory resolves to that project. Servers therefore exist exactly where\n * they are declared, and two projects may declare the same `serverName`\n * without colliding with each other or with profile-level entries.\n *\n * Sources, in increasing priority (later documents override by `serverName`):\n * 1. the global documents this deployment lists in `globalFiles` — none by default\n * 2. the project-relative documents it lists in `localFiles` —\n * `<project>/.dsh/mcp.json` out of the box\n *\n * @module dsh-project-mcp\n */\n\nimport type { Context } from '@deepseek-ai/cordis'\nimport z from '@deepseek-ai/schemastery'\nimport {\n DEFAULT_ACTIVATION_ENABLED,\n DEFAULT_ACTIVATION_MIN_CALLS,\n DEFAULT_ACTIVATION_SEEDED,\n DEFAULT_AUTO_ACTIVATION_LIMIT,\n DEFAULT_AUTO_ACTIVATION_STICKY_STEPS,\n DEFAULT_TOOL_BUDGET_CHARS,\n DEFAULT_TOOL_IDLE_MS,\n} from './activation.ts'\nimport {\n DEFAULT_FILE_MARKERS,\n DEFAULT_GLOBAL_FILES,\n DEFAULT_LOCAL_FILES,\n DEFAULT_PROJECT_MARKERS,\n defaultCredentialsPath,\n} from './discovery.ts'\nimport { DEFAULT_GUIDANCE_ENABLED } from './guidance.ts'\nimport { isValidLocalPrefix } from './naming.ts'\nimport { PolicyStore } from './policy.ts'\nimport { ProjectMcpRuntime } from './runtime.ts'\nimport type {\n AgentLike,\n AgentScopeLike,\n PolicyOutcome,\n RuntimeConfig,\n RuntimeOptions,\n SaveOutcome,\n ToolFactsOutcome,\n} from './runtime.ts'\nimport type { ConflictRequest, PinRequest, PolicyRequest, SaveRequest } from './shared.ts'\nimport { UsageStore, observeToolResults } from './usage.ts'\nimport type { ToolResultEventLike, ToolResultLike } from './usage.ts'\nimport { disposeRegistration, registerRoutes } from './ui.ts'\nimport type { WebServerLike } from './ui.ts'\nimport type { McpSnapshot, SnapshotChange } from './types.ts'\n\nexport { ProjectMcpRuntime, mountTrigger } from './runtime.ts'\nexport type {\n AgentLike,\n AgentMounts,\n AgentScopeLike,\n MountDecision,\n MountTrigger,\n PolicyOutcome,\n PolicySource,\n RuntimeConfig,\n RuntimeOptions,\n SaveOutcome,\n ToolFactsOutcome,\n UsageSource,\n} from './runtime.ts'\nexport {\n POLICY_FILE_NAME,\n POLICY_VERSION,\n PolicyStore,\n TOOL_MODES,\n isToolMode,\n parsePolicyDocument,\n policyFor,\n withMode,\n withPin,\n} from './policy.ts'\nexport type {\n PolicyDocument,\n PolicyLogger,\n PolicyState,\n PolicyStoreOptions,\n} from './policy.ts'\nexport { findProjectRoot, configDirectories, expandConfigPath, globalConfigPaths, localConfigPaths } from './discovery.ts'\nexport { parseDocument, mergeEntries, parseCredentials } from './parse.ts'\nexport {\n DEFAULT_ACTIVATION_ENABLED,\n DEFAULT_ACTIVATION_MIN_CALLS,\n DEFAULT_ACTIVATION_SEEDED,\n DEFAULT_SEARCH_LIMIT,\n DEFAULT_TOOL_IDLE_MS,\n MAX_SEARCH_LIMIT,\n MAX_SEARCH_TOKENS,\n SEARCH_TOOL_NAME,\n activate,\n createActivationState,\n createSearchTool,\n installActivation,\n noteUse,\n onCompaction,\n presentedNames,\n pruneIdle,\n seedFromUsage,\n withActiveTools,\n} from './activation.ts'\nexport type {\n ActivationContextLike,\n ActivationState,\n ActivationWiringOptions,\n AssembleListener,\n AssemblyLike,\n ListenerLike,\n SearchToolOptions,\n SeedOptions,\n SessionEventLike,\n TextBlockLike,\n ToolDefinitionLike,\n ToolSchemaLike,\n} from './activation.ts'\nexport {\n DEFAULT_GUIDANCE_ENABLED,\n GUIDANCE_SECTION_NAME,\n MAX_GUIDANCE_CHARS,\n MAX_GUIDANCE_PURPOSE,\n MAX_GUIDANCE_SERVERS,\n MAX_GUIDANCE_HIDDEN_NAMES,\n buildGuidance,\n installGuidance,\n projectLabel,\n} from './guidance.ts'\nexport type {\n GuidanceContextLike,\n GuidanceInput,\n GuidancePromptLike,\n GuidancePromptScopeLike,\n GuidanceSectionLike,\n GuidanceServer,\n GuidanceWiringOptions,\n} from './guidance.ts'\nexport {\n USAGE_FILE_NAME,\n USAGE_VERSION,\n UsageStore,\n matchServer,\n observeToolResults,\n parseUsageDocument,\n recordUsage,\n usageEventFor,\n} from './usage.ts'\nexport { createRouteHandler, disposeRegistration, registerRoutes } from './ui.ts'\nexport { ROUTE_PREFIX, TAB_ID } from './shared.ts'\nexport type { RouteHandler, WebServerLike } from './ui.ts'\nexport type {\n McpSnapshot,\n ProjectSnapshot,\n ServerRow,\n ServerStatus,\n ServerUsage,\n SessionSnapshot,\n SnapshotChange,\n SnapshotIssue,\n} from './types.ts'\nexport type {\n ToolResultEventLike,\n ToolResultLike,\n ToolResultObserverOptions,\n UsageCall,\n UsageDocument,\n UsageEvent,\n UsageLogger,\n UsageState,\n UsageStoreOptions,\n} from './usage.ts'\n\n/**\n * Plugin config: everything two deployments may want to set differently.\n *\n * Live editing: on DSH ≥ 0.1.7 the keys of {@link VOLATILE_CONFIG_KEYS} arrive\n * not as plain values but as volatile refs (`{ get(): T }`, see\n * {@link VolatileLike}) that the host re-points on every profile edit and\n * re-reads on `loader/volatile-update`. Every read of those keys goes through\n * {@link liveValue}, which accepts both shapes, so a plain object — yaml\n * config on an older host, and every test fixture — keeps working unchanged.\n */\nexport interface Config {\n /** Master switch; `false` mounts nothing and reads nothing. */\n enabled?: boolean\n /**\n * Project-relative MCP documents to read, lowest priority first — a later\n * document overrides an earlier entry of the same `serverName`. A spec is\n * relative to the project root, or absolute, or `~/…` / `$DSH_HOME/…`.\n * Default: `['.dsh/mcp.json']`.\n */\n localFiles?: string[]\n /**\n * Global MCP documents read before a project's own, lowest priority first.\n * A relative spec resolves against `$HOME`; `~`, `$DSH_HOME` and absolute\n * paths work as in {@link localFiles}. Empty — the default — reads none, so\n * a project never inherits a server it did not declare.\n *\n * A boolean is accepted as a **migration guard only**, for a config written\n * when this key was the switch \"also read `~/.dsh/mcp.json` and\n * `~/.kimi-code/mcp.json`\": `true` reads `~/.dsh/mcp.json`, `false` reads\n * nothing. Set a list instead.\n */\n globalFiles?: string[] | boolean\n /** Read `<project>/.env` and `<project>/.dsh/.env` for `${...}` values. */\n envFiles?: boolean\n /** Values for `${input:NAME}` references, consulted before env and credentials. */\n inputs?: Record<string, string>\n /** Directory names that terminate the upward project-root walk. */\n projectMarkers?: string[]\n /** File suffixes that also terminate the upward project-root walk. */\n fileMarkers?: string[]\n /** Timeout for every generated mcp-client config. */\n toolCallTimeoutMs?: number\n /** Whether a failed initial MCP connection should fail the mount. */\n failOnStartupError?: boolean\n /** Report a mount that produced no tool within this window as an error row; `0` disables. */\n connectTimeoutMs?: number\n /** Mount a session's project on its first turn instead of at session creation. */\n lazy?: boolean\n /** Release a session's mounts after this much inactivity; `0` disables. */\n idleTimeoutMs?: number\n /** How long the first step of a turn may wait for a pending mount; `0` never waits. */\n activationWaitMs?: number\n /** Profile-level `serverName` reservations win; the project row becomes `conflict`. */\n profileWins?: boolean\n /**\n * Local namespace a project entry mounts under when the profile already owns\n * its `serverName` and the user chose to see this project's copy as well,\n * at most five characters (`[A-Za-z0-9_-]`, {@link isValidLocalPrefix}).\n * Empty — the default — derives one from the project's own folder, so a\n * conflict has an answer without a setting. Only the local answer reads it:\n * the choice that mounts the entry under its declared name needs no prefix.\n */\n localPrefix?: string\n /** Watch project config documents for edits and re-sync. */\n watch?: boolean\n /** Debounce applied to watcher and lifecycle events (ms). */\n debounceMs?: number\n /** Safety-net rescan interval (ms). */\n rescanIntervalMs?: number\n /** Credentials document consulted for `${input:NAME}` values. */\n credentialsFile?: string\n /**\n * Offer the session's MCP tools through `mcp_search_tools` + activation, and\n * put the active ones back into each assembled request. `false` restores the\n * plain registry presentation: every mounted tool is always listed.\n */\n activationEnabled?: boolean\n /** Tools the durable counters may seed into the always-offered baseline; `0` seeds none. */\n activationSeeded?: number\n /** Calls one tool needs in the counters before it is seeded into the baseline. */\n activationMinCalls?: number\n /** Drop a session-activated tool after this long without a call; `0` disables. */\n toolIdleMs?: number\n /**\n * Publish one short project-MCP guidance section in the session's system\n * prompt, ahead of the per-server `mcp:<server>` instruction blocks, so the\n * model knows the rest of the project's tools can be requested. `false`\n * registers no section at all.\n */\n guidanceEnabled?: boolean\n /**\n * Cap on the names the context-driven tier offers at once; `0` disables the\n * tier. Optional so a config object that predates this feature keeps the\n * shipped default.\n */\n activationAutoLimit?: number\n /** Extra advances one context-driven offer survives after leaving the ranking. */\n activationAutoStickySteps?: number\n /**\n * Serialized size of a session's MCP surface, in characters, above which its\n * tools are offered on demand instead of being listed; `0` defers every\n * surface, however small.\n */\n activationToolBudgetChars?: number\n /**\n * Permit the panel to write the documents of the `globalFiles` list. `false`\n * keeps them read-only; a write also needs an explicit per-write consent, so\n * both gates must be open. Default `false`.\n */\n allowGlobalWrite?: boolean\n}\n\nconst DEFAULTS = {\n enabled: true,\n localFiles: [...DEFAULT_LOCAL_FILES],\n globalFiles: [...DEFAULT_GLOBAL_FILES],\n envFiles: true,\n toolCallTimeoutMs: 60_000,\n failOnStartupError: false,\n connectTimeoutMs: 60_000,\n lazy: true,\n idleTimeoutMs: 300_000,\n activationWaitMs: 2_000,\n profileWins: true,\n localPrefix: '',\n watch: true,\n debounceMs: 300,\n rescanIntervalMs: 10_000,\n activationEnabled: DEFAULT_ACTIVATION_ENABLED,\n activationSeeded: DEFAULT_ACTIVATION_SEEDED,\n activationMinCalls: DEFAULT_ACTIVATION_MIN_CALLS,\n toolIdleMs: DEFAULT_TOOL_IDLE_MS,\n guidanceEnabled: DEFAULT_GUIDANCE_ENABLED,\n activationAutoLimit: DEFAULT_AUTO_ACTIVATION_LIMIT,\n activationAutoStickySteps: DEFAULT_AUTO_ACTIVATION_STICKY_STEPS,\n activationToolBudgetChars: DEFAULT_TOOL_BUDGET_CHARS,\n allowGlobalWrite: false,\n} as const\n\nconst nonEmptyString = z.string().min(1)\n\n/**\n * The volatile-ref shape a DSH ≥ 0.1.7 host hands a volatile config field: a\n * stable reference whose `get()` reads the current, live-edited value.\n * Declared locally so no cordis version is needed to name it; an older host\n * passes the plain value instead, which {@link liveValue} also accepts.\n */\ninterface VolatileLike<T> {\n get(): T\n}\n\n// The loader's event typing ships with `@deepseek-ai/cordis-plugin-loader`,\n// which this plugin does not depend on; declaring the one event it listens to\n// keeps the dependency surface unchanged. The signature matches the loader's\n// own augmentation, so both merge cleanly where the loader's types are loaded.\ndeclare module '@deepseek-ai/cordis' {\n interface Events {\n /**\n * Volatile config values were committed into the running fiber without a\n * remount; dispatched to the owning fiber only.\n * @param paths - changed config paths as key arrays.\n */\n 'loader/volatile-update'(paths: readonly (readonly string[])[]): void\n }\n}\n\n/**\n * Mark a config field volatile — live-editable from Plugins → dsh-project-mcp\n * on DSH ≥ 0.1.7 — when the installed schemastery knows the flag. An older\n * schemastery at runtime gets the schema back unchanged, and the field stays\n * yaml-only there.\n */\nfunction volatileField<S>(schema: S): S {\n const mark = (schema as unknown as { volatile?: unknown }).volatile\n if (typeof mark !== 'function') return schema\n return (mark as (this: unknown) => S).call(schema)\n}\n\n/**\n * Read one config field that may be a live-edited volatile ref.\n * @param field - plain value, or a {@link VolatileLike} ref wrapping it.\n * @returns the current value, whichever shape arrived.\n */\nexport function liveValue<T>(field: T | VolatileLike<T> | undefined): T | undefined {\n if (\n typeof field === 'object' &&\n field !== null &&\n typeof (field as VolatileLike<T>).get === 'function'\n ) {\n return (field as VolatileLike<T>).get()\n }\n return field as T | undefined\n}\n\n/**\n * The {@link Config} keys a DSH ≥ 0.1.7 host may live-edit without restarting\n * the entry: all of them are read at use time, so merging them into the\n * running config is safe. Every other key is structural or boot-time\n * (documents, markers, credentials, the watch switch) and stays yaml-only.\n */\nexport const VOLATILE_CONFIG_KEYS: readonly (keyof RuntimeConfig)[] = [\n 'activationEnabled',\n 'activationSeeded',\n 'activationMinCalls',\n 'toolIdleMs',\n 'guidanceEnabled',\n 'activationAutoLimit',\n 'activationAutoStickySteps',\n 'activationToolBudgetChars',\n 'allowGlobalWrite',\n 'envFiles',\n 'lazy',\n 'localPrefix',\n 'profileWins',\n 'connectTimeoutMs',\n 'toolCallTimeoutMs',\n 'idleTimeoutMs',\n 'debounceMs',\n 'activationWaitMs',\n]\n\n/** Validated Loader schema for {@link Config}. */\nexport const Config: z<Config> = z.object({\n enabled: z.boolean().default(DEFAULTS.enabled),\n localFiles: z.array(nonEmptyString).default([...DEFAULT_LOCAL_FILES]),\n // The union is a migration guard, not a second setting: a document still\n // carrying the boolean this key used to be validates instead of failing the\n // entry, and `configuredFiles` reads its intent.\n globalFiles: z.union([z.array(nonEmptyString), z.boolean()]).default([...DEFAULT_GLOBAL_FILES]),\n envFiles: volatileField(z.boolean().default(DEFAULTS.envFiles)),\n inputs: z.dict(String).default({}),\n projectMarkers: z.array(nonEmptyString).default([...DEFAULT_PROJECT_MARKERS]),\n fileMarkers: z.array(nonEmptyString).default([...DEFAULT_FILE_MARKERS]),\n toolCallTimeoutMs: volatileField(z.number().step(1).min(1).default(DEFAULTS.toolCallTimeoutMs)),\n failOnStartupError: z.boolean().default(DEFAULTS.failOnStartupError),\n connectTimeoutMs: volatileField(z.number().step(1).min(0).default(DEFAULTS.connectTimeoutMs)),\n lazy: volatileField(z.boolean().default(DEFAULTS.lazy)),\n idleTimeoutMs: volatileField(z.number().step(1).min(0).default(DEFAULTS.idleTimeoutMs)),\n activationWaitMs: volatileField(\n z.number().step(1).min(0).max(30_000).default(DEFAULTS.activationWaitMs),\n ),\n profileWins: volatileField(z.boolean().default(DEFAULTS.profileWins)),\n localPrefix: volatileField(z.string().default(DEFAULTS.localPrefix)),\n watch: z.boolean().default(DEFAULTS.watch),\n debounceMs: volatileField(z.number().step(1).min(0).max(60_000).default(DEFAULTS.debounceMs)),\n rescanIntervalMs: z.number().step(1).min(1_000).default(DEFAULTS.rescanIntervalMs),\n credentialsFile: z.string().default(''),\n activationEnabled: volatileField(z.boolean().default(DEFAULTS.activationEnabled)),\n activationSeeded: volatileField(z.number().step(1).min(0).default(DEFAULTS.activationSeeded)),\n activationMinCalls: volatileField(\n z.number().step(1).min(0).default(DEFAULTS.activationMinCalls),\n ),\n toolIdleMs: volatileField(z.number().step(1).min(0).default(DEFAULTS.toolIdleMs)),\n guidanceEnabled: volatileField(z.boolean().default(DEFAULTS.guidanceEnabled)),\n activationAutoLimit: volatileField(\n z.number().step(1).min(0).default(DEFAULTS.activationAutoLimit),\n ),\n activationAutoStickySteps: volatileField(\n z.number().step(1).min(0).default(DEFAULTS.activationAutoStickySteps),\n ),\n activationToolBudgetChars: volatileField(\n z.number().step(1).min(0).default(DEFAULTS.activationToolBudgetChars),\n ),\n allowGlobalWrite: volatileField(z.boolean().default(DEFAULTS.allowGlobalWrite)),\n})\n\n/** Cordis plugin name used by loader diagnostics. */\nexport const name = 'project-mcp'\n\n/** Services required before project MCP servers can be mounted. */\nexport const inject = ['tools']\n\n/** Service name under which the runtime publishes its snapshot. */\nexport const SERVICE_NAME = 'projectMcp'\n\n/** Read-only handle published as the `projectMcp` service. */\nexport interface ProjectMcpService {\n /** Current rows per project with live sessions, merged and split per session. */\n snapshot(): McpSnapshot\n /**\n * Run one reconciliation pass immediately and await it, as the operator call:\n * it may start a session's declared servers without that session having\n * started a turn. Every other pass — a turn, an event, the rescan tick —\n * mounts only the sessions whose own working directory asked for their\n * project.\n * @param projectRoot - restricts the pass to one project's sessions.\n */\n syncNow(projectRoot?: string): Promise<void>\n /**\n * Ask for the same pass and answer at once, without waiting for it: the\n * panel's `Sync`. Scripted reconciliation awaits {@link ProjectMcpService.syncNow}.\n * @param projectRoot - restricts the pass to one project's sessions.\n */\n syncSoon(projectRoot?: string): void\n /**\n * Drop the failed mounts and re-mount them (after fixing their cause). Answers\n * as soon as they are dropped; the pass that mounts them again runs in the\n * background, because waiting for it is what made the panel's `Retry` look\n * hung while a server was still connecting.\n * @param projectRoot - restricts the drop and the pass to one project.\n */\n retry(projectRoot?: string): Promise<void>\n /**\n * Watch the picture instead of asking for it: the listener is told the current\n * state at once, then once per change that changes something. Backs the\n * panel's status channel, so an open panel polls nothing.\n * @param listener - told the revision and the whole snapshot it belongs to.\n * @returns a disposer that stops watching.\n */\n subscribe(listener: (change: SnapshotChange) => void): () => void\n /** Give one session's servers back now, or every mounted session's when no id is given. */\n release(agentId?: string): Promise<void>\n /**\n * Read one tool's detail for a row a panel opened: its model-facing\n * description, the fields its schema accepts, and the reason this session's\n * request does not carry it. Answered on demand instead of riding the\n * snapshot, because descriptions and schemas are the expensive part and this\n * is read once per opened row.\n * @param projectRoot - project root the panel read the row from.\n * @param sessionId - live agent id the row belongs to.\n * @param name - public registry name, as the panel drew it.\n * @returns the tool's facts, or the coded refusal the route maps to a status.\n */\n toolFacts(projectRoot: string, sessionId: string, name: string): ToolFactsOutcome\n /**\n * Write one edited entry back to the document that declares it.\n * @param request - entry body, declaring document and the revision it was read at.\n * @returns the fresh snapshot, or the coded refusal the route maps to a status.\n */\n save(request: SaveRequest): Promise<SaveOutcome>\n /**\n * Pin or unpin one tool of one project. Durable, and never a rescan: the policy\n * is not part of any declaring document.\n * @param request - project root, public tool name and the wanted pin state.\n * @returns the fresh snapshot, or the coded refusal the route maps to a status.\n */\n setPin(request: PinRequest): PolicyOutcome\n /**\n * Store one project's tool mode (`disclosure` | `direct` | `off`).\n * @param request - project root and the mode to store.\n * @returns the fresh snapshot, or the coded refusal the route maps to a status.\n */\n setPolicy(request: PolicyRequest): PolicyOutcome\n /**\n * Choose which declaration of one contested `serverName` this project shows.\n * Durable, and followed by a reconcile: the choice is what moves the entry\n * between a conflict report and a mount under its local name.\n * @param request - project root, contested name and the declaration to show.\n * @returns the fresh snapshot, or the coded refusal the route maps to a status.\n */\n setConflictChoice(request: ConflictRequest): PolicyOutcome\n}\n\n/**\n * Mount project-declared MCP servers per session scope.\n * @param ctx - host context of the plugin entry.\n * @param config - validated plugin configuration.\n */\nexport async function apply(ctx: Context, config: Config): Promise<void> {\n if (config.enabled === false) {\n ctx.logger.info('project-mcp: disabled by configuration')\n return\n }\n const usage = new UsageStore({ logger: ctx.logger })\n // The per-project tool policy is durable state of the same kind as the\n // counters, so it is loaded once here and published by the same runtime.\n const policy = new PolicyStore({ logger: ctx.logger })\n const runtime = new ProjectMcpRuntime(ctx, resolveConfig(config), { usage, policy })\n // A volatile-capable host (DSH ≥ 0.1.7) re-points the volatile refs inside\n // `config` on every profile edit and announces it here instead of restarting\n // the entry; an older host never emits the event, so this subscribes\n // unconditionally. `resolveConfig` re-reads the refs through `liveValue`,\n // and the runtime merges only the volatile keys.\n ctx.on('loader/volatile-update', () => {\n runtime.applyLiveConfig(resolveConfig(config))\n })\n const service: ProjectMcpService = {\n snapshot: () => runtime.snapshot(),\n syncNow: (projectRoot) => runtime.syncNow(projectRoot),\n syncSoon: (projectRoot) => runtime.syncSoon(projectRoot),\n retry: (projectRoot) => runtime.retry(projectRoot),\n release: (agentId) => runtime.release(agentId),\n toolFacts: (projectRoot, sessionId, name) => runtime.toolFactsOf(projectRoot, sessionId, name),\n save: (request) => runtime.saveEntry(request),\n setPin: (request) => runtime.setPin(request),\n setPolicy: (request) => runtime.setPolicy(request),\n setConflictChoice: (request) => runtime.setConflictChoice(request),\n subscribe: (listener) => runtime.subscribe(listener),\n }\n // `agents` exists in every interactive composition but is resolved lazily so\n // the plugin still loads when a deployment mounts it without the agent plane.\n ctx.inject(['agents'], (scope) => {\n runtime.attach(scope as unknown as AgentScopeLike)\n scope.provide(SERVICE_NAME, service)\n })\n // The sidebar panel runs in the browser half, which can reach neither this\n // service nor the host context that owns it: publish the same surface over HTTP\n // when the composition has a web server.\n ctx.inject(['webServer'], (scope) => {\n const webServer = (scope as unknown as { webServer?: WebServerLike }).webServer\n if (webServer === undefined) return\n scope.effect(() => {\n const registration = registerRoutes(webServer, service)\n return () => disposeRegistration(registration)\n }, 'project-mcp: panel routes')\n })\n ctx.effect(\n () => () => {\n void runtime.disposeAll()\n },\n 'project-mcp: runtime',\n )\n // Counters ride the registry's own result event: one listener for every\n // agent, attributed through the runtime's agent -> project mapping, so only\n // servers this plugin mounted can be counted. Activation freshness rides the\n // same event — a real call is what keeps an activated tool offered — so no\n // second `tools/result` subscription exists.\n ctx.effect(() => {\n const dispose = observeToolResults({\n on: (event, handler) =>\n ctx.on(event, (exec: ToolResultEventLike, result: ToolResultLike) => {\n runtime.noteToolUse(exec.agent?.id, exec.name)\n return handler(exec, result)\n }),\n mountsFor: (agentId) => runtime.mountsFor(agentId),\n store: usage,\n })\n return () => {\n dispose()\n usage.dispose()\n }\n }, 'project-mcp: usage counters')\n // The policy store owns the same debounced write the counters do, so it is\n // flushed and stopped with the fiber that created it.\n ctx.effect(\n () => () => {\n policy.dispose()\n },\n 'project-mcp: tool policy',\n )\n}\n\n/**\n * The local prefix one config asks for.\n *\n * A value the `serverName` alphabet cannot carry, or one longer than the five\n * characters the panel promises, is refused rather than trimmed: a silently\n * different namespace would rename a project's tools behind the user's back.\n * The empty string — the default and the answer to a refused value — asks for\n * the prefix derived from the project's own folder.\n *\n * @param value - raw `localPrefix` from the config.\n * @returns a valid prefix, or `''` for the derived one.\n */\nfunction localPrefixOf(value: string | undefined): string {\n if (value === undefined || value === '') return ''\n if (value === value.trim() && isValidLocalPrefix(value)) return value\n return ''\n}\n\n/**\n * One configured document list, from either shape the config can carry.\n *\n * A list is used as written. A boolean is the migration guard of the key that\n * used to be the switch \"also read the global documents\": `true` meant the\n * documents in `legacyTrue` (what that switch turned on), `false` meant none.\n * An absent value falls back to the default list.\n *\n * @param value - raw `localFiles` or `globalFiles`.\n * @param fallback - list used when the config says nothing.\n * @param legacyTrue - documents a legacy `true` stands for.\n * @returns specs, lowest priority first, with blanks dropped.\n */\nfunction configuredFiles(\n value: readonly string[] | boolean | undefined,\n fallback: readonly string[],\n legacyTrue: readonly string[],\n): string[] {\n if (value === undefined) return [...fallback]\n if (Array.isArray(value)) return value.filter((spec) => spec !== '')\n return value ? [...legacyTrue] : []\n}\n\n/** Resolve the plugin config into the runtime's fully-defaulted shape. */\nexport function resolveConfig(config: Config): RuntimeConfig {\n return {\n localFiles: configuredFiles(config.localFiles, DEFAULTS.localFiles, DEFAULT_LOCAL_FILES),\n // The only key whose boolean is legacy: it used to switch the DSH home\n // document on, so that is what `true` keeps meaning here.\n globalFiles: configuredFiles(config.globalFiles, DEFAULTS.globalFiles, ['$DSH_HOME/mcp.json']),\n envFiles: liveValue(config.envFiles) ?? DEFAULTS.envFiles,\n inputs: config.inputs ?? {},\n projectMarkers: [...(config.projectMarkers ?? DEFAULT_PROJECT_MARKERS)],\n fileMarkers: [...(config.fileMarkers ?? DEFAULT_FILE_MARKERS)],\n toolCallTimeoutMs: liveValue(config.toolCallTimeoutMs) ?? DEFAULTS.toolCallTimeoutMs,\n failOnStartupError: config.failOnStartupError ?? DEFAULTS.failOnStartupError,\n connectTimeoutMs: liveValue(config.connectTimeoutMs) ?? DEFAULTS.connectTimeoutMs,\n lazy: liveValue(config.lazy) ?? DEFAULTS.lazy,\n idleTimeoutMs: liveValue(config.idleTimeoutMs) ?? DEFAULTS.idleTimeoutMs,\n activationWaitMs: liveValue(config.activationWaitMs) ?? DEFAULTS.activationWaitMs,\n profileWins: liveValue(config.profileWins) ?? DEFAULTS.profileWins,\n localPrefix: localPrefixOf(liveValue(config.localPrefix)),\n watch: config.watch ?? DEFAULTS.watch,\n debounceMs: liveValue(config.debounceMs) ?? DEFAULTS.debounceMs,\n rescanIntervalMs: config.rescanIntervalMs ?? DEFAULTS.rescanIntervalMs,\n credentialsFile:\n config.credentialsFile !== undefined && config.credentialsFile !== ''\n ? config.credentialsFile\n : defaultCredentialsPath(),\n activationEnabled: liveValue(config.activationEnabled) ?? DEFAULTS.activationEnabled,\n activationSeeded: liveValue(config.activationSeeded) ?? DEFAULTS.activationSeeded,\n activationMinCalls: liveValue(config.activationMinCalls) ?? DEFAULTS.activationMinCalls,\n toolIdleMs: liveValue(config.toolIdleMs) ?? DEFAULTS.toolIdleMs,\n guidanceEnabled: liveValue(config.guidanceEnabled) ?? DEFAULTS.guidanceEnabled,\n activationAutoLimit: liveValue(config.activationAutoLimit) ?? DEFAULTS.activationAutoLimit,\n activationAutoStickySteps:\n liveValue(config.activationAutoStickySteps) ?? DEFAULTS.activationAutoStickySteps,\n activationToolBudgetChars:\n liveValue(config.activationToolBudgetChars) ?? DEFAULTS.activationToolBudgetChars,\n allowGlobalWrite: liveValue(config.allowGlobalWrite) ?? DEFAULTS.allowGlobalWrite,\n }\n}\n"],"mappings":";;;;;;;;;AAsgBA,MAAa,sBAAkC;CAAE,MAAM;CAAc,MAAM,CAAC;CAAG,SAAS,CAAC;AAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC5d3F,MAAa,6BAA6B;;;;;;AAO1C,MAAa,4BAA4B;;;;;;;AAQzC,MAAa,+BAA+B;;;;;;;;;AAU5C,MAAa,uBAAuB;;AAGpC,MAAa,uBAAuB;;AAGpC,MAAa,mBAAmB;;;;;;AAOhC,MAAa,oBAAoB;;AAGjC,MAAa,mBAAmB;;AAGhC,MAAM,6BAAkC,IAAI,IAAY;;AAuBxD,MAAa,mCAAmC;;;;;;;;;AAUhD,MAAa,4BAA4B;;AAGzC,MAAa,UAAU;;AAGvB,MAAa,SAAS;;;;;;;AAQtB,MAAa,mBAAm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AAU,OAAO,UAAU,KAAK,SAAS;EACrD,iBAAiB,UAAU,OAAO,eAAe,KAAK,SAAS;EAC/D,qBAAqB,UAAU,OAAO,mBAAmB,KAAK,SAAS;EACvE,2BACE,UAAU,OAAO,yBAAyB,KAAK,SAAS;EAC1D,2BACE,UAAU,OAAO,yBAAyB,KAAK,SAAS;EAC1D,kBAAkB,UAAU,OAAO,gBAAgB,KAAK,SAAS;CACnE;AACF"}
1
+ {"version":3,"file":"index.js","names":["compareNames","isRecord","MAX_SERVER_NAME_LENGTH","errorText","stringArray","stringRecord","DEFAULT_FLUSH_MS","isRecord","errorText","errorText","isRecord","isRecord","errorText"],"sources":["../src/types.ts","../src/activation.ts","../src/parse.ts","../src/discovery.ts","../src/guidance.ts","../src/naming.ts","../src/policy.ts","../src/bridge.ts","../src/logs.ts","../src/notifications.ts","../src/usage.ts","../src/write.ts","../src/runtime.ts","../src/shared.ts","../src/ui.ts","../src/index.ts"],"sourcesContent":["/**\n * Shared row/snapshot vocabulary for `dsh-project-mcp`.\n *\n * The host half publishes a {@link ProjectSnapshot} through the `projectMcp`\n * service so a future Web UI (or a test) can read what is mounted without\n * importing the runtime.\n *\n * @module dsh-project-mcp/types\n */\n\n/**\n * Type-only, and imported for its effect on the ambient types rather than for\n * anything this module uses: `@deepseek-ai/dsh-tools` declares `Context.tools`\n * and the `tools/change` / `tools/result` events as module augmentation of\n * `@deepseek-ai/cordis`, and TypeScript applies an augmentation only when the\n * augmenting module is part of the compilation. Nothing of the package reaches\n * the runtime — the import is erased by the compiler, and the plugin still\n * takes the service off the context it is handed instead of importing the\n * module.\n */\nimport type {} from '@deepseek-ai/dsh-tools'\n\n/** Runtime state of one project-declared MCP server. */\nexport type ServerStatus =\n /** Mounted and its tools are visible in the owning scope. */\n | 'active'\n /** Mounted; activation or the initial connection has not settled yet. */\n | 'connecting'\n /**\n * Declared, parsed, and not mounted: either `lazy` has not seen this\n * session's first turn yet, or the session went idle and its mounts were\n * released (`idleTimeoutMs`). The next turn mounts it again.\n */\n | 'idle'\n /** Declared with `enabled: false` — never mounted. */\n | 'disabled'\n /** The same `serverName` is reserved by a live profile-level instance. */\n | 'conflict'\n /** The entry or its mount failed; `detail` carries the reason. */\n | 'error'\n\n/** One server row of a project snapshot. */\nexport interface ServerRow {\n /** `serverName` (the `mcpServers` key, sanitized). */\n name: string\n /** Current lifecycle state. */\n status: ServerStatus\n /** Project root the entry was read from. */\n projectRoot: string\n /** Absolute path of the declaring document. */\n source?: string\n /** `stdio` or `streamable-http`, when the entry parsed. */\n transport?: 'stdio' | 'streamable-http'\n /**\n * Failure, stall or conflict explanation. Redacted on purpose: it names the\n * command but never its arguments, and an HTTP endpoint keeps its path but\n * drops the query string, because both can carry credentials.\n */\n detail?: string\n /**\n * Stable wire code of `detail` (`projectMcp.host` namespace), for\n * client-side translation. Optional and additive, exactly like\n * {@link blockedCode}: the prose field keeps its byte-identical English and\n * stays the fallback, so a client and a host of different builds degrade\n * rather than break.\n */\n detailCode?: string\n /**\n * Flat params of {@link detailCode}; a name ending in `Code` is itself a\n * wire code the client resolves two-level.\n */\n detailParams?: Record<string, string>\n /**\n * Parsed body of the entry, for the editor. Absent when the entry did not\n * parse — there is nothing to edit then.\n */\n entry?: EntrySnapshot\n /** Where this row may be written back, when it may be written at all. */\n writeScope?: WriteScope\n /** One line saying why writing is unavailable; always set for `readonly`. */\n writeBlockedReason?: string\n /**\n * Stable wire code of `writeBlockedReason` (`projectMcp.host` namespace),\n * for client-side translation. Optional and additive: the prose field keeps\n * its byte-identical English and stays the fallback, so a client and a host\n * of different builds degrade rather than break.\n */\n blockedCode?: string\n /**\n * Flat params of {@link blockedCode}; a name ending in `Code` is itself a\n * wire code the client resolves two-level.\n */\n blockedParams?: Record<string, string>\n /**\n * Opaque content revision of the declaring document at snapshot time. A save\n * must carry the revision it was built from: a mismatch means the document\n * changed underneath the editor, and the write is refused rather than merged.\n */\n documentRevision?: string\n}\n\n/**\n * How one `env` or `headers` entry is known to the host.\n *\n * A value can come from the declaring document, be answered outside it (the\n * project's own `.env` or the credentials file), or be withheld because it is a\n * credential. {@link EntryField.masked} is the field\n * that changes how a write treats it: a masked key submitted without a `value` is\n * kept exactly as the document declares it, so an editor that cannot see a secret\n * can never erase or replace one.\n */\nexport interface EntryField {\n /** Key exactly as declared. */\n readonly key: string\n /** Literal value; absent when the host withholds it. */\n readonly value?: string\n /** `true` when `value` is absent because the value is a secret. */\n readonly masked?: true\n /**\n * `true` when the key is answered outside the document — by the project's\n * `.env` or by the credentials file. The name predates the project dotenv\n * sources; the meaning the write path reads is \"never write this value back\".\n */\n readonly fromCredentials?: true\n}\n\n/**\n * One server entry as the host parsed it, for an editor.\n *\n * Every field is what the declaring document holds — a resolved default is never\n * folded in, because a save replaces the declaration, not the runtime config.\n */\nexport interface EntrySnapshot {\n /** Transport the entry declares. */\n readonly transport: 'stdio' | 'streamable-http'\n /** `stdio`: the program to run. */\n readonly command?: string\n /** `stdio`: its arguments, verbatim. */\n readonly args?: readonly string[]\n /** `stdio`: working directory, when the entry declares one. */\n readonly cwd?: string\n /** `stdio`: declared environment, secrets masked. */\n readonly env?: readonly EntryField[]\n /** `streamable-http`: the endpoint, with a credential-bearing query dropped. */\n readonly url?: string\n /** `streamable-http`: declared headers, secrets masked. */\n readonly headers?: readonly EntryField[]\n /** `false` when the declaration disables the server; absent means enabled. */\n readonly enabled?: boolean\n /** Declared connect timeout in milliseconds, when the entry sets one. */\n readonly connectTimeoutMs?: number\n /**\n * Keys the editor does not present, kept in their declared order and written\n * back untouched. A save replaces the entry wholesale, so dropping them would\n * delete configuration the panel never showed.\n */\n readonly extra?: Readonly<Record<string, unknown>>\n}\n\n/**\n * Whether one row's declaring document may be rewritten.\n *\n * - `project` — one of the deployment's project documents (`localFiles`,\n * `<project>/.dsh/mcp.json` out of the box);\n * - `global` — one of its global documents (`globalFiles`), written only with an\n * explicit per-write consent;\n * - `readonly` — the profile, `<DSH_HOME>` or a bundled document: never written.\n */\nexport type WriteScope = 'project' | 'global' | 'readonly'\n\n/**\n * One document a project is configured to read.\n *\n * The list a project publishes is exactly its read order — global documents\n * first, then the project's own — so the panel's priority number is an index\n * into it and never a table of hardcoded file names.\n */\nexport interface ConfiguredFile {\n /** Absolute path of the document. */\n readonly path: string\n /**\n * `global` — read for every project, before its own documents; `project` —\n * read from the project root.\n */\n readonly scope: 'global' | 'project'\n}\n\n/** Diagnostics surfaced alongside the rows. */\nexport interface SnapshotIssue {\n /** Absolute path of the declaring document. */\n source: string\n /** Server the diagnostic belongs to, when entry-scoped. */\n server?: string\n /** `error` or `warning`. */\n level: 'error' | 'warning'\n /** Human-readable text. */\n message: string\n /**\n * Stable wire code of `message` (`projectMcp.host` namespace), for\n * client-side translation. Optional and additive: `message` keeps its\n * byte-identical English and stays the fallback. Behavioural matches key on\n * this field — never on the prose, which the client may have translated.\n */\n code?: string\n /**\n * Flat params of {@link SnapshotIssue.code}; a name ending in `Code` is\n * itself a wire code the client resolves two-level.\n */\n params?: Record<string, string>\n}\n\n/**\n * One session's own view of the project it works in.\n *\n * Sessions of one project are independent: each mounts its own servers, and one\n * may have them running while another has not started a turn yet. The panel\n * needs that split, because a project-level merge alone cannot say *which*\n * session holds a mount.\n */\nexport interface SessionSnapshot {\n /** Agent (session) id. */\n id: string\n /** Rows for this session alone, in document order. */\n rows: ServerRow[]\n /** Diagnostics this session surfaced. */\n issues: SnapshotIssue[]\n /** What this session offers the model, when the host has mounted for it. */\n tools?: SessionTools\n /**\n * How many events of the project's ring belong to this session. Absent for a\n * session that produced none, so the tab's log badge reads a real `0`.\n */\n logCount?: number\n /**\n * `serverName` conflicts this session last reconciled: a profile-level\n * instance that already owns a name, or one name two project documents\n * declare. Published even when empty, so a reader can tell \"this session\n * reported none\" from a host that does not report conflicts at all.\n */\n conflicts?: readonly ServerConflict[]\n}\n\n/** One tool a session offers the model, and what put it in the request. */\nexport interface OfferedTool {\n /** Public registry name, eg `mcp__tglider__workspace`. */\n readonly name: string\n /**\n * The tier that offered it: `session` activated on demand through the search\n * tool, `context` ranked from the task text of the current conversation. The\n * counter-seeded baseline is not this shape — it is a plain name list in\n * {@link SessionTools.baseline}.\n */\n readonly via: 'session' | 'context'\n /**\n * Epoch milliseconds of the last offer or call. Absent for the context tier,\n * whose live state stamps an advance rather than a clock reading.\n */\n readonly at?: number\n /**\n * Number of the agent step (from `1`) the tool was offered at, or `undefined`\n * for a host that does not count steps. A panel that reads no number draws no\n * step tag at all rather than a made-up one.\n */\n readonly step?: number\n}\n\n/**\n * One accepted field of a tool's `parameters` schema, as the panel lists it.\n *\n * A field is listed from the definition the host already holds, so its type and\n * its `required` flag are the schema's own and neither is inferred from the\n * tool's name. Nesting stops at the top level: an object or array field is drawn\n * as its type, not expanded, because the panel lists what a call takes rather\n * than mirroring a schema. Schema `default` values are deliberately not part of\n * this shape — a default can carry a value the tool did not mean to publish.\n */\nexport interface ToolField {\n /** Property name, as the schema declares it. */\n readonly name: string\n /** JSON Schema `type` of the field, or `any` when the schema names none. */\n readonly type: string\n /** `true` when the schema's own `required` array names this property. */\n readonly required: boolean\n /** The property's own `description`, when the schema publishes one. */\n readonly description?: string\n}\n\n/**\n * Why one name is not in this session's request, in the host's own terms.\n *\n * The decision belongs to the host and the panel does not recompute it, so the\n * reason travels as data and its copy lives in the client's dictionaries. Every\n * figure here is a host measurement — the definition's own serialized size, the\n * session's budget, what the offered set already carries — so a reason line\n * invents no number. That is the same discipline as contract C2's step tag.\n */\nexport interface ToolReason {\n /**\n * Which decision left the name out. `budget` is the disclosure mode pushing it\n * past {@link ToolReason.budget}: the whole mounted surface is registered, and\n * this definition did not fit the request.\n */\n readonly kind: 'budget'\n /** Serialized size of this definition, in characters — the host's own figure. */\n readonly chars?: number\n /** The session's tool budget in characters, when the host budgeted one. */\n readonly budget?: number\n /** Characters the offered set already carries, when the host measured them. */\n readonly used?: number\n}\n\n/**\n * One tool's detail, answered on demand for a row the reader opened.\n *\n * The panel fetches this instead of carrying it in the snapshot: the snapshot\n * travels on every change frame and every poll, while a description and a schema\n * are read once per opened row. The text is model-facing and arrives as data —\n * it is never copied into a dictionary, is not translated, and is drawn as the\n * host published it.\n */\nexport interface ToolFacts {\n /** Public registry name this record answers about. */\n readonly name: string\n /** The definition's model-facing description, when the host holds one. */\n readonly description?: string\n /** Accepted fields, in schema order; empty when the tool declares none. */\n readonly fields: readonly ToolField[]\n /** Why the name is not offered, when it is not. Absent for an offered name. */\n readonly reason?: ToolReason\n}\n\n/**\n * Another loaded plugin that owns the assembled tool list.\n *\n * The plugin and such an owner cannot shape one request together: the outer\n * listener of whoever assembles last rewrites `assembly.tools`, so the plugin's\n * own deferral would be re-applied over an already-trimmed list. The host\n * reports the owner instead of silently composing with it, and a panel prints\n * the coexistence note only when this record is published.\n */\nexport interface PresentationOwner {\n /** Loader entry name, for example `dsh-progressive-tools`. */\n readonly name: string\n /** One line saying why coexisting in one request is impossible. */\n readonly note: string\n /**\n * The `projectMcp.host` code of {@link note} (F-48): the client translates\n * by it and falls back to `note`'s English, byte-identical, when the code is\n * absent or unknown. No params — the note is one fixed sentence.\n */\n readonly noteCode?: string\n}\n\n/**\n * One `serverName` two declarations fight over.\n *\n * `profile` is the profile-level `mcp-client` instance that already owns the\n * name: the project entry mounts only through the local alias the user chose,\n * and never under the contested name itself. `duplicate` is one name declared by\n * more than one project document: the highest-priority document wins and the\n * others are ignored.\n */\nexport interface ServerConflict {\n /** `serverName` the declarations share. */\n readonly server: string\n /** `profile` — a profile-level instance owns the name; `duplicate` — two documents. */\n readonly kind: 'profile' | 'duplicate'\n /** Declaring documents, the winner first. */\n readonly sources: readonly string[]\n /** One line: who wins, and why. */\n readonly message: string\n /**\n * The `projectMcp.host` code of {@link message} (F-48): the client translates\n * by it and falls back to `message`'s English, byte-identical, when the code\n * is absent (a host older than the field) or unknown to its dictionaries.\n */\n readonly code?: string\n /**\n * Flat params of {@link code}; numbers stringify at emission. A name ending\n * in `Code` is itself a wire code, resolved two-level through the same\n * namespace and substituted under the plain name.\n */\n readonly params?: Record<string, string>\n /**\n * The local name this project's entry mounts under when the user chose\n * `local`, as `mcp__<alias>__<tool>` in the model's own list. Published on a\n * `profile` conflict even while the choice is still the profile's, so the\n * panel can offer the alias it would use rather than inventing one.\n */\n readonly alias?: string\n /**\n * What the project's policy says about this name. Absent on a `duplicate`,\n * which no choice resolves, and on a host older than this field.\n */\n readonly choice?: ConflictChoice\n}\n\n/**\n * What one live session currently offers the model.\n *\n * Measured from the session's own state, not from the project: two sessions of\n * one project differ as soon as one of them has called a tool, and the panel's\n * promise is to show what *this* session's model sees.\n */\nexport interface SessionTools {\n /** Live agent (session) id this row describes. */\n readonly sessionId: string\n /**\n * Names offered because the durable counters proved them hot, plus the pins;\n * empty in `off`, which offers none of the project's tools.\n */\n readonly baseline: readonly string[]\n /** Names this session activated on demand, oldest first; empty in `off`. */\n readonly activated: readonly OfferedTool[]\n /** Names the task context offered, oldest first; empty in `off`. */\n readonly context: readonly OfferedTool[]\n /**\n * Names mounted for the project but not offered by this plugin, sorted. In\n * `disclosure` these are the names the budget pushed out of the request; in\n * `direct` the list is empty, because nothing is filtered; in `off` it is the\n * whole mounted surface, because a project that is switched off is offered not\n * at all. Its length is exactly the count a panel shows as hidden — and such a\n * panel has to read {@link ToolPolicy.mode} first, since tools another\n * presentation plugin leaves in the request are not this one's offers.\n */\n readonly deferred: readonly string[]\n /** Tools mounted for the project in total. */\n readonly mounted: number\n /** Serialized size of the mounted surface, in characters. */\n readonly surfaceChars: number\n /**\n * Serialized size of the offered set — {@link SessionTools.baseline} plus the\n * `activated` and `context` names — in characters. Absent from a host that\n * does not split the surface, and then a panel prints no request estimate\n * rather than inventing one.\n */\n readonly visibleChars?: number\n /**\n * Serialized size of {@link SessionTools.deferred}, in characters: exactly the\n * part of the mounted surface this plugin leaves out of the request. `0` when\n * nothing is deferred, so a panel that found this field may divide it by four\n * for a token estimate.\n */\n readonly deferredChars?: number\n /**\n * Configured deferral budget in characters. `0` means there is no threshold at\n * all: every surface counts as over budget, so tools are deferred however small\n * the project is. Read {@link SessionTools.deferring} rather than comparing this\n * with {@link SessionTools.surfaceChars} — the host owns the rule.\n */\n readonly budgetChars: number\n /**\n * `true` while the surface is over the budget, so tools really are deferred.\n * Only `disclosure` can defer: `direct` filters nothing and `off` offers\n * nothing, so both report `false` however large the mounted surface is.\n */\n readonly deferring: boolean\n}\n\n/** How one project's MCP tools are offered to the model. */\nexport type ToolMode =\n /** Offer the baseline and the on-demand tiers (the shipped behaviour). */\n | 'disclosure'\n /** Never defer: every mounted tool is listed in every request. */\n | 'direct'\n /** Do not offer this project's MCP tools at all. */\n | 'off'\n\n/**\n * How one `serverName` a project shares with a live profile instance is shown.\n *\n * The profile's instance owns the name in every scope, so the two declarations\n * cannot both mount under it. `profile` keeps the profile's tools exactly as\n * they are and leaves the project's entry unmounted; `local` mounts the\n * project's entry under a local namespace (see `src/naming.ts`) so both toolsets\n * reach the model — the only difference being the names they carry; `native`\n * mounts the project's entry under the name it declares, which is the nearer\n * declaration in this project's own sessions and so shadows the profile's tools\n * of that name there, while every other project keeps seeing the profile's.\n */\nexport type ConflictChoice =\n /** The profile instance keeps the name; the project entry does not mount. */\n | 'profile'\n /** The project entry mounts under its local alias, next to the profile's. */\n | 'local'\n /** The project entry mounts under the declared name, shadowing the profile's in this project. */\n | 'native'\n\n/**\n * One project's tool policy.\n *\n * The mode decides whether tools are deferred, the pins are the names the user\n * insists on — a pinned tool is offered from the first step of every request, is\n * never dropped by idle pruning or by a compaction, and is not counted against\n * the deferral budget's reading of what is hidden — and the aliases remember, per\n * conflicting `serverName`, which of the two declarations the user chose to see.\n */\nexport interface ToolPolicy {\n /** Mode in force. */\n readonly mode: ToolMode\n /**\n * Public registry names pinned for this project, in the order the user pinned\n * them. A name the project no longer mounts is kept: the declaration may come\n * back, and a pin that silently disappeared would be a surprise.\n */\n readonly pins: readonly string[]\n /**\n * Choice per contested `serverName`. Optional so every fixture, host and\n * stored document written before this field existed keeps meaning exactly\n * what it meant: a name that is absent is one the user never chose about,\n * and the shipped answer is the profile's instance. The store publishes an\n * empty map rather than dropping the field, so a reader may treat `undefined`\n * and `{}` alike.\n */\n readonly aliases?: Readonly<Record<string, ConflictChoice>>\n}\n\n/** The policy every project follows until one is configured. */\nexport const DEFAULT_TOOL_POLICY: ToolPolicy = { mode: 'disclosure', pins: [], aliases: {} }\n\n/**\n * How much one MCP server of one project has been used.\n *\n * Counted on the host from the tool registry's own events, so it is exact rather\n * than sampled, and keyed by project root: sessions come and go, the numbers\n * stay, which is what makes them usable for later decisions about a project.\n */\nexport interface ServerUsage {\n /** Calls dispatched through the registry, successful or not. */\n calls: number\n /** Calls whose result carried an error. */\n errors: number\n /** ISO timestamp of the most recent call. */\n lastUsedAt?: string\n /**\n * Per tool counts, keyed by the tool name as declared by the server, i.e.\n * without the `mcp__<serverName>__` prefix the registry publishes it under.\n */\n tools: Record<string, number>\n /**\n * The same readings split by session, keyed by the session (agent) id the\n * panel already uses everywhere else.\n *\n * Additive since F-34: a document written before this field existed is read as\n * it is — `USAGE_VERSION` does not move, because a reader that meets an unknown\n * version refuses the whole document and every counter would start from zero.\n * Absent means \"counted before the split\", never \"no calls\".\n */\n sessions?: Record<string, SessionUsage>\n}\n\n/**\n * One session's share of a server's counters.\n *\n * A server is mounted for a project and a project's sessions share it, so the\n * project total says what the project used while this says what *this* session\n * did; the two differ exactly when other sessions of the project called the\n * server, which is the case a panel scoped to one session could not show.\n */\nexport interface SessionUsage {\n /** Calls this session dispatched through the registry. */\n calls: number\n /** Of those, the ones whose result carried an error. */\n errors: number\n /** ISO timestamp of this session's most recent call. */\n lastUsedAt?: string\n /** This session's counts, keyed by the tool name as the server declares it. */\n tools: Record<string, number>\n}\n\n/**\n * How serious one plugin event is, as the Logs tab colours it.\n *\n * Four levels, mapped from the lifecycle line the host already writes: `info`\n * for a mount being registered, `up` for one whose tools became visible, `warn`\n * for a stall or a release, `error` for a failed mount and the unmount that\n * follows it. They are the labels the tab draws, not a host severity scale.\n */\nexport type LogLevel =\n /** The instance is being registered (`project-mcp: mounting …`). */\n | 'info'\n /** The instance's tools are visible (`… is up …`). */\n | 'up'\n /** A stall, a repeated pass, or a release the operator did not ask for. */\n | 'warn'\n /** The mount failed, or a failed mount is being torn down. */\n | 'error'\n\n/**\n * One lifecycle event, as the Logs tab lists it.\n *\n * The plugin's own events only — a mount, a start, a stop, a failure — mirroring\n * the lines the host writes to the DSH log, so the two readers see the same\n * facts. Events live in a per-project ring (`src/logs.ts`); the newest ones ride\n * in the snapshot, the rest are paged over the route.\n */\nexport interface LogEvent {\n /** When the event happened, epoch ms. */\n readonly at: number\n /** How serious it is, as the tab colours it. */\n readonly level: LogLevel\n /** Project root the event belongs to; the ring is keyed by it. */\n readonly projectRoot: string\n /**\n * Session the event is attributed to. Set exactly when the lifecycle line it\n * mirrors names one — `mounting`, `is up`, a stall — and absent on a\n * project-level event such as a shared instance's unmount.\n */\n readonly sessionId?: string\n /** `serverName` the event is about; absent for an event with no server. */\n readonly server?: string\n /** One line, without a newline: one event is one row of the tab. */\n readonly message: string\n /**\n * The three facts an error carries — the failure, the endpoint, the declaring\n * document — and no advice: the server row already offers the retry.\n */\n readonly detail?: string\n /**\n * Wire code of {@link LogEvent.message} (F-48), into the `projectMcp.host`\n * namespace. Optional: a host older than the field sends prose only, and the\n * client falls back to {@link LogEvent.message}.\n */\n readonly code?: string\n /** Flat params of {@link LogEvent.code}; numbers are stringified at emission. */\n readonly params?: Record<string, string>\n /** Wire code of {@link LogEvent.detail}, the same additive companion. */\n readonly detailCode?: string\n /** Flat params of {@link LogEvent.detailCode}. */\n readonly detailParams?: Record<string, string>\n}\n\n/** Everything one project contributes to the live runtime. */\nexport interface ProjectSnapshot {\n /** Project root the agents below resolved to. */\n projectRoot: string\n /**\n * Documents this project is configured to read, in priority order — global\n * ones first, then the project's own. Published even when empty, so a panel\n * can tell \"this deployment reads nothing\" from a host that does not report\n * its documents at all. Absent only from a snapshot a host older than this\n * field produced, and then a reader falls back to the shipped names rather\n * than inventing a priority.\n */\n files?: readonly ConfiguredFile[]\n /**\n * The tool policy in force for this project. Absent only from a snapshot a host\n * older than the policy store produced; a reader treats that as the shipped\n * default, {@link DEFAULT_TOOL_POLICY}.\n */\n policy?: ToolPolicy\n /** Live agent (session) ids currently bound to this project. */\n sessionIds: string[]\n /**\n * Merged rows for every declared server, in document order. When sessions\n * disagree about one server, the more actionable state wins, so a mounted or\n * broken server is never hidden behind a session that has not turned yet.\n */\n rows: ServerRow[]\n /** Parse and lifecycle diagnostics, deduplicated across the sessions. */\n issues: SnapshotIssue[]\n /** The same data split per session, in session-registration order. */\n sessions: SessionSnapshot[]\n /**\n * Usage counters keyed by `serverName`, remembered across sessions. Absent\n * while the host half has counted nothing for this project yet.\n */\n usage?: Record<string, ServerUsage>\n /**\n * Another loaded plugin that owns the assembled tool list, when the profile\n * has one. Absent means this plugin is the only owner — a panel that reads no\n * record draws no coexistence notice.\n */\n presentation?: PresentationOwner\n /**\n * Real `serverName` conflicts of this project: a profile-level instance that\n * already owns a name, or one name two project documents declare. The list is\n * always published — an empty one is the honest answer \"no conflicts\", which\n * is what lets a panel report that instead of offering a disabled button.\n */\n conflicts?: readonly ServerConflict[]\n /**\n * The newest events of this project's ring, oldest first, at most the page\n * size (50). Absent for a project that has recorded nothing, so a tab draws\n * its empty state rather than an empty list.\n */\n logs?: readonly LogEvent[]\n /**\n * How many events the project's ring holds right now, `0…200`. Absent exactly\n * when {@link ProjectSnapshot.logs} is: no events, nothing to count.\n */\n logCount?: number\n}\n\n/** Whole-plugin snapshot: one entry per project with live agents. */\nexport interface McpSnapshot {\n /** `true` while the agents service has been observed. */\n ready: boolean\n /** Projects with at least one live agent. */\n projects: ProjectSnapshot[]\n /**\n * Documents this deployment is configured to read, exactly as the config\n * spells them — `local` relative to a project root, `global` relative to\n * `$HOME` (or absolute). Published for the surfaces that must speak about the\n * deployment itself, with no project at hand: the empty state names what would\n * be read instead of a file name baked into the client. Absent from a snapshot\n * a host older than this field produced.\n */\n sources?: { readonly local: readonly string[]; readonly global: readonly string[] }\n /** Absolute paths currently watched for config edits. */\n watchedFiles: string[]\n}\n\n/**\n * One pushed picture: what the status channel sends.\n *\n * The snapshot travels whole rather than as a delta, so a frame that arrives\n * after a gap is still a complete answer — the panel can apply it without\n * asking for anything back. `revision` counts the changes the host has announced\n * and is what a late or repeated frame is judged by.\n */\nexport interface SnapshotChange {\n /** Monotonic change counter, starting at `0` for the picture a stream opens on. */\n revision: number\n /** The whole picture at that revision. */\n snapshot: McpSnapshot\n}\n","/**\n * Session-scoped activation of the MCP tools a project mounts.\n *\n * A project can declare a large MCP surface, and a model request must not carry\n * every tool the project owns. This module keeps the *presentation* list small\n * without touching the registry:\n *\n * - the usage counters seed a **baseline** of tools the project has called — one\n * call is enough ({@link seedFromUsage}) — and they are offered directly from\n * the first step on;\n * - the newest task text ranks the project's mounted tools with BM25, and the\n * best matches are offered through a **sticky window** that holds one offered\n * set across the session's steps ({@link advanceAutoOffer});\n * - the rest are discovered through the `mcp_search_tools` tool this module\n * registers in the agent scope, which **activates** the matches for the next\n * step ({@link activate});\n * - a compaction ends the session's activations that no call backs, while the\n * ones the model really called and the counter baseline stay\n * ({@link onCompaction}); idle pruning ({@link pruneIdle}) stays available\n * through a positive `toolIdleMs`, and the shipped `0` leaves it off, so the\n * compaction boundary is the one place that shrinks the offered set;\n * - the agent's own `system-prompt/assemble` listener puts the active schemas\n * back into the assembled request ({@link withActiveTools}).\n *\n * Everything the registry owns stays untouched: no tool is unregistered and no\n * restriction is installed (`ctx.tools.restrict()` cannot hide a scope-local\n * registration anyway — exactly where mcp-client registers its tools). The\n * listener only *adds* schemas to an assembly it did not author, and it is\n * contained: a failure of this plugin's own work returns the continuation's\n * value unchanged.\n *\n * The module is import-free of `@deepseek-ai/dsh-tools` on purpose: that peer is\n * not installed in every deployment, so the registry, definition and schema\n * surfaces are described by the minimal structural types below.\n *\n * @module dsh-project-mcp/activation\n */\n\nimport { DEFAULT_TOOL_POLICY } from './types.ts'\nimport type { OfferedTool, ServerUsage, SessionTools, ToolPolicy } from './types.ts'\n\n/** `true` while the session may offer MCP tools through search + activation. */\nexport const DEFAULT_ACTIVATION_ENABLED = true\n\n/**\n * Tools seeded into the baseline from the durable counters. A project with a\n * few dozen mounted tools calls more than a handful of them, so the cap sits\n * above the narrow window that used to evict a tool the project really uses.\n */\nexport const DEFAULT_ACTIVATION_SEEDED = 16\n\n/**\n * Calls one tool needs in the counters before it is seeded. One call is enough:\n * a tool the project actually uses enters the durable baseline the first time it\n * is called, so the baseline grows from real usage instead of waiting for the\n * counters to reach an arbitrary threshold.\n */\nexport const DEFAULT_ACTIVATION_MIN_CALLS = 1\n\n/**\n * How long a session-activated tool survives without a call (`0` disables).\n *\n * The shipped `0` keeps a searched tool offered for the rest of the session:\n * dropping it mid-session shrinks the request and rewrites the prompt prefix,\n * which invalidates the provider's prefix cache, so time-based removal stays an\n * explicit opt-in.\n */\nexport const DEFAULT_TOOL_IDLE_MS = 0\n\n/** Matches one `mcp_search_tools` call activates when it omits `limit`. */\nexport const DEFAULT_SEARCH_LIMIT = 8\n\n/** Hard cap on matches one `mcp_search_tools` call may activate. */\nexport const MAX_SEARCH_LIMIT = 50\n\n/**\n * Distinct query words one `mcp_search_tools` call scores at most. A query\n * longer than that is a sentence, and its tail words add noise rather than\n * signal — the first words are the ones the model chose first.\n */\nexport const MAX_SEARCH_TOKENS = 8\n\n/** Registry name of the discovery tool this module registers. */\nexport const SEARCH_TOOL_NAME = 'mcp_search_tools'\n\n/** Empty foreign set: what the containment reads when nothing is wired or foreign. */\nconst NO_FOREIGN: ReadonlySet<string> = new Set<string>()\n\n/**\n * Tools the context-driven tier may offer at once when `activationAutoLimit` is\n * unset; `0` disables the tier.\n */\nexport const DEFAULT_AUTO_ACTIVATION_LIMIT = 12\n\n/** Hard cap on the context-driven tier, however the config asks for more. */\nexport const MAX_AUTO_ACTIVATION_LIMIT = 50\n\n/**\n * Extra user messages a context-driven offer survives after the one that ranked\n * it; `0` keeps only that message. The offering set is recomputed when the task\n * context moves, so this is what holds one tool list across several steps.\n *\n * The shipped window spans a whole session: dropping an offer mid-session\n * rewrites the prompt prefix and invalidates the provider's prefix cache, so the\n * context tier grows and only resets at a compaction.\n */\nexport const DEFAULT_AUTO_ACTIVATION_STICKY_STEPS = 100\n\n/** Hard cap on the sticky window, however the config asks for more. */\nexport const MAX_AUTO_ACTIVATION_STICKY_STEPS = 1000\n\n/**\n * Serialized size of the MCP surface a session may offer directly before this\n * module defers anything, in characters. Roughly four characters per token, so\n * the default is about 10K tokens: below it the request would carry every\n * mounted tool anyway, and rewriting the prompt prefix to hide a few of them\n * buys nothing and costs the model its cache. `0` disables the gate and defers\n * the whole surface however small it is.\n */\nexport const DEFAULT_TOOL_BUDGET_CHARS = 40_000\n\n/** BM25 term-frequency saturation. */\nexport const BM25_K1 = 1.2\n\n/** BM25 document-length normalization. */\nexport const BM25_B = 0.75\n\n/**\n * Weight one tool-name hit carries over the same hit in the description. A name\n * hit is what a tool *is*, so it outranks a description that merely mentions the\n * term — without the weight a name repeated in a short description and a\n * description-only hit score nearly the same.\n */\nexport const BM25_NAME_WEIGHT = 1.5\n\n/**\n * Raw BM25 score a tool needs before the context-driven tier may offer it.\n *\n * The floor is what keeps a tool whose name or description shares one incidental\n * word with the task text out of the offered list. A term that stands out in the\n * corpus is worth roughly 1.4 for its first occurrence, one that is merely\n * frequent is worth under 0.3, and a term every tool shares is worth nothing —\n * so the floor sits above the ambient noise a plural or a common verb produces\n * and below a genuine match. Activation through `mcp_search_tools` stays\n * available for anything the floor rejects, and `activationAutoLimit: 0` turns\n * the tier off outright.\n */\nexport const MIN_AUTO_SCORE = 0.6\n\n/** Maximum task-context characters one advance considers (the newest tail wins). */\nexport const MAX_AUTO_QUERY_CHARS = 2_000\n\n/** Maximum tool names the recent-call history carries between advances. */\nexport const MAX_AUTO_RECENT_CALLS = 16\n\n/**\n * Minimal structural view of one model-facing tool schema.\n *\n * It is the exact element type of `system-prompt/assemble`'s `tools` list and of\n * `ctx.tools.schemas()`, described locally because `@deepseek-ai/dsh-tools` is a\n * peer this plugin does not import.\n */\nexport interface ToolSchemaLike {\n /** Public registry name, eg `mcp__alpha__run`. */\n readonly name: string\n /** Model-facing description. */\n readonly description: string\n /** JSON Schema object arguments. */\n readonly parameters: Record<string, unknown>\n}\n\n/** One text block of the model-facing content vocabulary. */\nexport interface TextBlockLike {\n /** Always `text`; the only block this module renders. */\n readonly type: 'text'\n /** Human-readable text. */\n readonly text: string\n}\n\n/**\n * Minimal structural view of a tool definition as `ctx.tools.register` accepts\n * it. Only the fields this module writes are declared.\n */\nexport interface ToolDefinitionLike {\n /** Registry name presented to the model. */\n readonly name: string\n /** Model-facing description. */\n readonly description: string\n /** JSON Schema object arguments. */\n readonly parameters: Record<string, unknown>\n /** Canonical output contract: a schema to validate and a content renderer. */\n readonly output: {\n /** Enforced JSON Schema of the canonical value `execute` returns. */\n readonly schema: Record<string, unknown>\n /**\n * Project the canonical value onto model-facing content.\n * @param args - parsed call arguments.\n * @param value - the validated canonical value.\n * @returns the content blocks the model sees.\n */\n render(args: unknown, value: unknown): readonly TextBlockLike[]\n }\n /**\n * Run one accepted call.\n * @param args - parsed call arguments.\n * @param context - execution identity; unused here.\n * @returns the canonical value declared by `output.schema`.\n */\n execute(args: unknown, context: unknown): Promise<unknown>\n}\n\n/** One listener as `ctx.on` accepts it (method syntax keeps parameters bivariant). */\nexport type ListenerLike = (...args: never[]) => unknown\n\n/**\n * The agent-scoped context slices this module touches. Described structurally so\n * the wiring is testable without a live harness.\n */\nexport interface ActivationContextLike {\n /**\n * Register an event listener through the scope; the scope owns its disposal.\n * @param name - event name.\n * @param listener - listener called with the event's dispatch arguments.\n * @param options - `prepend` places the listener outermost in a waterfall.\n * @returns the disposer, or anything the runtime returns for one.\n */\n on(name: string, listener: ListenerLike, options?: { prepend?: boolean }): unknown\n /** The tool registry, through the scope so registrations stay scope-local. */\n readonly tools: {\n /**\n * Register a tool in the calling scope.\n * @param definition - schema and execution.\n * @returns the exact disposer that unregisters the tool.\n */\n register(definition: ToolDefinitionLike): () => void\n }\n}\n\n/** The subset of one prompt assembly this module reads and returns. */\nexport interface AssemblyLike {\n /** Model-facing tool schemas, already in canonical order. */\n tools: ToolSchemaLike[]\n}\n\n/** Handler of the `system-prompt/assemble` waterfall this module installs. */\nexport type AssembleListener = (\n assembly: AssemblyLike,\n context: unknown,\n next: () => Promise<AssemblyLike>,\n) => Promise<AssemblyLike>\n\n/**\n * The fields the wiring reads from one appended session event: enough to catch\n * a `compaction/end` and to recover the task text of a committed `user/message`.\n */\nexport interface SessionEventLike {\n /** Session event type, eg `compaction/end`. */\n readonly type?: unknown\n /** Event payload, present on every committed event (`event.data`). */\n readonly data?: unknown\n}\n\n/**\n * One session's activation state.\n *\n * `baseline` is the counter-seeded set and outlives a compaction; `active` holds\n * the names this session activated through search or the context tier, each with\n * the epoch milliseconds of its last touch, and is what idle pruning and\n * compaction trim. `used` records the calls the session made for this plugin's\n * own namespace — the evidence a compaction keeps an activation by, because a\n * tool the model called is one the session really uses. It is cumulative for the\n * session and never bounded, so the compaction boundary shrinks the offers no\n * call backs and never shrinks a used tool again.\n *\n * Every field is read-only because every transition returns a new state.\n */\nexport interface ActivationState {\n /** Public names the durable counters proved hot; always offered. */\n readonly baseline: ReadonlySet<string>\n /** Session-activated public names mapped to their last touch. */\n readonly active: ReadonlyMap<string, number>\n /**\n * `mcp__` names this session called at least once and the durable baseline\n * does not already keep. Read by nothing but {@link onCompaction}, and\n * cumulative for the session: it is deliberately never bounded, so with the\n * shipped `DEFAULT_TOOL_IDLE_MS` of `0` nothing else removes a name and a tool\n * the session used stays offered for the rest of the session, across every\n * further compaction.\n */\n readonly used: ReadonlySet<string>\n}\n\n/**\n * Build one session's state.\n * @param baseline - counter-seeded public names; defaults to none.\n * @returns an empty active set and an empty used record over that baseline.\n */\nexport function createActivationState(baseline: Iterable<string> = []): ActivationState {\n return { baseline: new Set(baseline), active: new Map(), used: new Set() }\n}\n\n/** How {@link seedFromUsage} reads the durable counters. */\nexport interface SeedOptions {\n /** Maximum names seeded; `0` seeds none. */\n readonly count: number\n /** Calls one tool needs before it is seeded. */\n readonly minCalls: number\n}\n\n/**\n * Seed the baseline from a project's durable counters.\n *\n * The counters key tools by the name the server declares them under and servers\n * by `serverName`, so the public registry name is the `mcp__<server>` prefix plus\n * the tool key — the same reconstruction the counter's own attribution relies\n * on. A name the registry had to truncate cannot be reversed this way; such a\n * tool is simply not seeded, which is why the search tool stays the discovery\n * path of record.\n *\n * @param usage - counters of one project, or `undefined` when none were recorded.\n * @param options - seed cap and per-tool minimum.\n * @returns the baseline names, most-called first (name order breaks ties).\n */\nexport function seedFromUsage(\n usage: Record<string, ServerUsage> | undefined,\n options: SeedOptions,\n): Set<string> {\n const baseline = new Set<string>()\n if (usage === undefined || options.count <= 0) return baseline\n const candidates: { name: string; calls: number }[] = []\n for (const [server, serverUsage] of Object.entries(usage)) {\n for (const [tool, calls] of Object.entries(serverUsage.tools)) {\n if (calls < options.minCalls) continue\n candidates.push({ name: `mcp__${server}__${tool}`, calls })\n }\n }\n candidates.sort((left, right) => right.calls - left.calls || compareNames(left.name, right.name))\n for (const candidate of candidates.slice(0, options.count)) baseline.add(candidate.name)\n return baseline\n}\n\n/**\n * Activate names for this session, idempotently.\n *\n * A baseline name is skipped: it is already offered, so tracking it in the\n * session set would only make a compaction look like it changed something.\n *\n * @param state - activation state before the activation.\n * @param names - public names activated (already filtered to this plugin's mounts).\n * @param at - epoch milliseconds of the activation.\n * @returns the updated state, or the input when nothing changed.\n */\nexport function activate(\n state: ActivationState,\n names: Iterable<string>,\n at: number,\n): ActivationState {\n let active: Map<string, number> | undefined\n for (const name of names) {\n if (state.baseline.has(name)) continue\n if (state.active.get(name) === at) continue\n active ??= new Map(state.active)\n active.set(name, at)\n }\n return active === undefined ? state : { baseline: state.baseline, active, used: state.used }\n}\n\n/**\n * Record a call — the freshness of a session-activated tool and the evidence a\n * compaction keeps it by.\n *\n * `active` is refreshed exactly as before: a call is what keeps a\n * session-activated tool offered. `used` records the call itself, but only for\n * this plugin's own namespace: the core tools (`read`, `bash`, …) ride the same\n * `tools/result` hook, and they are no part of a session's MCP activation state.\n * A baseline name is not recorded either — the durable baseline already keeps it\n * offered, so recording the call would only make a compaction look like it\n * changed something.\n *\n * @param state - activation state before the call.\n * @param name - public name of the called tool.\n * @param at - epoch milliseconds of the call.\n * @returns the updated state, or the input when nothing changed.\n */\nexport function noteUse(state: ActivationState, name: string, at: number): ActivationState {\n const previous = state.active.get(name)\n const refresh = previous !== undefined && previous !== at\n // `used` post-dates the interface: a state an embedder built before the field\n // existed reads as a session that has used nothing, so the read is optional\n // and the write coalesces an empty record instead of throwing.\n const already = state.used?.has(name) === true\n const record = name.startsWith('mcp__') && !state.baseline.has(name) && !already\n if (!refresh && !record) return state\n const active = refresh ? new Map(state.active) : undefined\n active?.set(name, at)\n const used = record ? new Set(state.used ?? []) : undefined\n used?.add(name)\n return {\n baseline: state.baseline,\n active: active ?? state.active,\n used: used ?? state.used ?? new Set(),\n }\n}\n\n/**\n * Drop the session-activated tools that have not been called for `idleMs`.\n * The baseline is never pruned: it comes from the durable counters, not from the\n * session. `idleMs <= 0` disables pruning.\n *\n * A positive `idleMs` is an explicit opt-in to *forgetting*: an evicted name\n * leaves the used record with the offer it was about, so the sweep is final —\n * a later compaction cannot read the call back and resurrect what time already\n * dropped. A name the model needs again is activated again through search. The\n * names still inside the window keep their record, and a sweep that evicts\n * nothing returns its input.\n *\n * @param state - activation state at `now`.\n * @param now - epoch milliseconds of the sweep.\n * @param idleMs - age at which a tool falls out.\n * @returns the updated state, or the input when nothing was stale.\n */\nexport function pruneIdle(state: ActivationState, now: number, idleMs: number): ActivationState {\n if (idleMs <= 0 || state.active.size === 0) return state\n let active: Map<string, number> | undefined\n let used: Set<string> | undefined\n for (const [name, at] of state.active) {\n if (now - at < idleMs) continue\n active ??= new Map(state.active)\n active.delete(name)\n // `used` post-dates the interface, so a legacy state simply has no record to\n // forget; a record that is there is copied before it is dropped.\n if (state.used?.has(name) !== true) continue\n used ??= new Set(state.used ?? [])\n used.delete(name)\n }\n return active === undefined\n ? state\n : { baseline: state.baseline, active, used: used ?? state.used ?? new Set() }\n}\n\n/**\n * End the session's activations that no call backs, at the compaction boundary.\n *\n * A compaction rewrites the conversation, so the provider's prompt prefix is\n * recomputed anyway: this is the one boundary where dropping a tool costs no\n * cache, which is why idle time is off by default and why this is the only place\n * the offered set shrinks. Only the part the session never used goes — an offer\n * from a context match or a search that the model did not act on. A tool this\n * session did call is one it really uses, so it stays active, stamped with its\n * last touch; evicting it would charge a re-discovery step for a tool the\n * session demonstrably needs. A used name that was never activated falls back to\n * the compaction's own clock. The counter baseline is never pruned.\n *\n * The used record is cumulative for the session and deliberately never bounded:\n * with the shipped `DEFAULT_TOOL_IDLE_MS` of `0` nothing else removes a name, so\n * a tool the session used stays offered for the rest of the session, across every\n * further compaction. This boundary shrinks the offers no call backs — it never\n * shrinks one the session used again.\n *\n * @param state - activation state before the compaction.\n * @param at - epoch milliseconds of the compaction.\n * @returns the updated state, or the input when nothing was active or used, or\n * when the rebuild is equivalent to what is already there — a caller compares\n * by identity to tell a real change from a boundary that changed nothing.\n */\nexport function onCompaction(state: ActivationState, at: number): ActivationState {\n // `used` post-dates the interface: a state an embedder built before the field\n // existed reads as a session that has used nothing.\n const used = state.used ?? new Set<string>()\n if (state.active.size === 0 && used.size === 0) return state\n const active = new Map<string, number>()\n for (const name of used) active.set(name, state.active.get(name) ?? at)\n // A second compaction with no new call rebuilds exactly the map already there,\n // and an equal-but-different object would read as a change to every caller\n // that compares by identity. Same names and same stamps: the input comes back.\n if (active.size === state.active.size) {\n let equivalent = true\n for (const [name, stamp] of active) {\n if (state.active.get(name) !== stamp) {\n equivalent = false\n break\n }\n }\n if (equivalent) return state\n }\n return { baseline: state.baseline, active, used: state.used ?? new Set() }\n}\n\n/**\n * Every name this session currently offers: the baseline plus the session's own\n * activations.\n * @param state - current activation state.\n * @returns the union; the baseline itself when nothing is session-activated.\n */\nexport function presentedNames(state: ActivationState): ReadonlySet<string> {\n if (state.active.size === 0) return state.baseline\n return new Set([...state.baseline, ...state.active.keys()])\n}\n\n/**\n * Serialized size of a tool surface, in characters.\n *\n * Counts what a request actually carries per schema — name, description and the\n * JSON form of the parameters — so the number is comparable with\n * {@link DEFAULT_TOOL_BUDGET_CHARS}. Total: a `parameters` value that cannot be\n * serialized (a cycle) contributes nothing instead of throwing.\n *\n * @param schemas - the schemas a session may offer.\n * @returns the summed character count.\n */\nexport function surfaceChars(schemas: readonly ToolSchemaLike[]): number {\n let total = 0\n for (const schema of schemas) total += schemaChars(schema)\n return total\n}\n\n/**\n * Serialized size of one tool schema, in characters: the same measurement\n * {@link surfaceChars} sums, so a caller that splits a surface into two halves\n * counts each half by one rule.\n *\n * Exported for the same reason {@link surfaceChars} is: the on-demand tool\n * detail route answers the *size of one definition* as a host measurement, and\n * a reason line that recomputed it would risk a different number than the\n * budget decision it explains.\n *\n * @param schema - one schema a session may offer.\n * @returns its character count.\n */\nexport function schemaChars(schema: ToolSchemaLike): number {\n return schema.name.length + schema.description.length + serializedLength(schema.parameters)\n}\n\n/**\n * Whether one mounted surface is over the deferral budget.\n *\n * This is exactly the gate {@link installActivation} applies before it defers\n * anything, so a reader that reports the decision cannot drift from the\n * listener that makes it: a surface that fits the budget exactly is carried\n * whole, and a budget of `0` disables the comparison so every surface is over\n * it.\n *\n * @param chars - serialized surface size, as {@link surfaceChars} measures it.\n * @param budgetChars - configured budget in characters.\n * @returns `true` when the surface must be handed over on demand.\n */\nexport function overToolBudget(chars: number, budgetChars: number): boolean {\n return budgetChars <= 0 || chars > budgetChars\n}\n\n/**\n * The model-facing schema of a definition this module built itself, so its own\n * tool can be offered from the assembly listener rather than through the\n * registry alone.\n *\n * @param definition - a registry-ready tool definition.\n * @returns the three fields an assembly carries for it.\n */\nfunction schemaOf(definition: ToolDefinitionLike): ToolSchemaLike {\n return {\n name: definition.name,\n description: definition.description,\n parameters: definition.parameters,\n }\n}\n\n/** `JSON.stringify` length of one value, or `0` when it cannot be serialized. */\nfunction serializedLength(value: unknown): number {\n try {\n return JSON.stringify(value)?.length ?? 0\n } catch {\n return 0\n }\n}\n\n/**\n * Merge the session's active schemas into an already assembled tool list.\n *\n * Total and side-effect free: it copies the base list, never removes or reorders\n * an entry that is already there, and only appends an active schema that the\n * base does not already carry and that `available` actually publishes (a stale\n * baseline name of a server that is no longer mounted is silently skipped).\n * Missing schemas are inserted at their sorted position, so with the canonical\n * (lexicographic) base order DSH produces the result stays sorted; a deployment\n * with a custom `toolOrder` keeps its existing entries exactly where they were.\n *\n * @param baseTools - the assembly's tool list as the inner listeners left it.\n * @param available - live schemas this plugin may offer for the session.\n * @param activeNames - baseline plus session-activated public names.\n * @returns a new list; equal input yields an equal list.\n */\nexport function withActiveTools(\n baseTools: readonly ToolSchemaLike[],\n available: readonly ToolSchemaLike[],\n activeNames: ReadonlySet<string>,\n): ToolSchemaLike[] {\n const result = [...baseTools]\n if (activeNames.size === 0 || available.length === 0) return result\n const present = new Set(result.map((tool) => tool.name))\n const byName = new Map<string, ToolSchemaLike>()\n for (const tool of available) {\n if (!byName.has(tool.name)) byName.set(tool.name, tool)\n }\n const missing: ToolSchemaLike[] = []\n for (const name of activeNames) {\n if (present.has(name)) continue\n const tool = byName.get(name)\n if (tool === undefined) continue\n present.add(name)\n missing.push(tool)\n }\n missing.sort((left, right) => compareNames(left.name, right.name))\n for (const tool of missing) {\n const index = result.findIndex((existing) => compareNames(existing.name, tool.name) > 0)\n if (index === -1) result.push(tool)\n else result.splice(index, 0, tool)\n }\n return result\n}\n\n/**\n * The task context one auto-offer decision reads: the newest user-role text the\n * session committed, plus the tools it called since the last decision.\n *\n * A called name is context, never activation. Only names inside `available`\n * — the tools this plugin mounted for the session — can enter the window, so a\n * call to a profile-level or other-project tool cannot smuggle a foreign schema\n * into the request.\n */\nexport interface AutoOfferInput {\n /** Newest committed user message text; `''` when the session has none yet. */\n readonly userText: string\n /**\n * Tool names called since the last decision, call order preserved. Repeating\n * the list is safe: a name already inside the window keeps its stamp.\n */\n readonly recentCalls?: readonly string[]\n}\n\n/** How the context-driven tier ranks, caps, and holds one decision. */\nexport interface AutoOfferOptions {\n /** Maximum names one decision may offer; `0` disables the tier. */\n readonly limit?: number\n /**\n * Extra user messages a name survives after the one that ranked it. One\n * decision runs per new task text, so this is the sticky window width.\n */\n readonly stickySteps?: number\n /** Raw BM25 score a tool needs before it may be offered. */\n readonly minScore?: number\n}\n\n/**\n * The context-driven tier's state: a sticky window over the BM25 ranking of the\n * session's available tools.\n *\n * `window` maps a name to the decision that put it there, so a later decision\n * can count how long the name has been offered without renumbering anything.\n * {@link autoPresentedNames} reads the offered set back out. The state is\n * immutable; a decision that changes nothing returns its input object.\n */\nexport interface AutoOfferState {\n /** Name -> decision stamp of every name still inside the sticky window. */\n readonly window: ReadonlyMap<string, number>\n}\n\n/**\n * One empty context-driven state.\n * @returns a state whose window is empty.\n */\nexport function createAutoOfferState(): AutoOfferState {\n return { window: new Map() }\n}\n\n/**\n * Split free text into lowercase search tokens.\n *\n * Separators, punctuation and case boundaries all delimit a token, so `runSQL`,\n * `run_sql`, `run-sql` and `mcp__alpha__run` all yield `run`/`sql`/`mcp`/\n * `alpha` as separate terms instead of one opaque blob. A token must hold at\n * least one letter or digit, which drops the punctuation-only pieces.\n *\n * @param text - raw name, description, or task text.\n * @returns the tokens in source order, duplicates kept (BM25 needs term counts).\n */\nexport function tokenize(text: string): string[] {\n const tokens: string[] = []\n for (const chunk of text.split(/[^\\p{L}\\p{N}]+/u)) {\n if (chunk === '') continue\n for (const piece of chunk.split(/(?<=\\p{Ll})(?=\\p{Lu})|(?<=\\p{Lu})(?=\\p{Lu}\\p{Ll})/u)) {\n if (piece === '') continue\n const token = piece.toLowerCase()\n if (/[\\p{L}\\p{N}]/u.test(token)) tokens.push(token)\n }\n }\n return tokens\n}\n\n/**\n * Rank the available schemas against one task text with BM25.\n *\n * The corpus is each tool's name plus its description; the query is the task\n * text tokenized the same way. The name is repeated so a name hit outweighs a\n * description hit, and the name breaks score ties, so one corpus and query\n * always produce the same list. Candidates below `minScore` are dropped.\n *\n * @param schemas - live schemas this plugin may offer for the session.\n * @param query - task text to rank against.\n * @param limit - maximum names to return.\n * @param minScore - raw BM25 score a candidate needs.\n * @returns the top names, best first, deterministically ordered.\n */\nexport function rankToolsByQuery(\n schemas: readonly ToolSchemaLike[],\n query: string,\n limit: number,\n minScore: number,\n): string[] {\n const queryTokens = [...new Set(tokenize(query))]\n if (queryTokens.length === 0 || limit <= 0 || schemas.length === 0) return []\n\n const documents: {\n tool: ToolSchemaLike\n nameTokens: string[]\n descriptionTokens: string[]\n }[] = []\n const nameFrequency = new Map<string, number>()\n const descriptionFrequency = new Map<string, number>()\n let nameLength = 0\n let descriptionLength = 0\n for (const tool of schemas) {\n const description = typeof tool.description === 'string' ? tool.description : ''\n const nameTokens = tokenize(tool.name)\n const descriptionTokens = tokenize(description)\n documents.push({ tool, nameTokens, descriptionTokens })\n nameLength += nameTokens.length\n descriptionLength += descriptionTokens.length\n for (const token of new Set(nameTokens)) nameFrequency.set(token, (nameFrequency.get(token) ?? 0) + 1)\n for (const token of new Set(descriptionTokens)) {\n descriptionFrequency.set(token, (descriptionFrequency.get(token) ?? 0) + 1)\n }\n }\n const averageNameLength = Math.max(nameLength / documents.length, 1)\n const averageDescriptionLength = Math.max(descriptionLength / documents.length, 1)\n\n /** One field's BM25 contribution for one query term, matching the term count. */\n const fieldScore = (\n frequency: number,\n tokens: number,\n documentFrequency: number,\n averageLength: number,\n ): number => {\n const inverse = Math.log(\n 1 + (documents.length - documentFrequency + 0.5) / (documentFrequency + 0.5),\n )\n const saturation =\n (frequency * (BM25_K1 + 1)) /\n (frequency + BM25_K1 * (1 - BM25_B + (BM25_B * tokens) / averageLength))\n return inverse * saturation\n }\n\n const ranked: { name: string; score: number }[] = []\n for (const document of documents) {\n const nameCounts = countTokens(document.nameTokens)\n const descriptionCounts = countTokens(document.descriptionTokens)\n let score = 0\n for (const token of queryTokens) {\n if (nameCounts.has(token)) {\n score +=\n BM25_NAME_WEIGHT *\n fieldScore(\n nameCounts.get(token) ?? 0,\n document.nameTokens.length,\n nameFrequency.get(token) ?? 0,\n averageNameLength,\n )\n }\n if (descriptionCounts.has(token)) {\n score += fieldScore(\n descriptionCounts.get(token) ?? 0,\n document.descriptionTokens.length,\n descriptionFrequency.get(token) ?? 0,\n averageDescriptionLength,\n )\n }\n }\n if (score < minScore) continue\n ranked.push({ name: document.tool.name, score })\n }\n ranked.sort((left, right) => right.score - left.score || compareNames(left.name, right.name))\n return ranked.slice(0, limit).map((candidate) => candidate.name)\n}\n\n/** Term counts of one field, keyed by token. */\nfunction countTokens(tokens: readonly string[]): Map<string, number> {\n const counts = new Map<string, number>()\n for (const token of tokens) counts.set(token, (counts.get(token) ?? 0) + 1)\n return counts\n}\n\n/**\n * Read the newest user-role text out of one committed session event.\n *\n * Only text blocks enter the task context: an image or file block carries no\n * words to rank against, and an event that is not a `user/message` is not task\n * text at all.\n *\n * Neither is a synthetic `user/message`. The same event type carries every\n * plugin-authored context injection — runtime context snapshots, agent\n * instructions, skill catalogues, cron notices — and they are distinguished\n * only by `source.kind` (`plugin` against a human prompt's `user`). Ranking a\n * tool offer against a context snapshot rather than against the task is worse\n * than ranking against nothing, so only a `user` source is accepted. A\n * deployment that injects its own task text as a `plugin` message therefore\n * ranks on the last human turn instead of that injection.\n *\n * @param event - one event as the `session/event` listener receives it.\n * @returns the message text, or `''` when this event carries none.\n */\nexport function readUserMessage(event: SessionEventLike): string {\n if (event?.type !== 'user/message' || !isRecord(event.data)) return ''\n const source = event.data.source\n if (!isRecord(source) || source.kind !== 'user') return ''\n const content = event.data.content\n if (!Array.isArray(content)) return ''\n const parts: string[] = []\n for (const block of content) {\n if (!isRecord(block) || block.type !== 'text') continue\n if (typeof block.text === 'string') parts.push(block.text)\n }\n return parts.join('\\n').trim()\n}\n\n/**\n * Reset the context-driven tier: a compaction rewrote the conversation the\n * offers belonged to, so nothing sticky survives it.\n *\n * @param state - state before the compaction.\n * @returns an empty state, or the input when it was already empty.\n */\nexport function resetAutoOffer(state: AutoOfferState): AutoOfferState {\n if (state.window.size === 0) return state\n return createAutoOfferState()\n}\n\n/**\n * Bound one task text to the newest {@link MAX_AUTO_QUERY_CHARS} characters.\n *\n * The tail is the part that matters — a long message states its request last —\n * and the bound keeps one very long paste from turning every later ranking pass\n * into a scan of the whole message.\n *\n * @param text - committed user message text.\n * @returns the text unchanged when it is already short enough.\n */\nexport function boundTaskText(text: string): string {\n return text.length <= MAX_AUTO_QUERY_CHARS ? text : text.slice(text.length - MAX_AUTO_QUERY_CHARS)\n}\n\n/**\n * Advance the context-driven tier by one input: recompute the BM25 ranking and\n * merge it into the sticky window.\n *\n * A name survives for the advance that offered it plus `stickySteps` later\n * advances, instead of falling out the moment its score dips — that is what\n * keeps one tool list across the steps of a turn. An input that offers nothing\n * clears the window: there is nothing to be sticky about. Nothing here reads a\n * clock; the caller decides what one advance is, so the model stays\n * deterministic and testable.\n *\n * @param previous - state before this input.\n * @param input - the session's newest task text and recent calls.\n * @param available - live schemas this plugin may offer for the session.\n * @param options - ranking and window configuration.\n * @returns the next state, or the input state when nothing changed.\n */\nexport function advanceAutoOffer(\n previous: AutoOfferState,\n input: AutoOfferInput,\n available: readonly ToolSchemaLike[],\n options: AutoOfferOptions = {},\n): AutoOfferState {\n const limit = autoOfferLimit(options.limit)\n const stickySteps = autoOfferStickySteps(options.stickySteps)\n const ranked = rankToolsByQuery(available, input.userText, limit, options.minScore ?? MIN_AUTO_SCORE)\n const previousAdvance = currentAdvance(previous)\n\n // A called name is context, never activation: only a tool this plugin\n // mounted for the session may enter the window, so a call to a profile-level\n // or other-project tool cannot smuggle a foreign schema into the request.\n const mounted = new Set(available.map((schema) => schema.name))\n const calls: string[] = []\n for (const name of input.recentCalls ?? []) {\n if (name !== '' && mounted.has(name) && !calls.includes(name)) calls.push(name)\n }\n if (ranked.length === 0 && calls.length === 0) {\n const empty = createAutoOfferState()\n return sameAutoOffer(previous, empty) ? previous : empty\n }\n\n const advance = previousAdvance + 1\n // The stamp of the oldest advance still offered. A name entered at advance\n // `E` is offered at `E` itself plus the next `stickySteps` advances, so this\n // advance still shows `advance - stickySteps` and drops anything older.\n const firstKeptAdvance = Math.max(advance - stickySteps, 0)\n const window = new Map<string, number>()\n for (const [name, stamp] of previous.window) {\n if (name === AUTO_ADVANCE_KEY || stamp < firstKeptAdvance) continue\n window.set(name, stamp)\n }\n // A name the window already carries keeps the stamp its offer was made with,\n // so being called never shortens an offer; a fresh one is stamped current.\n for (const name of ranked) window.set(name, advance)\n for (const name of calls) {\n if (!window.has(name)) window.set(name, advance)\n }\n window.set(AUTO_ADVANCE_KEY, advance)\n\n const next: AutoOfferState = { window }\n return sameAutoOffer(previous, next) ? previous : next\n}\n\n\n\n/**\n * Reserved window key that records the advance the state has reached. A real\n * tool name can never collide with it: registry names are non-empty, and this\n * key is empty. {@link autoPresentedNames} skips it.\n */\nconst AUTO_ADVANCE_KEY = ''\n\n/** The advance one state has reached; `0` for a state that never advanced. */\nfunction currentAdvance(state: AutoOfferState): number {\n return state.window.get(AUTO_ADVANCE_KEY) ?? 0\n}\n\n/**\n * Every name the context-driven tier currently offers.\n * @param state - current context-driven state.\n * @returns the offered names, in code-unit order.\n */\nexport function autoPresentedNames(state: AutoOfferState): ReadonlySet<string> {\n const names = new Set<string>()\n for (const name of state.window.keys()) {\n if (name !== AUTO_ADVANCE_KEY) names.add(name)\n }\n return new Set([...names].sort(compareNames))\n}\n\n/**\n * Every name the context-driven tier currently offers, oldest offer first.\n *\n * The window stamps are advances, not clock readings: this state deliberately\n * holds no wall-clock time, so the order is recency in *decisions*. A caller\n * that needs a timestamp cannot read one from here.\n *\n * @param state - current context-driven state.\n * @returns the offered names, ordered by the advance that offered each.\n */\nexport function autoOffers(state: AutoOfferState): readonly string[] {\n const entries: { name: string; advance: number }[] = []\n for (const [name, advance] of state.window) {\n if (name === AUTO_ADVANCE_KEY) continue\n entries.push({ name, advance })\n }\n entries.sort((left, right) => left.advance - right.advance || compareNames(left.name, right.name))\n return entries.map((entry) => entry.name)\n}\n\n/**\n * Whether two context-driven states offer the same names.\n *\n * Only the presented names are compared, never the advance stamp and never the\n * per-name window stamps, so an advance that changes nothing hands back the\n * previous state without ticking the advance counter: the sticky window ages by\n * changes of the offered set, not by input count. This was reviewed as a\n * possible stickiness off-by-one and cannot produce a wrong offered set — a\n * stall can only hold names the ranking has just chosen again, and it ends at\n * the first advance whose set differs — so do not re-chase an age here before\n * reading `advanceAutoOffer`.\n */\nfunction sameAutoOffer(left: AutoOfferState, right: AutoOfferState): boolean {\n const leftNames = autoPresentedNames(left)\n const rightNames = autoPresentedNames(right)\n if (leftNames.size !== rightNames.size) return false\n for (const name of leftNames) {\n if (!rightNames.has(name)) return false\n }\n return true\n}\n\n/**\n * Read the offered-set cap, clamped to the supported range.\n * @param value - configured cap, or `undefined` for the shipped default.\n * @returns the effective cap; `0` disables the context-driven tier.\n */\nexport function autoOfferLimit(value: number | undefined): number {\n return Math.min(Math.max(value ?? DEFAULT_AUTO_ACTIVATION_LIMIT, 0), MAX_AUTO_ACTIVATION_LIMIT)\n}\n\n/**\n * Read the sticky-window configuration, clamped to the supported range.\n * @param value - configured extra advances, or `undefined` for the shipped default.\n * @returns the effective extra advances; `0` keeps only the current advance.\n */\nexport function autoOfferStickySteps(value: number | undefined): number {\n return Math.min(\n Math.max(value ?? DEFAULT_AUTO_ACTIVATION_STICKY_STEPS, 0),\n MAX_AUTO_ACTIVATION_STICKY_STEPS,\n )\n}\n\n/**\n * One live session's presentation inputs, read where the session's state lives.\n *\n * Every field is a snapshot-time read: `mounted` is the registry probe the\n * activation wiring itself consumes, and both states are the session's own, so\n * a caller that derives a row again after an activation sees it — nothing here\n * is a copy a later path updates.\n */\nexport interface SessionToolInput {\n /** Live agent (session) id the row describes. */\n readonly sessionId: string\n /** Schemas this plugin mounted for the session, as the registry lists them now. */\n readonly mounted: readonly ToolSchemaLike[]\n /** Activation state of the session; absent before its first seed. */\n readonly activation: ActivationState | undefined\n /** Context-driven window of the session; absent before its first advance. */\n readonly auto: AutoOfferState | undefined\n /** `false` when activation is off, so every mounted tool stays in the request. */\n readonly activationEnabled: boolean\n /** Deferral budget in characters; defaults to {@link DEFAULT_TOOL_BUDGET_CHARS}. */\n readonly budgetChars?: number\n /**\n * Tool policy of the session's project; absent means the shipped default,\n * {@link DEFAULT_TOOL_POLICY}. Read at call time like every other field here,\n * so the row follows a pin or a mode change as soon as it is stored.\n */\n readonly policy?: ToolPolicy\n /**\n * Step each session activation was recorded on, keyed by public name, and the\n * step this row is being read on. Both are optional and independent: `steps`\n * stamps the `activated` tier with the step its offer happened on, while\n * `step` stamps the context tier with the step the request belongs to. Absent\n * means the caller counts no steps, and then no tier carries a number — the\n * panel draws no step tag rather than a zero.\n */\n readonly steps?: ReadonlyMap<string, number>\n /** Step this row is read on; see {@link SessionToolInput.steps}. */\n readonly step?: number\n}\n\n/**\n * Derive what one session offers the model right now from its live state.\n *\n * The row is a *measurement*, not a decision: `mounted` counts the schemas the\n * caller probed, and `deferred` is exactly the part of that surface the request\n * does not carry, so `deferred.length` is the panel's \"hidden\" number and the\n * tier lists name why the rest is there. Nothing is cached: the same inputs\n * read after an activation list it.\n *\n * Names of tiers that the session no longer mounts are dropped, because the\n * row describes what is offered, not what once was. The context tier carries no\n * `at`: the live window stamps an advance, not a wall-clock time.\n *\n * The project's policy is read here too, and it decides all three fields. In\n * `disclosure` the row offers the counter baseline and the pins and hides the\n * part of the mounted surface the budget pushed out of the request. `direct`\n * filters nothing, so it hides nothing: `deferring` is `false` and `deferred` is\n * empty however large the surface is. `off` offers none of the project's tools,\n * so every tier of this row is empty and the whole mounted surface is `deferred`\n * — the row reports what *this* plugin contributes, and a project the user\n * switched off contributes nothing, whether or not another presentation plugin\n * leaves the tools visible to the model. Pinned names join the counter baseline,\n * so in `disclosure` and `direct` they are offered from the first step of every\n * request and are never counted as hidden, whatever the counters and the budget\n * say.\n *\n * @param input - live mount, activation, context, config and policy of one session.\n * @returns the presentation row, or `undefined` when the session mounts no tool\n * (a session the host has not turned has nothing to report, and an empty row\n * would claim it offers nothing rather than that its surface is absent).\n */\nexport function toolsFor(input: SessionToolInput): SessionTools | undefined {\n const mounted = input.mounted\n if (mounted.length === 0) return undefined\n const mountedNames = new Set(mounted.map((schema) => schema.name))\n const chars = surfaceChars(mounted)\n const budgetChars = input.budgetChars ?? DEFAULT_TOOL_BUDGET_CHARS\n const policy = input.policy ?? DEFAULT_TOOL_POLICY\n // Nothing is hidden while the surface fits: the activation listener leaves the\n // assembly untouched then, so a name a tier would have offered is in the\n // request anyway. Only a surface the gate defers can hide anything — and only\n // `disclosure` defers by size at all: `direct` filters nothing and `off`\n // offers nothing.\n const deferring =\n policy.mode === 'disclosure' && input.activationEnabled && overToolBudget(chars, budgetChars)\n // `off` offers none of the project's tools, so no tier of this row offers one\n // either. The pins stay in the policy and the session keeps its activations —\n // the mode is read again on the next assembly, so switching back finds them —\n // but a row that promises nothing is what makes the whole mounted surface\n // `deferred` below.\n const offersNothing = policy.mode === 'off'\n\n // A pin is the user's own always-offered name, so it belongs to the baseline\n // next to the counter-seeded ones. A pinned name the project no longer mounts\n // is not part of this row — but stays pinned in the policy store, so the\n // declaration coming back finds it again.\n const baselineNames = new Set<string>(input.activation?.baseline ?? [])\n for (const pin of policy.pins) baselineNames.add(pin)\n const baseline = offersNothing\n ? []\n : [...baselineNames].filter((name) => mountedNames.has(name)).sort(compareNames)\n // The step an activation was recorded on, when the caller counted one; `0`\n // (or no map at all) is \"this host does not count steps\", and a tier must then\n // carry no number rather than a zero a panel would draw as a step tag.\n const stepOf = (name: string): number | undefined => {\n const step = input.steps?.get(name)\n return step === undefined || step <= 0 ? undefined : step\n }\n const activated: OfferedTool[] = offersNothing\n ? []\n : [...(input.activation?.active ?? [])]\n .filter(([name]) => mountedNames.has(name))\n .sort(\n ([leftName, leftAt], [rightName, rightAt]) =>\n leftAt - rightAt || compareNames(leftName, rightName),\n )\n .map(([name, at]): OfferedTool => {\n const step = stepOf(name)\n return { name, via: 'session', at, ...(step === undefined ? {} : { step }) }\n })\n // The context tier is a live window, not a record of offers made: the stamp it\n // carries is the step this row is read on, which is the step the request it\n // describes belongs to. A caller that counts no steps leaves it absent.\n const context: OfferedTool[] = offersNothing\n ? []\n : (input.auto === undefined ? [] : autoOffers(input.auto))\n .filter((name) => mountedNames.has(name))\n .map((name): OfferedTool => ({\n name,\n via: 'context',\n ...(input.step === undefined ? {} : { step: input.step }),\n }))\n\n const offered = new Set<string>(baseline)\n for (const tool of activated) offered.add(tool.name)\n for (const tool of context) offered.add(tool.name)\n\n // `off` promises nothing, so the whole mounted surface is what this plugin\n // does not offer; `direct` filters nothing, so it hides nothing; only\n // `disclosure` over its budget hides the difference between the two.\n const deferred =\n offersNothing\n ? [...mountedNames].sort(compareNames)\n : deferring\n ? [...mountedNames].filter((name) => !offered.has(name)).sort(compareNames)\n : []\n\n // The request's own weight, split the way the request is: exactly the names in\n // `deferred` are the ones the assembly leaves out, so a surface that fits the\n // budget carries all of it and defers nothing, and what hiding saved is\n // `surfaceChars - visibleChars`. Both halves are measured with\n // {@link surfaceChars}, the same rule the budget gate uses, so the numbers\n // cannot drift from the decision.\n const deferredNames = new Set(deferred)\n let visibleChars = 0\n let deferredChars = 0\n for (const schema of mounted) {\n if (deferredNames.has(schema.name)) deferredChars += schemaChars(schema)\n else visibleChars += schemaChars(schema)\n }\n\n return {\n sessionId: input.sessionId,\n baseline,\n activated,\n context,\n deferred,\n mounted: mounted.length,\n surfaceChars: chars,\n visibleChars,\n deferredChars,\n budgetChars,\n deferring,\n }\n}\n\n/** Construction options for the `mcp_search_tools` definition. */\nexport interface SearchToolOptions {\n /** Live schemas the search matches and may activate: the whole visible MCP surface. */\n readonly available: () => readonly ToolSchemaLike[]\n /** Record the matched names as activated for the session. */\n readonly activate: (names: readonly string[]) => void\n /** Cap applied when a call omits `limit`; defaults to {@link DEFAULT_SEARCH_LIMIT}. */\n readonly defaultLimit?: number\n}\n\n/** One search result: what the model may call directly from the next step on. */\ninterface SearchMatch {\n readonly name: string\n readonly description: string\n}\n\n/**\n * Build the `mcp_search_tools` definition.\n *\n * The tool never pretends: a query that matches nothing says so, and it only\n * ever offers schemas its session actually sees (the caller supplies that\n * filtered list). Activating is enough to present a tool from the *next* step\n * on, because the assembly listener reads the state at every request.\n *\n * @param options - the session's visible schemas and activation sink.\n * @returns a registry-ready definition.\n */\nexport function createSearchTool(options: SearchToolOptions): ToolDefinitionLike {\n const defaultLimit = options.defaultLimit ?? DEFAULT_SEARCH_LIMIT\n return {\n name: SEARCH_TOOL_NAME,\n description:\n 'Search the MCP tools this session sees and activate every match, so the activated tools are offered directly from the next model step on. Use it when the tool you need is not listed: a tool it activates joins the offered list from the next model step on, and until then only the tools already listed are reliable. `query` matches tool names and descriptions — case-insensitive, each word on its own, so separate keywords (`issue update`) find what a whole sentence does not; `limit` caps how many matches are activated.',\n parameters: {\n type: 'object',\n properties: {\n query: {\n type: 'string',\n description: 'A keyword or name fragment of the needed MCP tool; several words are matched one by one.',\n },\n limit: {\n type: 'integer',\n description: `Maximum matches to activate; default ${defaultLimit}.`,\n },\n },\n required: ['query'],\n additionalProperties: false,\n },\n output: {\n // The canonical value is a small JSON object; any of its shapes is valid.\n schema: {},\n render: (_args, value) => [{ type: 'text', text: renderJson(value) }],\n },\n async execute(args) {\n const query = readQuery(args)\n if (query === '') {\n throw new Error(`${SEARCH_TOOL_NAME}: \"query\" must be a non-empty string`)\n }\n const matches = searchTools(options.available(), query, readLimit(args, defaultLimit))\n options.activate(matches.map((match) => match.name))\n return {\n query,\n matches,\n activated: matches.map((match) => match.name),\n message:\n matches.length === 0\n ? `no MCP tool of this project matches ${JSON.stringify(query)}`\n : `${matches.length} MCP tool(s) match and will be offered from the next step on`,\n }\n },\n }\n}\n\n/** What the wiring needs from the runtime; everything is read at use time. */\nexport interface ActivationWiringOptions {\n /** Agent-scoped context; both the listener and the search tool live here. */\n readonly ctx: ActivationContextLike\n /** Current activation state of the session. */\n readonly state: () => ActivationState\n /** Replace the session's activation state after a transition. */\n readonly setState: (next: ActivationState) => void\n /** Live schemas of the tools this plugin mounted for the session. */\n readonly available: () => readonly ToolSchemaLike[]\n /**\n * Every MCP schema the session sees — the profile plane, this plugin's own\n * mounts, and any F-19 forwarders — beyond {@link available}. The deferral\n * budget and the discovery tool count this whole surface, while the\n * context-driven tier and the usage counters keep reading `available` alone.\n * Absent means `available` is the whole surface, so a deployment whose\n * presentation owner already hides the profile plane keeps today's behaviour.\n */\n readonly visible?: () => readonly ToolSchemaLike[]\n /**\n * Names that belong to ANOTHER project mounted in this process, which this\n * session must never be offered. The runtime computes the set from the other\n * projects it manages, and the assembly listener drops every such name from\n * the assembled request — whatever the tool mode, and however large the\n * surface. The budget and the discovery tool keep counting the whole visible\n * surface, so this only trims the final list and never re-feeds the deferral\n * decision. Absent means nothing is foreign, which keeps a deployment without\n * the containment probe on today's behaviour.\n */\n readonly foreign?: () => ReadonlySet<string>\n /** Cap on the tools one search activates; defaults to {@link DEFAULT_SEARCH_LIMIT}. */\n readonly searchLimit?: number\n /**\n * Cap on the names the context-driven tier offers at once; defaults to\n * {@link DEFAULT_AUTO_ACTIVATION_LIMIT}, and `0` disables the tier.\n */\n readonly autoLimit?: number\n /** Extra advances a context offer survives; defaults to {@link DEFAULT_AUTO_ACTIVATION_STICKY_STEPS}. */\n readonly autoStickySteps?: number\n /** Lowest BM25 score the context-driven tier may offer; defaults to {@link MIN_AUTO_SCORE}. */\n readonly autoMinScore?: number\n /**\n * Serialized size of the MCP surface, in characters, above which this module\n * defers tools at all; defaults to {@link DEFAULT_TOOL_BUDGET_CHARS}. `0`\n * defers every surface, however small.\n */\n readonly toolBudgetChars?: number\n /**\n * Live tool policy of the session's project; absent means the shipped default,\n * {@link DEFAULT_TOOL_POLICY}. Read at every assembly, so a mode or pin change\n * applies from the next step on, without re-minting the scope.\n */\n readonly policy?: () => ToolPolicy\n /**\n * Number of the agent step this plugin is currently on, counted by the caller\n * from its own `agent/pre-step` hook. Read when a search activates names, so\n * the record of that offer carries the step it happened on. Absent means the\n * caller counts no steps, and then an activation records none.\n */\n readonly step?: () => number\n /**\n * Told the names one search just activated, and the step it happened on, so\n * the caller can keep that stamp for the lifetime of the session — longer\n * than one scope's wiring, which an idle release disposes. Absent drops the\n * stamp: the offer is still recorded, it simply carries no step.\n */\n readonly onActivated?: (names: readonly string[], step: number) => void\n /**\n * Told that a compaction ended some of the session's activations, so the\n * caller can drop the step records that belonged to the ones it removed.\n * Absent leaves the records in place, which only means a later activation of\n * the same name may carry the step of the offer the compaction removed.\n */\n readonly onCompaction?: () => void\n /**\n * Told that the offered set may have moved: a search activated names, a\n * compaction dropped the ones no call backed, or the context tier advanced.\n *\n * A harness whose assembly carries no tool list cannot be filtered from this\n * module at all (0.2.2 and later: declarations are provider-owned), so the\n * presentation lives in the caller's own registrations instead — the bridge's\n * `deferLoading` forwarders. This is the seat that keeps that copy level with\n * {@link ActivationState}; absent simply means nothing presents the set but the\n * assembly this module used to rewrite.\n */\n readonly onOfferedChanged?: () => void\n /** Context-driven state to start from; defaults to an empty state. */\n readonly autoState?: AutoOfferState\n /** Sink for the context-driven state after every advance that changed it. */\n readonly setAutoState?: (next: AutoOfferState) => void\n /** Sink for a contained failure of this plugin's own work. */\n readonly onError?: (error: unknown) => void\n}\n\n/**\n * The context-driven tier's live inputs, owned by the wiring for one scope.\n *\n * `userText` is the newest committed `user/message` and `calls` holds the tool\n * names called since the last advance; both are read from the events the\n * harness already dispatches, and `changed` records that the task context moved\n * since the offered set was last computed.\n */\ninterface ActivationQueryTracker {\n /** Context-driven state as of the last advance. */\n state: AutoOfferState\n /** Newest committed user-role text, `''` until the session has one. */\n userText: string\n /** Tool names called since the last advance, call order preserved. */\n calls: string[]\n /** `true` while a committed user message arrived after the last advance. */\n changed: boolean\n}\n\n/**\n * Install the session wiring on one agent scope: the `system-prompt/assemble`\n * listener, the `mcp_search_tools` registration, and the `session/event`\n * listener that feeds compaction, the task context, and the recent-call names.\n *\n * The listener is prepended so it is the **outermost** handler of the waterfall:\n * `next()` has already run every plugin that filters the catalogue (the\n * `dsh-progressive-tools` presentation this replaces), and the list it returns is\n * the one that runs. Idle pruning is not wired here — the runtime already\n * watches `agent/status`, and it calls {@link pruneIdle} on that transition.\n *\n * The context-driven tier advances only when the task context actually moves: a\n * new user message or a new tool call. When it does, and the resulting offered\n * set is the one the previous advance produced, this returns the identical\n * assembly object, so nothing downstream treats the tool list as changed.\n *\n * @param options - scope, session state accessors, and the mounted-schema probe.\n * @returns the disposer that unregisters everything installed here.\n */\nexport function installActivation(options: ActivationWiringOptions): () => void {\n const tracker: ActivationQueryTracker = {\n state: options.autoState ?? createAutoOfferState(),\n userText: '',\n calls: [],\n changed: false,\n }\n\n /**\n * Record the step an activation happened on. Owned by the caller, because the\n * session, not one scope's wiring, is what keeps an activation across an idle\n * release; this is the only place a search activation happens, so it is the\n * only place the record can be made.\n */\n const recordActivated = (names: readonly string[]): void => {\n const step = options.step?.() ?? 0\n if (step > 0) options.onActivated?.(names, step)\n }\n\n const dispose = (fn: () => void): void => {\n try {\n fn()\n } catch (error) {\n options.onError?.(error)\n }\n }\n const listen = (name: string, listener: ListenerLike, prepend: boolean): (() => void) => {\n const registered = options.ctx.on(name, listener, { prepend })\n return typeof registered === 'function' ? (registered as () => void) : () => undefined\n }\n\n /** Recompute the context-driven offer whenever the task context actually moved. */\n const advance = (): void => {\n const calls = tracker.calls\n tracker.calls = []\n // Nothing new: the offered set from the previous advance is still current,\n // so not touching it is what keeps the request prefix byte-identical.\n if (!tracker.changed && calls.length === 0) return\n tracker.changed = false\n if (autoOfferLimit(options.autoLimit) === 0) return\n const next = advanceAutoOffer(\n tracker.state,\n { userText: tracker.userText, recentCalls: calls },\n options.available(),\n {\n ...(options.autoLimit === undefined ? {} : { limit: options.autoLimit }),\n ...(options.autoStickySteps === undefined ? {} : { stickySteps: options.autoStickySteps }),\n ...(options.autoMinScore === undefined ? {} : { minScore: options.autoMinScore }),\n },\n )\n if (next === tracker.state) return\n tracker.state = next\n options.setAutoState?.(next)\n // The offered set moved, so a presentation that lives outside this assembly —\n // the bridge's `deferLoading` forwarders — has to follow it.\n options.onOfferedChanged?.()\n }\n\n /** Every name the session's explicit activation and context-driven tiers offer. */\n const offeredNames = (): ReadonlySet<string> => {\n const names = new Set(presentedNames(options.state()))\n for (const name of autoPresentedNames(tracker.state)) names.add(name)\n return names\n }\n\n /**\n * Every MCP schema the session sees, as one name-keyed surface: this plugin's\n * own mounts first, then the profile plane and any F-19 forwarders, each name\n * once. This plugin's discovery tool is left out by identity — it is added\n * separately below, so a profile that already lists a tool named\n * `mcp_search_tools` cannot shadow the one this module mints.\n */\n const wholeSurface = (): readonly ToolSchemaLike[] => {\n const available = options.available()\n const visible = options.visible?.() ?? []\n if (visible.length === 0) return available\n const seen = new Set<string>()\n const merged: ToolSchemaLike[] = []\n for (const schema of available) {\n if (schema.name === SEARCH_TOOL_NAME) continue\n seen.add(schema.name)\n merged.push(schema)\n }\n for (const schema of visible) {\n if (schema.name === SEARCH_TOOL_NAME || seen.has(schema.name)) continue\n seen.add(schema.name)\n merged.push(schema)\n }\n return merged\n }\n\n /**\n * Whether the whole visible MCP surface is large enough to be worth deferring\n * at all. A surface that already fits the budget is carried whole by the\n * request, so hiding a few of its tools would rewrite the prompt prefix — and\n * cost the model its cache — to save nothing. `0` disables the gate.\n */\n const deferring = (surface: readonly ToolSchemaLike[]): boolean =>\n overToolBudget(\n surfaceChars(surface),\n options.toolBudgetChars ?? DEFAULT_TOOL_BUDGET_CHARS,\n )\n\n /**\n * Containment: a name another project mounts in this process never reaches the\n * assembled request, whatever the mode does around it. The set is read fresh on\n * every assembly, and the whole visible surface the budget measures is\n * deliberately unchanged — containment trims the final list only, so the\n * deferral decision still counts a foreign name the host defect leaked into the\n * session's chain. Absent (or empty) means nothing is foreign, and the\n * continuation's value comes back by identity.\n */\n const contain = (result: AssemblyLike): AssemblyLike => {\n if (!Array.isArray(result.tools)) return result\n const foreign = options.foreign?.() ?? NO_FOREIGN\n if (foreign.size === 0) return result\n const kept = result.tools.filter((tool) => !foreign.has(tool.name))\n return kept.length === result.tools.length ? result : { ...result, tools: kept }\n }\n\n /**\n * The visible surface without the names another project's mount leaked into\n * this session's chain. The discovery catalogue is built from this rather than\n * from {@link wholeSurface}: a name the session may never be offered must not\n * come back as text through a search either, or the containment would hand the\n * foreign catalogue over one step later. The deferral decision still counts the\n * whole surface, foreign names included — they occupy the request just as\n * locally mounted ones would.\n */\n const searchable = (): readonly ToolSchemaLike[] => {\n const foreign = options.foreign?.() ?? NO_FOREIGN\n const surface = wholeSurface()\n return foreign.size === 0 ? surface : surface.filter((schema) => !foreign.has(schema.name))\n }\n\n const merge = (result: AssemblyLike): AssemblyLike => {\n const policy = options.policy?.() ?? DEFAULT_TOOL_POLICY\n // A harness whose assembly carries no tool list cannot be shaped from here at\n // all. From 0.2.2 on, `system-prompt/assemble` transforms a presentation and\n // the declared schemas are provider-owned, so a listener that rewrote\n // `assembly.tools` would be writing into a field the harness discards — and\n // reading it would throw on every model request. The presentation lives in\n // the caller's `deferLoading` forwarders instead (`src/bridge.ts`), kept level\n // through {@link ActivationWiringOptions.onOfferedChanged}; this listener\n // still drives the context tier and degrades to the rest of the harness's\n // answer.\n if (!Array.isArray(result.tools)) {\n if (policy.mode === 'disclosure') advance()\n return result\n }\n const surface = wholeSurface()\n // Nothing is visible: there is nothing to find, so nothing is added.\n if (surface.length === 0) return contain(result)\n // `off` promises that the project's tools are not offered, and the promise is\n // about the request, not only about what the panel says: the project plane\n // leaves the assembly here. Only this plugin's own mounts go — the profile\n // plane and other plugins' tools are none of this mode's business — and a pin\n // does not cancel the mode, so the discovery tool is not advertised either,\n // because there is nothing it may disclose.\n if (policy.mode === 'off') {\n const mounted = options.available()\n if (mounted.length === 0) return contain(result)\n const offNames = new Set(mounted.map((schema) => schema.name))\n const kept = result.tools.filter((tool) => !offNames.has(tool.name))\n return contain(kept.length === result.tools.length ? result : { ...result, tools: kept })\n }\n // `direct` is the opposite promise: the whole visible catalogue is listed, so\n // the assembly is handed back exactly as the rest of the harness produced it\n // and the discovery tool is not advertised — except that another project's\n // tools, which this session must never carry, still leave it.\n if (policy.mode !== 'disclosure') return contain(result)\n advance()\n // The discovery tool is pinned: offered in every disclosure assembly,\n // whatever the budget says. A surface inside the budget is carried whole —\n // every mounted tool stays listed — and the search tool is added alongside\n // them so the model can always discover tools as the project grows. Over\n // budget, this module does the trimming a presentation owner would\n // otherwise do: every `mcp__` tool the budget pushed out is dropped, while\n // the non-MCP tools the inner listeners listed (core tools, other plugins)\n // are kept. `withActiveTools` inserts the wanted schemas at their sorted\n // position and never duplicates or reorders an existing entry. Pins are\n // wanted unconditionally — offered from the first step of every request,\n // whatever the counters and the budget say — and a pin or activation may\n // name a profile-plane tool, whose schema is found in `surface` and\n // re-inserted.\n const defer = deferring(surface)\n const wanted = new Set(offeredNames())\n for (const pin of policy.pins) wanted.add(pin)\n wanted.add(SEARCH_TOOL_NAME)\n const kept = defer\n ? result.tools.filter(\n (tool) => wanted.has(tool.name) || !tool.name.startsWith('mcp__'),\n )\n : result.tools\n const merged = withActiveTools(kept, [...surface, schemaOf(search)], wanted)\n // Identity is decided on the list this call produced, never on whether the\n // names this module wants have changed: the inner listeners rebuild the\n // registry list from scratch on every step and re-apply their own filtering,\n // so a memoized \"nothing changed\" answer would hand back their trimmed list\n // with this module's additions missing, one step after they appeared.\n // Returning `result` when nothing was dropped or added keeps the prompt\n // prefix — and the model's cache — byte-identical, the property that matters.\n const changed = kept.length !== result.tools.length || merged.length !== kept.length\n return contain(changed ? { ...result, tools: merged } : result)\n }\n\n const assemble: AssembleListener = async (_assembly, _context, next) => {\n const result = await next()\n try {\n return merge(result)\n } catch (error) {\n // A listener that throws would break every model request of the session;\n // this one degrades to \"the assembly the rest of the harness produced\".\n options.onError?.(error)\n return result\n }\n }\n\n const observe = (_session: unknown, event: SessionEventLike): void => {\n try {\n if (event?.type === 'compaction/end') {\n options.setState(onCompaction(options.state(), Date.now()))\n // The step records of the activations the compaction just dropped go\n // with them: a name activated again after this is stamped with the step\n // it returns on, not with the one it left on, while a tool the session\n // really used keeps the step its offer happened on.\n options.onCompaction?.()\n // A compaction rewrote the conversation the offers belonged to, so the\n // context tier starts over; the counter baseline is untouched.\n tracker.state = resetAutoOffer(tracker.state)\n tracker.calls = []\n tracker.changed = false\n // The boundary is the one place that shrinks the offered set, so a\n // presentation outside this assembly re-applies it here.\n options.onOfferedChanged?.()\n return\n }\n if (event?.type === 'user/message') {\n const text = readUserMessage(event)\n // An empty text (an image-only or non-text message) says nothing about\n // the task, so it must not wipe a context an earlier message set up.\n if (text !== '' && text !== tracker.userText) {\n const bounded = boundTaskText(text)\n tracker.changed = bounded !== tracker.userText\n tracker.userText = bounded\n }\n return\n }\n if (event?.type === 'tool/call') {\n const name = readCallName(event)\n if (name !== '') {\n tracker.calls.push(name)\n if (tracker.calls.length > MAX_AUTO_RECENT_CALLS) {\n tracker.calls.splice(0, tracker.calls.length - MAX_AUTO_RECENT_CALLS)\n }\n }\n }\n } catch (error) {\n options.onError?.(error)\n }\n }\n\n const search = createSearchTool({\n available: searchable,\n activate: (names) => {\n recordActivated(names)\n options.setState(activate(options.state(), names, Date.now()))\n options.onOfferedChanged?.()\n },\n ...(options.searchLimit === undefined ? {} : { defaultLimit: options.searchLimit }),\n })\n\n const disposers: (() => void)[] = [\n listen('system-prompt/assemble', assemble as unknown as ListenerLike, true),\n listen('session/event', observe as unknown as ListenerLike, false),\n ]\n try {\n disposers.push(options.ctx.tools.register(search))\n } catch (error) {\n options.onError?.(error)\n }\n return () => {\n for (const registered of disposers) dispose(registered)\n }\n}\n\n/**\n * Read the tool name out of one committed `tool/call` event.\n *\n * The recent calls are context evidence only, never activation: a name the\n * context tier offers is still filtered by the runtime's own mount records, so\n * a call to a profile-level tool cannot smuggle a foreign name into the list.\n *\n * @param event - one event as the `session/event` listener receives it.\n * @returns the called tool's public name, or `''` when the event carries none.\n */\nfunction readCallName(event: SessionEventLike): string {\n if (event.type !== 'tool/call' || !isRecord(event.data)) return ''\n const name = event.data.name\n return typeof name === 'string' ? name : ''\n}\n\n/** Read and normalize the `query` argument. */\nfunction readQuery(args: unknown): string {\n if (!isRecord(args)) return ''\n const query = args.query\n return typeof query === 'string' ? query.trim() : ''\n}\n\n/** Read the `limit` argument, clamped to the tool's supported range. */\nfunction readLimit(args: unknown, fallback: number): number {\n if (!isRecord(args)) return fallback\n const raw = args.limit\n if (typeof raw !== 'number' || !Number.isFinite(raw)) return fallback\n const limit = Math.trunc(raw)\n if (limit <= 0) return fallback\n return Math.min(limit, MAX_SEARCH_LIMIT)\n}\n\n/**\n * Score one schema against the query: an exact name beats a name substring, and\n * both beat a description hit. Results keep the best score first and the name\n * order breaks ties, so one query always returns the same list.\n */\nfunction searchTools(\n available: readonly ToolSchemaLike[],\n query: string,\n limit: number,\n): SearchMatch[] {\n const needle = query.toLowerCase()\n const tokens = searchTokens(needle)\n const scored: { match: SearchMatch; score: number }[] = []\n for (const tool of available) {\n const description = typeof tool.description === 'string' ? tool.description : ''\n const score = scoreTool(tool.name, description, needle, tokens)\n if (score === 0) continue\n scored.push({ match: { name: tool.name, description }, score })\n }\n scored.sort((left, right) => right.score - left.score || compareNames(left.match.name, right.match.name))\n return scored.slice(0, limit).map((entry) => entry.match)\n}\n\n/**\n * Distinct words of a query, lowercased, in first-use order. Words shorter\n * than two characters are dropped (a one-letter word is a substring of half\n * the catalog and scores noise, not intent); the split keeps letters, digits\n * and underscores, so a query may quote a tool name verbatim (`issue_update`)\n * as well as name its concepts (`issue update`).\n */\nfunction searchTokens(needle: string): string[] {\n const tokens: string[] = []\n const seen = new Set<string>()\n for (const piece of needle.split(/[^\\p{L}\\p{N}_]+/u)) {\n if (piece.length < 2 || seen.has(piece)) continue\n seen.add(piece)\n tokens.push(piece)\n if (tokens.length >= MAX_SEARCH_TOKENS) break\n }\n return tokens\n}\n\n/**\n * Score one candidate tool; `0` means no match. The whole query as one\n * substring stays the strongest signal (an exact name beats a phrase that\n * happens to sit inside a description), and every query word then adds its\n * own hit — a word in the name outweighs the same word in the description.\n * The per-word tier is what keeps a natural query like \"issue get create\n * update\" useful: no tool contains that phrase, but the tools that contain\n * most of its words are exactly the ones the model meant.\n */\nfunction scoreTool(name: string, description: string, needle: string, tokens: readonly string[]): number {\n const lowerName = name.toLowerCase()\n if (lowerName === needle) return 1_000\n const lowerDescription = description.toLowerCase()\n let score = 0\n if (lowerName.includes(needle)) score += 500\n else if (lowerDescription.includes(needle)) score += 250\n for (const token of tokens) {\n if (lowerName.includes(token)) score += 10\n else if (lowerDescription.includes(token)) score += 1\n }\n return score\n}\n\n/** Code-unit name comparison, matching the canonical tool order of DSH. */\nfunction compareNames(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0\n}\n\n/** Serialize one canonical value for the model; total by construction. */\nfunction renderJson(value: unknown): string {\n const text = JSON.stringify(value, undefined, 2)\n return text === undefined ? String(value) : text\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n","/**\n * MCP document parsing for `dsh-project-mcp`.\n *\n * Reads Kimi Code / Claude-style documents (`{ \"mcpServers\": { ... } }`) and\n * converts every entry into an `@deepseek-ai/dsh-mcp-client` config. The module\n * is intentionally free of Cordis and of ambient process state: environment,\n * project dotenv values, plugin-level `inputs` and credential values are\n * injected through {@link ResolveContext}, so the whole conversion is\n * unit-testable.\n *\n * Error policy: a broken row never blocks the document. It becomes an entry\n * with `error` set, which the runtime surfaces as an `error` row.\n *\n * @module dsh-project-mcp/parse\n */\n\nimport { readFileSync } from 'node:fs'\nimport type { Config as McpClientConfig } from '@deepseek-ai/dsh-mcp-client'\n\n/**\n * `serverName` accepted by mcp-client; anything else cannot own a tool\n * namespace (`mcp__<serverName>__<rawName>`).\n */\nexport const SERVER_NAME_PATTERN = /^[A-Za-z0-9_-]{1,32}$/\n\n/** Whole-string `${NAME}` / `${input:NAME}` reference. */\nconst WHOLE_REF_PATTERN = /^\\$\\{(.+)\\}$/\n\n/** Any `${...}` reference inside a longer string. */\nconst INLINE_REF_PATTERN = /\\$\\{([^}]+)\\}/g\n\n/** The same grammar, read through `matchAll` where every reference is needed. */\nconst REFERENCE_PATTERN = /\\$\\{([^}]+)\\}/g\n\n/** Prefix selecting the interactive-input namespace of a reference. */\nconst INPUT_PREFIX = 'input:'\n\n/** Maximum length of a generated `serverName`. */\nconst MAX_SERVER_NAME_LENGTH = 32\n\n/** Severity of a parse diagnostic. */\nexport type IssueLevel = 'error' | 'warning'\n\n/** One diagnostic produced while reading a document. */\nexport interface ParseIssue {\n /** Absolute path of the document (or a pseudo-path for in-memory input). */\n source: string\n /** Server key the diagnostic belongs to, when it is entry-scoped. */\n server?: string\n /** Whether the entry is unusable (`error`) or merely notable (`warning`). */\n level: IssueLevel\n /** Human-readable description. */\n message: string\n /**\n * Stable wire code of `message` (`projectMcp.host` namespace), for\n * client-side translation. Additive: `message` keeps its byte-identical\n * English and stays the fallback, and behavioural matches key on this field\n * — never on the prose, which the client may have translated.\n */\n code?: string\n /** Flat params of {@link ParseIssue.code}, stringified at emission. */\n params?: Record<string, string>\n}\n\n/** One parsed `mcpServers` entry: exactly one of `config` / `error` is set. */\nexport interface ParsedEntry {\n /** Key in `mcpServers` (or the sanitized form of it). */\n name: string\n /** `false` only for an explicit `enabled: false` / `disabled: true`. */\n enabled: boolean\n /** Absolute path of the document the entry came from. */\n source: string\n /** mcp-client config, ready to mount. */\n config?: McpClientConfig\n /** Why the entry cannot be mounted. */\n error?: string\n /**\n * Stable wire code of `error` (`projectMcp.host` namespace) — the path by\n * which a parse failure becomes a translated `row.detail` on the client.\n */\n errorCode?: string\n /** Flat params of {@link ParsedEntry.errorCode}, stringified at emission. */\n errorParams?: Record<string, string>\n}\n\n/** External values needed to expand `${...}` references. */\nexport interface ResolveContext {\n /** Ambient environment (`process.env`). */\n env: Record<string, string | undefined>\n /** Project-local dotenv values (`<project>/.env`, then `<project>/.dsh/.env`). */\n dotenv: Record<string, string>\n /** Plugin-level `inputs` config: explicit `${input:NAME}` values. */\n inputs: Record<string, string>\n /** Values read from the DSH credentials file. */\n secrets: Record<string, string>\n /**\n * Identity of the three value sources above, so a caller that caches whole\n * parsed documents can tell \"the same values answered this parse\" from \"the\n * files moved\". Opaque here: the parser never reads it.\n */\n stamp?: string\n /** Project root used as the default `cwd` of stdio servers. */\n projectRoot: string\n /** Timeout applied to every generated config. */\n toolCallTimeoutMs: number\n /** Whether a failed initial connection should reject the mount. */\n failOnStartupError: boolean\n}\n\n/** Result of parsing one document. */\nexport interface ParsedDocument {\n /** Entries in document order. */\n entries: ParsedEntry[]\n /** Diagnostics for the document itself and for individual entries. */\n issues: ParseIssue[]\n /** `false` when the file could not be read or held no server map. */\n ok: boolean\n}\n\ntype Resolution =\n | { ok: true; value: string }\n | { ok: false; message: string; code: string; params?: Record<string, string> }\n\n/** Expand every `${...}` reference inside `value`. */\nexport function expandValue(value: string, ctx: ResolveContext): Resolution {\n const whole = WHOLE_REF_PATTERN.exec(value)\n if (whole !== null) return resolveRef(whole[1] as string, ctx)\n let failure: Extract<Resolution, { ok: false }> | undefined\n const replaced = value.replace(INLINE_REF_PATTERN, (match, ref: string) => {\n const resolved = resolveRef(ref, ctx)\n if (resolved.ok) return resolved.value\n failure ??= resolved\n return match\n })\n if (failure !== undefined) return failure\n return { ok: true, value: replaced }\n}\n\n/**\n * Whether `value` contains at least one `${...}` reference.\n *\n * A value written as a reference does not live in the declaring document, so\n * an editor is shown the key without it and a save keeps the declared text\n * instead of substituting the resolved value.\n * @param value - declared string value.\n * @returns `true` when the value carries a reference.\n */\nexport function hasReference(value: string): boolean {\n return /\\$\\{[^}]+\\}/.test(value)\n}\n\n/**\n * Whether any `${...}` reference of `value` is answered from outside the\n * process — by the project's `.env` or by the credentials file.\n *\n * Provenance only, mirroring {@link resolveRef}'s own fallback order (plugin\n * inputs, then the project dotenv values, then `process.env`, then credentials):\n * a value whose reference falls through to one of the two external maps is\n * marked `fromCredentials` in a snapshot — the flag the editor reads as \"do not\n * write the resolved value back\" — and stays as declared.\n * @param value - declared string value.\n * @param ctx - same resolve context the mount path uses.\n * @returns `true` when at least one reference was answered externally.\n */\nexport function referencesCredentials(value: string, ctx: ResolveContext): boolean {\n for (const match of value.matchAll(REFERENCE_PATTERN)) {\n const ref = match[1]?.trim() ?? ''\n const isInput = ref.startsWith(INPUT_PREFIX)\n const key = (isInput ? ref.slice(INPUT_PREFIX.length) : ref).trim()\n if (key === '') continue\n if (isInput && firstSet(ctx.inputs[key]) !== undefined) continue\n if (firstSet(ctx.dotenv[key]) !== undefined) return true\n if (firstSet(ctx.env[key]) !== undefined) continue\n if (firstSet(ctx.secrets[key]) !== undefined) return true\n }\n return false\n}\n\n/**\n * Resolve one `${...}` reference.\n *\n * `${input:NAME}` is answered by the plugin's own `inputs`, then by the same\n * chain a plain `${NAME}` uses, so a project can keep using the prefix its\n * `mcp.json` already carries. The chain is project-local first: the project's\n * dotenv documents, then the ambient environment, then the global credentials\n * file. An empty string counts as unset at every step.\n */\nfunction resolveRef(ref: string, ctx: ResolveContext): Resolution {\n const name = ref.trim()\n if (name.startsWith(INPUT_PREFIX)) {\n const key = name.slice(INPUT_PREFIX.length).trim()\n if (key === '') return { ok: false, message: 'empty ${input:} reference', code: 'parse.ref.empty' }\n const explicit = firstSet(ctx.inputs[key])\n if (explicit !== undefined) return { ok: true, value: explicit }\n const value = projectValue(ctx, key)\n if (value === undefined) {\n return {\n ok: false,\n message: `input \"${key}\" is not set (looked in plugin inputs, the project .env, the environment, and the credentials file)`,\n code: 'parse.ref.inputUnset',\n params: { key },\n }\n }\n return { ok: true, value }\n }\n const value = projectValue(ctx, name)\n if (value === undefined) {\n return {\n ok: false,\n message: `variable \"${name}\" is not set (looked in the project .env, the environment, and the credentials file)`,\n code: 'parse.ref.varUnset',\n params: { name },\n }\n }\n return { ok: true, value }\n}\n\n/** Project dotenv → ambient environment → credentials, for one key. */\nfunction projectValue(ctx: ResolveContext, key: string): string | undefined {\n return firstSet(ctx.dotenv[key], ctx.env[key], ctx.secrets[key])\n}\n\n/** The first non-empty value, or `undefined` when every source was unset. */\nfunction firstSet(...values: (string | undefined)[]): string | undefined {\n for (const value of values) {\n if (value !== undefined && value !== '') return value\n }\n return undefined\n}\n\n/** Sanitize an arbitrary `mcpServers` key into a valid `serverName`. */\nexport function slugifyServerName(name: string): string {\n const slug = name\n .replace(/[^A-Za-z0-9_-]+/g, '-')\n .replace(/^-+|-+$/g, '')\n return slug.slice(0, MAX_SERVER_NAME_LENGTH)\n}\n\n/**\n * Parse the text of one MCP document.\n * @param text - raw file content.\n * @param source - absolute path used for diagnostics and for entry `source`.\n * @param ctx - values used to expand references and to fill config defaults.\n * @returns parsed entries plus diagnostics; `ok` reports whether a server map was found.\n */\nexport function parseDocument(text: string, source: string, ctx: ResolveContext): ParsedDocument {\n const issues: ParseIssue[] = []\n let data: unknown\n try {\n data = JSON.parse(text) as unknown\n } catch (error) {\n return {\n entries: [],\n issues: [\n {\n source,\n level: 'error',\n message: `invalid JSON: ${errorText(error)}`,\n code: 'parse.json.invalid',\n params: { error: errorText(error) },\n },\n ],\n ok: false,\n }\n }\n const servers = extractServerMap(data)\n if (servers === null) {\n return {\n entries: [],\n issues: [\n {\n source,\n level: 'error',\n message: 'expected an object with an \"mcpServers\" object',\n code: 'parse.doc.notObject',\n },\n ],\n ok: false,\n }\n }\n const entries: ParsedEntry[] = []\n const seen = new Set<string>()\n for (const [key, raw] of Object.entries(servers)) {\n const name = sanitizeName(key, source, issues)\n if (name === undefined) continue\n if (seen.has(name)) {\n const message = `serverName \"${name}\" is declared twice in this document`\n const code = 'parse.server.duplicateName'\n const params = { name }\n issues.push({ source, server: name, level: 'error', message, code, params })\n entries.push({ name, enabled: false, source, error: message, errorCode: code, errorParams: params })\n continue\n }\n seen.add(name)\n entries.push(toEntry(name, raw, source, ctx, issues))\n }\n return { entries, issues, ok: true }\n}\n\n/** Read and parse one document; a missing file yields `undefined`. */\nexport function parseDocumentFile(path: string, ctx: ResolveContext): ParsedDocument | undefined {\n let text: string\n try {\n text = readFileSync(path, 'utf8')\n } catch {\n return undefined\n }\n return parseDocument(text, path, ctx)\n}\n\n/**\n * Extract a `name -> entry` map from a document: `mcpServers`, `servers`, or a\n * bare flat map whose values all look like server entries.\n * @param data - parsed document (or any JSON value).\n * @returns the server map, or `null` when the value holds none.\n */\nexport function extractServerMap(data: unknown): Record<string, unknown> | null {\n if (data === null || typeof data !== 'object' || Array.isArray(data)) return null\n const record = data as Record<string, unknown>\n for (const key of ['mcpServers', 'servers'] as const) {\n const container = record[key]\n if (container !== null && typeof container === 'object' && !Array.isArray(container)) {\n return container as Record<string, unknown>\n }\n }\n const values = Object.values(record)\n if (values.length === 0) return null\n const looksFlat = values.every(\n (value) => value !== null && typeof value === 'object' && !Array.isArray(value),\n )\n return looksFlat ? record : null\n}\n\n/**\n * Bring a `mcpServers` key into the `serverName` alphabet, or reject it when\n * nothing usable remains. A rename is a warning, not an error: the entry stays\n * mountable and only its tool namespace changes.\n */\nfunction sanitizeName(key: string, source: string, issues: ParseIssue[]): string | undefined {\n if (SERVER_NAME_PATTERN.test(key)) return key\n const slug = slugifyServerName(key)\n if (slug === '') {\n issues.push({\n source,\n server: key,\n level: 'error',\n message: `\"${key}\" cannot be converted into a valid serverName (${String(SERVER_NAME_PATTERN)})`,\n code: 'parse.server.badName',\n params: { key, pattern: String(SERVER_NAME_PATTERN) },\n })\n return undefined\n }\n issues.push({\n source,\n server: slug,\n level: 'warning',\n message: `serverName \"${key}\" is not a valid mcp-client name; using \"${slug}\"`,\n code: 'parse.server.renamedName',\n params: { key, slug },\n })\n return slug\n}\n\nfunction toEntry(\n name: string,\n raw: unknown,\n source: string,\n ctx: ResolveContext,\n issues: ParseIssue[],\n): ParsedEntry {\n if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {\n return fail(name, source, issues, 'entry must be an object', 'parse.entry.notObject')\n }\n const record = raw as Record<string, unknown>\n const enabled = record.enabled !== false && record.disabled !== true\n\n const declared = record.type ?? record.transport\n if (declared !== undefined && typeof declared !== 'string') {\n return fail(name, source, issues, '\"type\" must be a string', 'parse.entry.badType')\n }\n const normalized = declared === undefined ? undefined : declared.toLowerCase()\n if (\n normalized !== undefined\n && !['stdio', 'http', 'streamable-http', 'sse'].includes(normalized)\n ) {\n return fail(name, source, issues, '\"type\" must be one of \"stdio\", \"http\", \"streamable-http\" or \"sse\"', 'parse.entry.typeUnknown')\n }\n const hasUrl = record.url !== undefined\n const useHttp = normalized === undefined ? hasUrl : normalized !== 'stdio'\n return useHttp\n ? buildHttpEntry(name, record, source, ctx, issues, enabled)\n : buildStdioEntry(name, record, source, ctx, issues, enabled)\n}\n\nfunction buildStdioEntry(\n name: string,\n record: Record<string, unknown>,\n source: string,\n ctx: ResolveContext,\n issues: ParseIssue[],\n enabled: boolean,\n): ParsedEntry {\n const command = record.command\n if (typeof command !== 'string' || command === '') {\n return fail(name, source, issues, 'stdio servers require a \"command\"', 'parse.entry.noCommand')\n }\n const args = stringArray(record.args)\n if (args === undefined) return fail(name, source, issues, '\"args\" must be an array of strings', 'parse.entry.badArgs')\n const env = stringRecord(record.env)\n if (env === undefined) return fail(name, source, issues, '\"env\" must be an object of strings', 'parse.entry.badEnv')\n if (record.cwd !== undefined && typeof record.cwd !== 'string') {\n return fail(name, source, issues, '\"cwd\" must be a string', 'parse.entry.badCwd')\n }\n\n const expandedCommand = expandValue(command, ctx)\n if (!expandedCommand.ok) return fail(name, source, issues, expandedCommand.message, expandedCommand.code, expandedCommand.params)\n const expandedArgs = expandAll(args, ctx)\n if (!expandedArgs.ok) return fail(name, source, issues, expandedArgs.message, expandedArgs.code, expandedArgs.params)\n const expandedEnv = expandRecord(env, ctx)\n if (!expandedEnv.ok) return fail(name, source, issues, expandedEnv.message, expandedEnv.code, expandedEnv.params)\n const expandedCwd = expandValue(\n typeof record.cwd === 'string' && record.cwd !== '' ? record.cwd : ctx.projectRoot,\n ctx,\n )\n if (!expandedCwd.ok) return fail(name, source, issues, expandedCwd.message, expandedCwd.code, expandedCwd.params)\n\n return {\n name,\n enabled,\n source,\n config: {\n transport: 'stdio',\n serverName: name,\n command: expandedCommand.value,\n args: expandedArgs.value,\n env: expandedEnv.value,\n cwd: expandedCwd.value,\n toolCallTimeoutMs: ctx.toolCallTimeoutMs,\n failOnStartupError: ctx.failOnStartupError,\n },\n }\n}\n\nfunction buildHttpEntry(\n name: string,\n record: Record<string, unknown>,\n source: string,\n ctx: ResolveContext,\n issues: ParseIssue[],\n enabled: boolean,\n): ParsedEntry {\n const url = record.url\n if (typeof url !== 'string' || url === '') {\n return fail(name, source, issues, 'http servers require a \"url\"', 'parse.entry.noUrl')\n }\n const headers = stringRecord(record.headers)\n if (headers === undefined) {\n return fail(name, source, issues, '\"headers\" must be an object of strings', 'parse.entry.badHeaders')\n }\n const expandedUrl = expandValue(url, ctx)\n if (!expandedUrl.ok) return fail(name, source, issues, expandedUrl.message, expandedUrl.code, expandedUrl.params)\n const expandedHeaders = expandRecord(headers, ctx)\n if (!expandedHeaders.ok) return fail(name, source, issues, expandedHeaders.message, expandedHeaders.code, expandedHeaders.params)\n return {\n name,\n enabled,\n source,\n config: {\n transport: 'streamable-http',\n serverName: name,\n url: expandedUrl.value,\n headers: expandedHeaders.value,\n toolCallTimeoutMs: ctx.toolCallTimeoutMs,\n failOnStartupError: ctx.failOnStartupError,\n },\n }\n}\n\nfunction fail(\n name: string,\n source: string,\n issues: ParseIssue[],\n message: string,\n code: string,\n params?: Record<string, string>,\n): ParsedEntry {\n issues.push({\n source,\n server: name,\n level: 'error',\n message,\n code,\n ...(params === undefined ? {} : { params }),\n })\n return {\n name,\n enabled: false,\n source,\n error: message,\n errorCode: code,\n ...(params === undefined ? {} : { errorParams: params }),\n }\n}\n\nfunction expandAll(values: string[], ctx: ResolveContext): { ok: true; value: string[] } | Extract<Resolution, { ok: false }> {\n const result: string[] = []\n for (const value of values) {\n const expanded = expandValue(value, ctx)\n if (!expanded.ok) return expanded\n result.push(expanded.value)\n }\n return { ok: true, value: result }\n}\n\nfunction expandRecord(\n record: Record<string, string>,\n ctx: ResolveContext,\n): { ok: true; value: Record<string, string> } | Extract<Resolution, { ok: false }> {\n const result: Record<string, string> = {}\n for (const [key, value] of Object.entries(record)) {\n const expanded = expandValue(value, ctx)\n if (!expanded.ok) {\n return {\n ok: false,\n message: `${key}: ${expanded.message}`,\n // `{name}` deliberately carries the inner failure's English prose: the wrapper\n // covers three inner shapes (varUnset / inputUnset / empty ref) whose sentences\n // and params differ and collide with the flat `{key}` grammar, so no single\n // translated template can fill back byte-identically. Accepted partial\n // translation — F-48 ledger Ruling 4; only the wrapper punctuation localizes.\n code: 'parse.ref.failedInKey',\n params: { key, name: expanded.message },\n }\n }\n result[key] = expanded.value\n }\n return { ok: true, value: result }\n}\n\nfunction stringArray(value: unknown): string[] | undefined {\n if (value === undefined) return []\n if (!Array.isArray(value)) return undefined\n const result: string[] = []\n for (const item of value) {\n if (typeof item !== 'string') return undefined\n result.push(item)\n }\n return result\n}\n\nfunction stringRecord(value: unknown): Record<string, string> | undefined {\n if (value === undefined) return {}\n if (value === null || typeof value !== 'object' || Array.isArray(value)) return undefined\n const result: Record<string, string> = {}\n for (const [key, item] of Object.entries(value as Record<string, unknown>)) {\n if (typeof item !== 'string') return undefined\n result[key] = item\n }\n return result\n}\n\n/**\n * Merge per-document entry lists in priority order; a later document overrides\n * an earlier entry with the same `serverName`, keeping the position where that\n * name first appeared.\n * @param groups - entry lists from lowest to highest priority.\n * @returns merged entries plus the names that were overridden.\n */\nexport function mergeEntries(groups: ParsedEntry[][]): { entries: ParsedEntry[]; overridden: string[] } {\n const merged = new Map<string, ParsedEntry>()\n const overridden: string[] = []\n for (const group of groups) {\n for (const entry of group) {\n if (merged.has(entry.name)) overridden.push(entry.name)\n merged.set(entry.name, entry)\n }\n }\n return { entries: [...merged.values()], overridden }\n}\n\n/** Parse a YAML-ish credentials file into a flat string map. */\nexport function parseCredentials(text: string): Record<string, string> {\n const result: Record<string, string> = {}\n for (const line of text.split(/\\r?\\n/)) {\n const match = /^\\s*([A-Za-z_][A-Za-z0-9_]*)\\s*:\\s*(.*?)\\s*$/.exec(line)\n if (match === null) continue\n const value = (match[2] as string).replace(/^(['\"])(.*)\\1$/, '$2')\n if (value === '') continue\n result[match[1] as string] = value\n }\n return result\n}\n\n/**\n * Parse a dotenv document into a flat string map.\n *\n * The subset a project needs next to its `mcp.json`: one `KEY=value` per line,\n * an optional `export `, single or double quotes, and `#` comments — on their\n * own line, or after whitespace on a value line. Double quotes understand the\n * usual escapes (`\\n`, `\\r`, `\\t`, `\\\"`, `\\\\`); single quotes stay literal. An\n * empty value is skipped, exactly as {@link parseCredentials} skips one, so\n * `${NAME}` sees \"unset\" either way.\n * @param text - dotenv document contents.\n * @returns the values it declares, in first-wins order of the map.\n */\nexport function parseEnvFile(text: string): Record<string, string> {\n const result: Record<string, string> = {}\n for (const line of text.split(/\\r?\\n/)) {\n const match = /^\\s*(?:export\\s+)?([A-Za-z_][A-Za-z0-9_]*)\\s*=\\s*(.*?)\\s*$/.exec(line)\n if (match === null) continue\n const key = match[1] as string\n const value = unquoteEnvValue(match[2] as string)\n if (value === '') continue\n result[key] = value\n }\n return result\n}\n\n/** One dotenv value: unquoted (with an optional trailing comment), or quoted. */\nfunction unquoteEnvValue(raw: string): string {\n if (raw.startsWith('\"') && raw.endsWith('\"') && raw.length >= 2) {\n return raw\n .slice(1, -1)\n .replace(/\\\\n/g, '\\n')\n .replace(/\\\\r/g, '\\r')\n .replace(/\\\\t/g, '\\t')\n .replace(/\\\\\"/g, '\"')\n .replace(/\\\\\\\\/g, '\\\\')\n }\n if (raw.startsWith(\"'\") && raw.endsWith(\"'\") && raw.length >= 2) return raw.slice(1, -1)\n const comment = raw.indexOf(' #')\n return (comment === -1 ? raw : raw.slice(0, comment)).trim()\n}\n\nfunction errorText(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n","/**\n * Filesystem discovery for `dsh-project-mcp`: project root, config documents,\n * and the two credential sources behind `${...}` references — the global\n * credentials file and the project's own dotenv documents.\n *\n * Which MCP documents are read is a setting, not a constant: the deployment\n * lists its **local** documents (relative to a project root) and its **global**\n * ones (relative to `$HOME`, or absolute) in `localFiles` / `globalFiles`, and\n * one spec resolves through {@link expandConfigPath} to an absolute path.\n *\n * @module dsh-project-mcp/discovery\n */\n\nimport { existsSync, readFileSync, readdirSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { dirname, isAbsolute, join, resolve } from 'node:path'\nimport { parseCredentials, parseEnvFile } from './parse.ts'\n\n/** Directory/marker names that terminate the upward project-root walk. */\nexport const DEFAULT_PROJECT_MARKERS = ['.git', '.dsh', '.kimi-code', 'package.json']\n\n/** File-suffix markers that terminate the upward project-root walk. */\nexport const DEFAULT_FILE_MARKERS = ['.sln', '.slnx', '.csproj']\n\n/**\n * Project-relative documents read out of the box, in increasing priority: the\n * native DSH file only. A deployment that also wants another agent's document\n * names it in `localFiles`.\n */\nexport const DEFAULT_LOCAL_FILES: readonly string[] = ['.dsh/mcp.json']\n\n/**\n * Global documents read out of the box, in increasing priority: none. A global\n * document is read only when a deployment lists it in `globalFiles`, so a\n * project never inherits a server it did not ask for.\n */\nexport const DEFAULT_GLOBAL_FILES: readonly string[] = []\n\n/** `$DSH_HOME`, falling back to `~/.dsh`. */\nexport function dshHome(env: Record<string, string | undefined> = process.env): string {\n const configured = env.DSH_HOME\n return configured !== undefined && configured !== '' ? configured : join(homedir(), '.dsh')\n}\n\n/** Environment-variable references a path spec may carry. */\nconst HOME_REFERENCE = '~'\nconst DSH_HOME_REFERENCE = '$DSH_HOME'\nconst DSH_HOME_BRACED_REFERENCE = '${DSH_HOME}'\n\n/**\n * Resolve one configured document spec to an absolute path.\n *\n * A spec is read the way a shell reads it, in this order:\n *\n * - `~/x` (and a bare `~`) → `$HOME/x`;\n * - `$DSH_HOME/x` or `${DSH_HOME}/x` → the deployment's own home;\n * - an absolute path → itself;\n * - anything else → `base/x`, so a local document stays inside the project and\n * a global one stays inside `$HOME`.\n *\n * @param spec - one entry of `localFiles` or `globalFiles`.\n * @param base - directory a relative spec is read from.\n * @param env - environment used to resolve `$DSH_HOME`.\n * @returns the absolute document path.\n */\nexport function expandConfigPath(\n spec: string,\n base: string,\n env: Record<string, string | undefined> = process.env,\n): string {\n if (spec === HOME_REFERENCE) return homedir()\n if (spec.startsWith(`${HOME_REFERENCE}/`)) return resolve(homedir(), spec.slice(2))\n if (spec === DSH_HOME_REFERENCE || spec === DSH_HOME_BRACED_REFERENCE) return dshHome(env)\n if (spec.startsWith(`${DSH_HOME_REFERENCE}/`)) {\n return resolve(dshHome(env), spec.slice(DSH_HOME_REFERENCE.length + 1))\n }\n if (spec.startsWith(`${DSH_HOME_BRACED_REFERENCE}/`)) {\n return resolve(dshHome(env), spec.slice(DSH_HOME_BRACED_REFERENCE.length + 1))\n }\n if (isAbsolute(spec)) return resolve(spec)\n return resolve(base, spec)\n}\n\n/**\n * Project documents to read for one project root, in increasing priority — a\n * later document overrides an earlier entry of the same `serverName`.\n * @param projectRoot - absolute project root.\n * @param files - configured project-relative specs, lowest priority first.\n * @param env - environment used to resolve `$DSH_HOME`.\n * @returns absolute paths, lowest priority first.\n */\nexport function localConfigPaths(\n projectRoot: string,\n files: readonly string[] = DEFAULT_LOCAL_FILES,\n env: Record<string, string | undefined> = process.env,\n): string[] {\n return files.map((spec) => expandConfigPath(spec, projectRoot, env))\n}\n\n/**\n * Global documents of one deployment, in increasing priority. They are read\n * before a project's own documents, so a project declaration always wins.\n * @param files - configured specs, lowest priority first.\n * @param env - environment used to resolve `$DSH_HOME`.\n * @returns absolute paths, lowest priority first.\n */\nexport function globalConfigPaths(\n files: readonly string[] = DEFAULT_GLOBAL_FILES,\n env: Record<string, string | undefined> = process.env,\n): string[] {\n const home = homedir()\n return files.map((spec) => expandConfigPath(spec, home, env))\n}\n\n/** Default credentials document consulted for `${input:NAME}` values. */\nexport function defaultCredentialsPath(env: Record<string, string | undefined> = process.env): string {\n return join(dshHome(env), '.credentials.yaml')\n}\n\n/** Project-relative dotenv documents read for `${...}` values, lowest priority first. */\nexport const PROJECT_ENV_RELATIVE = ['.env', '.dsh/.env'] as const\n\n/**\n * Dotenv documents of one project, lowest priority first: the plain `.env` at\n * the project root, then the one in `.dsh` next to `mcp.json`. A value declared\n * in both is taken from the `.dsh` file — the project-local declaration wins.\n * @param projectRoot - absolute project root.\n * @returns absolute paths, lowest priority first.\n */\nexport function projectEnvPaths(projectRoot: string): string[] {\n return PROJECT_ENV_RELATIVE.map((relative) => join(projectRoot, relative))\n}\n\n/**\n * Walk upward from `cwd` to the first directory carrying a project marker.\n * @param cwd - absolute session working directory.\n * @param markers - directory/file marker names.\n * @param fileMarkers - file suffixes that also mark a project root.\n * @returns the absolute project root, or `undefined` when no marker is found.\n */\nexport function findProjectRoot(\n cwd: string,\n markers: readonly string[] = DEFAULT_PROJECT_MARKERS,\n fileMarkers: readonly string[] = DEFAULT_FILE_MARKERS,\n): string | undefined {\n let current = resolve(cwd)\n for (;;) {\n if (isProjectRoot(current, markers, fileMarkers)) return current\n const parent = dirname(current)\n if (parent === current) return undefined\n current = parent\n }\n}\n\nfunction isProjectRoot(\n dir: string,\n markers: readonly string[],\n fileMarkers: readonly string[],\n): boolean {\n for (const marker of markers) {\n if (existsSync(join(dir, marker))) return true\n }\n if (fileMarkers.length === 0) return false\n try {\n for (const entry of readdirSync(dir)) {\n if (fileMarkers.some((suffix) => entry.endsWith(suffix))) return true\n }\n } catch {\n return false\n }\n return false\n}\n\n/** Read the credentials document into a flat string map; missing file yields `{}`. */\nexport function readSecrets(path: string): Record<string, string> {\n try {\n return parseCredentials(readFileSync(path, 'utf8'))\n } catch {\n return {}\n }\n}\n\n/** Read one dotenv document into a flat string map; missing file yields `{}`. */\nexport function readEnvFile(path: string): Record<string, string> {\n try {\n return parseEnvFile(readFileSync(path, 'utf8'))\n } catch {\n return {}\n }\n}\n\n/**\n * Directories that hold this project's MCP documents. Used by the flat-watch\n * fallback when the runtime cannot watch a tree recursively.\n * @param projectRoot - absolute project root.\n * @param files - configured project-relative specs, lowest priority first.\n * @param env - environment used to resolve `$DSH_HOME`.\n * @returns existing directories, project root first, deduplicated.\n */\nexport function configDirectories(\n projectRoot: string,\n files: readonly string[] = DEFAULT_LOCAL_FILES,\n env: Record<string, string | undefined> = process.env,\n): string[] {\n const directories = [projectRoot]\n for (const path of localConfigPaths(projectRoot, files, env)) {\n const directory = dirname(path)\n if (!directories.includes(directory)) directories.push(directory)\n }\n return directories.filter((directory) => existsSync(directory))\n}\n","/**\n * Project-level MCP guidance for the session system prompt.\n *\n * A project can mount a large MCP surface, and with activation on (see\n * `./activation.ts`) most of its tools are not listed in a request at all: they\n * are offered on demand through `mcp_search_tools`. The per-server\n * `mcp:<server>` sections mcp-client publishes say what a server *is*, but\n * nothing tells the model that a tool it cannot see may still be asked for.\n *\n * This module contributes that one short section. {@link buildGuidance} is\n * pure: it turns a plain input object into markdown — or `''` when there is\n * nothing worth saying — with a hard length cap, a deterministic server order\n * and a deterministic truncated tool sample. {@link installGuidance} is the\n * thin scope wiring the runtime installs beside its mount and activation\n * wiring: it registers the section through `ctx.inject(['systemPrompt'], …)`\n * with a stable name whose code-unit order places it ahead of every per-server\n * block, and reads the project's live state at each assembly, so a rescan that\n * changes the mounted set changes the text without re-registering anything.\n *\n * The text never carries an absolute path, an endpoint or any other local\n * machine identifier: the project is named by its `~`-collapsed label\n * ({@link projectLabel}) and the input holds server names, states and tool\n * names only.\n *\n * Like `./activation.ts`, the module describes the prompt surface structurally\n * instead of importing `@deepseek-ai/dsh-system-prompt`: that peer is not\n * installed in every deployment, so the section and the injected scope are\n * declared by the minimal types below.\n *\n * @module dsh-project-mcp/guidance\n */\n\nimport { DEFAULT_ACTIVATION_ENABLED, SEARCH_TOOL_NAME } from './activation.ts'\nimport type { ServerStatus } from './types.ts'\n\n/** `true` unless a deployment turns the guidance section off. */\nexport const DEFAULT_GUIDANCE_ENABLED = true\n\n/**\n * Section name. At equal orders sections sort by code-unit name, and `-`\n * (0x2D) precedes `:` (0x3A), so this name — exactly like mcp-resources'\n * `mcp-resource-servers` — sorts ahead of every `mcp:<server>` instruction\n * block mcp-client publishes at the same order.\n */\nexport const GUIDANCE_SECTION_NAME = 'mcp-project-guidance'\n\n/** Hard cap on the section text; {@link buildGuidance} never returns more. */\nexport const MAX_GUIDANCE_CHARS = 1200\n\n/** Server bullets rendered at most, before the rest is summarized. */\nexport const MAX_GUIDANCE_SERVERS = 8\n\n/** Deferred tool names the on-demand inventory line shows before `+N more`. */\nexport const MAX_GUIDANCE_HIDDEN_NAMES = 12\n\n/** Baseline names the most-used line shows before `+N more`. */\nexport const MAX_GUIDANCE_MOST_USED = 4\n\n/** Longest purpose text kept in one server bullet. */\nexport const MAX_GUIDANCE_PURPOSE = 80\n\n/** One mounted server, as far as the guidance section describes it. */\nexport interface GuidanceServer {\n /** `serverName` of the mount. */\n readonly name: string\n /** Transport, when the mount has one. */\n readonly transport?: 'stdio' | 'streamable-http'\n /** Live mount state. */\n readonly status: ServerStatus\n /** Tool names the server currently publishes, in any order. */\n readonly tools?: readonly string[]\n /** Optional one-line purpose, shown after the server name. */\n readonly purpose?: string\n}\n\n/**\n * Plain input of {@link buildGuidance}. Every field is optional so a caller\n * that predates this feature (or a test) can pass a bare object; the defaults\n * describe \"no project, no servers\".\n */\nexport interface GuidanceInput {\n /** `~`-collapsed project label; defaults to `this project`. */\n readonly project?: string\n /** Mounted servers, in any order. */\n readonly servers?: readonly GuidanceServer[]\n /** Tool names offered directly in the request right now. */\n readonly offered?: readonly string[]\n /** Tool names reachable only through `mcp_search_tools` right now. */\n readonly deferred?: readonly string[]\n /**\n * The counter-seeded hot tools, most-called first. They are offered directly\n * from the first step on; naming them keeps the model from searching for\n * what it already has.\n */\n readonly mostUsed?: readonly string[]\n /** Whether the on-demand search surface is on; defaults to the activation default. */\n readonly activationEnabled?: boolean\n /**\n * Whether a deferred tool can still be called by its exact full name.\n *\n * It can on a route that accepts tool declarations after the first request:\n * the schema is hidden from the model and the registry keeps the tool\n * admitted, so `mcp__server__tool` executes. On a route without that\n * capability the tool is simply not declared, and a call by name answers\n * \"unknown tool\" — the names line must then send the model through the search\n * instead of promising the call. Defaults to `true`, the shipped capability.\n */\n readonly directCalls?: boolean\n}\n\n/**\n * Build the project-MCP guidance section.\n *\n * Deterministic and total: server bullets follow code-unit name order, the\n * deferred surface is listed as one flat, sorted, deduped names line, and the\n * result never exceeds {@link MAX_GUIDANCE_CHARS} — when it would, trailing\n * server bullets are replaced by an `and N more server(s)` line, the on-demand\n * paragraph and the names line are reserved their room first, and a final cut\n * falls back to the last complete line. Equal input always yields equal\n * output, and `''` means there is nothing worth saying.\n *\n * @param input - project label, mounted servers and the offered/deferred split.\n * @returns markdown for one prompt section, or `''`.\n */\nexport function buildGuidance(input: GuidanceInput): string {\n const servers = normalizeServers(input.servers ?? [])\n if (servers.length === 0) return ''\n const activationEnabled = input.activationEnabled ?? DEFAULT_ACTIVATION_ENABLED\n const offered = new Set(input.offered ?? [])\n // A tool that is already offered is never presented as on-demand, and with\n // activation off nothing is on demand at all.\n const deferred = new Set(\n activationEnabled ? (input.deferred ?? []).filter((name) => !offered.has(name)) : [],\n )\n const header = [\n '## Project MCP servers',\n '',\n `Project \\`${label(input.project)}\\` mounts ${servers.length} MCP server(s) in this session.`,\n '',\n ]\n const tail: string[] = []\n // The counter-seeded hot tools are offered from the first step on; naming\n // them here keeps the model from searching for what it already has.\n const hot = mostUsedLine(input.mostUsed ?? [])\n if (activationEnabled && hot !== '') tail.push('', hot)\n if (deferred.size > 0) {\n tail.push('', onDemandParagraph(offered.size, deferred.size))\n tail.push('', hiddenNamesLine(deferred, input.directCalls ?? true))\n }\n const bullets: string[] = []\n let hidden = 0\n for (const [index, server] of servers.entries()) {\n const remaining = servers.length - index\n const bullet = serverBullet(server)\n const overflow = remaining > 1 ? [`- … and ${remaining - 1} more server(s)`] : []\n const candidate = [...header, ...bullets, bullet, ...overflow, ...tail].join('\\n')\n if (index >= MAX_GUIDANCE_SERVERS || candidate.length > MAX_GUIDANCE_CHARS) {\n hidden = remaining\n break\n }\n bullets.push(bullet)\n }\n if (hidden > 0) bullets.push(`- … and ${hidden} more server(s)`)\n return applyCap([...header, ...bullets, ...tail].join('\\n'))\n}\n\n/**\n * `~`-collapsed display label for a project root.\n *\n * The session prompt must never carry an absolute path or a local machine\n * identifier, so the label is the home-relative form when the root lives under\n * `home` and the directory name otherwise. `home` is passed in rather than read\n * from the environment, which keeps the helper pure and testable.\n *\n * @param projectRoot - absolute project root, or any path-shaped string.\n * @param home - home directory to collapse to `~`, when known.\n * @returns a relative `~/…` label, the directory name, or `this project`.\n */\nexport function projectLabel(projectRoot: string, home?: string): string {\n const root = stripSeparators(projectRoot)\n if (root === '') return 'this project'\n if (home !== undefined) {\n const base = stripSeparators(home)\n if (base !== '') {\n if (root === base) return '~'\n if (root.startsWith(`${base}/`) || root.startsWith(`${base}\\\\`)) {\n return `~${root.slice(base.length)}`\n }\n }\n }\n const index = Math.max(root.lastIndexOf('/'), root.lastIndexOf('\\\\'))\n return index === -1 ? root : root.slice(index + 1)\n}\n\n/** The prompt-section fields this module registers (structural view). */\nexport interface GuidanceSectionLike {\n /** Unique section name. */\n readonly name: string\n /** Numeric sort order. */\n readonly order: number\n /** `false` preserves literal text; this section carries no variables. */\n readonly interpolate?: boolean\n /** Text, or a provider evaluated at each assembly. */\n readonly text: string | (() => string)\n}\n\n/** The `systemPrompt` slice the wiring reads (structural view). */\nexport interface GuidancePromptLike {\n /**\n * Register one ordered section in the calling scope.\n * @param section - the section to register.\n * @returns the registration's effect disposer.\n */\n section(section: GuidanceSectionLike): unknown\n /**\n * Resolve a centrally owned placement.\n * @param name - stable placement name.\n * @returns the numeric sort order.\n */\n getSectionOrder(name: 'MCP_SERVERS'): number\n}\n\n/** The injected scope carrying `systemPrompt`. */\nexport interface GuidancePromptScopeLike {\n /** The prompt registry. */\n readonly systemPrompt: GuidancePromptLike\n}\n\n/**\n * The agent-scoped context slice the guidance wiring touches. Described\n * structurally so the wiring is testable without a live harness.\n */\nexport interface GuidanceContextLike {\n /**\n * Start a callback once the injected services exist; the injected scope owns\n * what the callback registers.\n * @param deps - service names the callback requires.\n * @param callback - receives the injected scope.\n * @returns a disposer for the callback's own fiber, when the runtime gives one.\n */\n inject(deps: readonly string[], callback: (inner: GuidancePromptScopeLike) => unknown): unknown\n}\n\n/** Wiring options for {@link installGuidance}. */\nexport interface GuidanceWiringOptions {\n /** Agent-scoped context; the section lives here. */\n readonly ctx: GuidanceContextLike\n /** Live section text; called at every assembly, so it may read changing state. */\n readonly text: () => string\n /** Section name override; defaults to {@link GUIDANCE_SECTION_NAME}. */\n readonly name?: string\n /** Sink for a contained failure of this plugin's own work. */\n readonly onError?: (error: unknown) => void\n}\n\n/**\n * Register the guidance section on one agent scope.\n *\n * The section goes in through `ctx.inject(['systemPrompt'], …)`, so the scope\n * fiber owns it and a scope disposal unregisters it with the real registry.\n * The returned disposer is the explicit path for a host that publishes a plain\n * `systemPrompt` stub — the runtime keeps it and releases it exactly when it\n * releases the scope (idle release and agent disposal), so no section outlives\n * its mounts. It is idempotent.\n *\n * @param options - scope, live text provider and an optional failure sink.\n * @returns the disposer that unregisters everything installed here.\n */\nexport function installGuidance(options: GuidanceWiringOptions): () => void {\n const disposers: (() => void)[] = []\n const contain = (error: unknown): void => {\n options.onError?.(error)\n }\n try {\n const registered = options.ctx.inject(['systemPrompt'], (inner) => {\n const dispose = inner.systemPrompt.section({\n name: options.name ?? GUIDANCE_SECTION_NAME,\n order: inner.systemPrompt.getSectionOrder('MCP_SERVERS'),\n interpolate: false,\n text: options.text,\n })\n const release = disposerOf(dispose)\n if (release !== undefined) disposers.push(release)\n return dispose\n })\n const release = disposerOf(registered)\n if (release !== undefined) disposers.push(release)\n } catch (error) {\n contain(error)\n }\n return () => {\n // Newest first: the section registration is released before the injected\n // fiber that owns it. `splice` makes a second call a no-op.\n for (const dispose of disposers.splice(0).reverse()) {\n try {\n dispose()\n } catch (error) {\n contain(error)\n }\n }\n }\n}\n\n/** Dedupe by name, drop blank names and put the rest in code-unit name order. */\nfunction normalizeServers(servers: readonly GuidanceServer[]): GuidanceServer[] {\n const byName = new Map<string, GuidanceServer>()\n for (const server of servers) {\n const name = server.name.trim()\n if (name === '' || byName.has(name)) continue\n byName.set(name, { ...server, name })\n }\n return [...byName.values()].sort((left, right) => compareNames(left.name, right.name))\n}\n\n/** One server bullet: state and the optional purpose. */\nfunction serverBullet(server: GuidanceServer): string {\n const state =\n server.transport === undefined ? server.status : `${server.transport}, ${server.status}`\n const purpose = shorten(server.purpose, MAX_GUIDANCE_PURPOSE)\n return `- ${server.name} (${state})${purpose === '' ? '' : ` — ${purpose}`}`\n}\n\n/**\n * The flat inventory of the deferred surface: bare names only, sorted and\n * deduped, truncated to {@link MAX_GUIDANCE_HIDDEN_NAMES} with a `+N more`.\n * Descriptions and schemas are the expensive part, so the line carries names\n * only — the model picks the one it needs and runs a single targeted search\n * instead of rephrasing blind guesses.\n *\n * The tail sentence is the one place the route changes the advice. Where the\n * harness can declare a tool after the first request, deferral only trims the\n * request list — the tool stays registered, so a call by its exact full name\n * still executes and the search is how the model reads the description, not a\n * gate. Where it cannot, the tool is not declared at all: the name no longer\n * exists for the turn, and the model has to search first, so promising the\n * direct call there would send it into an \"unknown tool\" error.\n * @param deferred - names reachable only through the discovery tool right now.\n * @param directCalls - whether an exact-name call still executes (§\n * `GuidanceInput.directCalls`).\n * @returns one line, or an empty string when nothing is deferred.\n */\nfunction hiddenNamesLine(deferred: ReadonlySet<string>, directCalls: boolean): string {\n const names = [...deferred].sort(compareNames)\n const shown = names.slice(0, MAX_GUIDANCE_HIDDEN_NAMES)\n const hidden = names.length - shown.length\n const list = hidden === 0 ? shown.join(', ') : `${shown.join(', ')} +${hidden} more`\n if (!directCalls) {\n return (\n `On demand right now: ${list} — none of them is in this request, so ask for one with ` +\n `\\`${SEARCH_TOOL_NAME}\\` (a keyword or the name) and it becomes callable from the next ` +\n 'step on.'\n )\n }\n return (\n `On demand right now: ${list} — every one of them runs when called by its exact full ` +\n `name \\`mcp__<server>__<tool>\\`; search a name with \\`${SEARCH_TOOL_NAME}\\` first to see ` +\n 'its description and parameters.'\n )\n}\n\n/** The paragraph that turns \"a tool is missing\" into \"ask for it\". */\nfunction onDemandParagraph(offered: number, deferred: number): string {\n return (\n `${offered} of ${offered + deferred} MCP tool(s) are offered directly; the other ${deferred} ` +\n `are offered on demand — call \\`${SEARCH_TOOL_NAME}\\` with a keyword or a tool name (several ` +\n 'words are matched one by one), and a tool it activates becomes callable from the next ' +\n 'step. Search once with the best keywords you have; when the search reports no match, this ' +\n 'project mounts no such ' +\n 'tool — report the gap instead of rephrasing the search or guessing a name.'\n )\n}\n\n/**\n * The session-start \"most used\" line. The input arrives most-called first\n * (the seeded baseline's insertion order is the rank order), so the line\n * keeps that order and samples the top names before `+N more`.\n */\nfunction mostUsedLine(mostUsed: readonly string[]): string {\n const unique: string[] = []\n const seen = new Set<string>()\n for (const name of mostUsed) {\n const trimmed = name.trim()\n if (trimmed === '' || seen.has(trimmed)) continue\n seen.add(trimmed)\n unique.push(trimmed)\n }\n if (unique.length === 0) return ''\n const shown = unique.slice(0, MAX_GUIDANCE_MOST_USED)\n const hidden = unique.length - shown.length\n const list = hidden === 0 ? shown.join(', ') : `${shown.join(', ')} +${hidden} more`\n return (\n `Most used in this project's sessions, offered from the first step on: ${list} — ` +\n 'call them directly, no search needed.'\n )\n}\n\n/** Project label, or a neutral fallback for a blank/missing one. */\nfunction label(project: string | undefined): string {\n const value = project?.trim() ?? ''\n return value === '' ? 'this project' : value\n}\n\n/** Trim a purpose and bound it, so one server cannot crowd the section. */\nfunction shorten(text: string | undefined, max: number): string {\n const value = text?.trim() ?? ''\n if (value.length <= max) return value\n return `${value.slice(0, max - 1).replace(/\\s+$/, '')}…`\n}\n\n/** Final guard: cut at the last complete line and add an ellipsis. */\nfunction applyCap(text: string): string {\n if (text.length <= MAX_GUIDANCE_CHARS) return text\n const head = text.slice(0, MAX_GUIDANCE_CHARS - 1)\n const cut = head.lastIndexOf('\\n')\n const body = (cut === -1 ? head : head.slice(0, cut)).replace(/\\s+$/, '')\n return `${body}…`\n}\n\n/** Remove trailing path separators; a bare root collapses to an empty string. */\nfunction stripSeparators(path: string): string {\n return path.replace(/[\\\\/]+$/, '')\n}\n\nfunction compareNames(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0\n}\n\n/** Read a disposer from either a function or an object with `dispose()`. */\nfunction disposerOf(value: unknown): (() => void) | undefined {\n if (typeof value === 'function') return value as () => void\n if (typeof value === 'object' && value !== null) {\n const target = value as { dispose?: unknown }\n if (typeof target.dispose === 'function') {\n const dispose = target.dispose as () => void\n return () => {\n dispose.call(target)\n }\n }\n }\n return undefined\n}\n","/**\n * The local namespace of a project-declared MCP server.\n *\n * A profile-level `mcp-client` instance and a project document can declare the\n * same `serverName`. `dsh-mcp-client` reserves that name per scope, so only one\n * of them can mount — which is a lost server, not a bad declaration. This module\n * is the pure rule that gives the project's entry a second, local name instead\n * (`grafana-dev` → `p-grafana-dev`), so both toolsets stay in the model's hands\n * under names nobody has to guess at.\n *\n * The rule is a total function of the declared name, the prefix and the names\n * already taken, and it is the *only* place the alias is computed: the pass that\n * mounts the server, the row that reports it and the tool prefix the model sees\n * all read this answer, so they cannot drift apart.\n *\n * @module dsh-project-mcp/naming\n */\n\n/** The five characters a local prefix may carry, config or derived. */\nexport const MAX_LOCAL_PREFIX_LENGTH = 5\n\n/** The `serverName` cap `@deepseek-ai/dsh-mcp-client` enforces. */\nconst MAX_SERVER_NAME_LENGTH = 32\n\n/** A local prefix is a valid `serverName` head or it is nothing. */\nconst PREFIX_SHAPE = /^[A-Za-z0-9_-]+$/\n\n/**\n * Whether a value may serve as a local prefix.\n *\n * The routes and the loader schema both read an untrusted string, so the shape\n * is checked here rather than trusted: a prefix that carries a character\n * `serverName` does not allow would produce a server the registry rejects, and\n * an empty prefix is a request for the derived one, not an error.\n *\n * @param value - candidate prefix.\n * @returns `true` when it is empty or a valid prefix of at most five characters.\n */\nexport function isValidLocalPrefix(value: string): boolean {\n if (value === '') return true\n return value.length <= MAX_LOCAL_PREFIX_LENGTH && PREFIX_SHAPE.test(value)\n}\n\n/**\n * The prefix a project brings by itself: its own folder name.\n *\n * Used when the config names no prefix, so a conflict has an answer without a\n * setting. A folder that yields nothing usable — `/`, dots, digits only — has no\n * answer, and such a project keeps today's behaviour rather than a made-up name.\n *\n * @param projectRoot - absolute project root.\n * @returns up to five characters, or `undefined` when the folder yields none.\n */\nexport function deriveLocalPrefix(projectRoot: string): string | undefined {\n const folder = projectRoot.split(/[\\\\/]/).filter((part) => part !== '').pop()\n if (folder === undefined) return undefined\n const cleaned = folder\n .toLowerCase()\n .replace(/[^A-Za-z0-9_-]+/g, '-')\n // A `serverName` may not open with a digit, and neither may the prefix: a\n // folder `2fast-service` contributes `fast`, not `2fast`.\n .replace(/^[0-9]+-*/, '')\n .slice(0, MAX_LOCAL_PREFIX_LENGTH)\n // Trimmed after the cap as well, so a cut at a separator (`2fast-service`\n // capped to five) never leaves the trailing dash the cap exposed.\n .replace(/^-+|-+$/g, '')\n return cleaned || undefined\n}\n\n/**\n * The local name of one declaration: the prefix, then the declared name,\n * trimmed so the result fits the `serverName` cap.\n *\n * The declared name is what gets trimmed, never the prefix, because a truncated\n * prefix would collide across servers the user meant to tell apart.\n *\n * @param name - declared `serverName`.\n * @param prefix - local prefix, already known to be valid.\n * @returns a `serverName` of at most 32 characters.\n */\nexport function aliasOf(name: string, prefix: string): string {\n const head = `${prefix}-`\n return `${head}${name.slice(0, Math.max(1, MAX_SERVER_NAME_LENGTH - head.length))}`\n}\n\n/** One declaration considered for a local name. */\nexport interface ConflictNameInput {\n /** Declared `serverName`. */\n readonly name: string\n /** `true` when a live profile-level instance already owns that name. */\n readonly reserved: boolean\n}\n\n/** What {@link resolveConflictNames} is asked to name. */\nexport interface ResolveNamesInput {\n /** Every declaration of the project, in document order. */\n readonly entries: readonly ConflictNameInput[]\n /** Explicit local prefix; empty asks for the one derived from the project. */\n readonly prefix: string\n /** Project root, read only when `prefix` is empty. */\n readonly projectRoot?: string\n}\n\n/**\n * The local name of every declaration a profile-level instance shadows.\n *\n * Aliases are handed out in name order so the answer never depends on which\n * document was read first, and a candidate that is already owned — by another\n * declaration of this project, by the profile, or by an alias handed out a\n * moment ago — gets a numeric tail (`p-grafana-dev-2`) rather than stealing the\n * name. Names that conflict with nothing are absent from the map: the absence is\n * the honest answer \"this one mounts under the name it declared\".\n *\n * @param input - declarations, prefix and project root.\n * @returns declared name → local name, in name order; empty when nothing is shadowed.\n */\nexport function resolveConflictNames(input: ResolveNamesInput): Map<string, string> {\n const prefix = input.prefix !== '' ? input.prefix : deriveLocalPrefix(input.projectRoot ?? '')\n const aliases = new Map<string, string>()\n if (prefix === undefined || !isValidLocalPrefix(prefix) || prefix === '') return aliases\n const taken = new Set(input.entries.map((entry) => entry.name))\n const shadowed = input.entries.filter((entry) => entry.reserved).map((entry) => entry.name)\n // Sorted, so the numeric tail always lands on the same declaration.\n shadowed.sort()\n for (const name of shadowed) {\n let candidate = aliasOf(name, prefix)\n for (let tail = 2; taken.has(candidate); tail += 1) {\n candidate = aliasOf(`${name}-${tail}`, prefix)\n }\n taken.add(candidate)\n aliases.set(name, candidate)\n }\n return aliases\n}\n","/**\n * Durable per-project tool policy for `dsh-project-mcp`.\n *\n * The panel lets a user decide how one project's MCP tools are offered — never\n * defer (`direct`), do not offer them at all (`off`), or keep the shipped\n * on-demand presentation (`disclosure`) — and which tool names are pinned. That\n * decision is the same kind of state as the usage counters: remembered across\n * sessions and restarts in one versioned document under `$DSH_HOME`, written\n * atomically on a debounce, and never able to break a model request.\n *\n * The decision logic is pure ({@link policyFor}, {@link withMode},\n * {@link withPin}) and the document only sits behind {@link PolicyStore}, so the\n * model is testable without a filesystem. Absent file, absent project and absent\n * field all mean {@link DEFAULT_TOOL_POLICY}, so a broken or hand-edited\n * document can only ever fall back to the shipped behaviour.\n *\n * @module dsh-project-mcp/policy\n */\n\nimport { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { dshHome } from './discovery.ts'\nimport { DEFAULT_TOOL_POLICY } from './types.ts'\nimport type { ConflictChoice, ToolMode, ToolPolicy } from './types.ts'\n\n/** Current on-disk document version; another version is ignored, not migrated. */\nexport const POLICY_VERSION = 1\n\n/** Policy document name under `$DSH_HOME`, next to the usage counters. */\nexport const POLICY_FILE_NAME = 'dsh-project-mcp-policy.json'\n\n/** Every mode a request may store, in the order the type declares them. */\nexport const TOOL_MODES: readonly ToolMode[] = ['disclosure', 'direct', 'off']\n\n/** Policy of every project ever configured, keyed by project root. */\nexport type PolicyState = Record<string, ToolPolicy>\n\n/** The durable policy document as written to disk. */\nexport interface PolicyDocument {\n /** Document version; a reader that does not know it starts clean. */\n version: typeof POLICY_VERSION\n /** Policy of every project the user configured. */\n projects: PolicyState\n}\n\n/** The logger surface the store uses; a Cordis logger satisfies it. */\nexport interface PolicyLogger {\n /** Non-fatal report; the store never throws at its caller. */\n warn(message: string): void\n}\n\n/** Construction options for {@link PolicyStore}; production uses the defaults. */\nexport interface PolicyStoreOptions {\n /** Absolute document path; defaults to `$DSH_HOME/dsh-project-mcp-policy.json`. */\n file?: string\n /** Debounce before a policy change reaches disk. */\n flushMs?: number\n /** Sink for a corrupt document or a failed write. */\n logger?: PolicyLogger\n}\n\n/** Debounce that keeps a panel click off the filesystem. */\nconst DEFAULT_FLUSH_MS = 1_000\n\n/**\n * The shape `@deepseek-ai/dsh-mcp-client` accepts for a reserved `serverName`,\n * narrowed to a name that may open a stored conflict key: a key that fails it is\n * a hand-edit or an array index, and never a server this host could mount.\n */\nconst SERVER_NAME_SHAPE = /^[A-Za-z_][A-Za-z0-9_-]*$/\n\n/**\n * Whether a value is one of the modes this plugin stores.\n *\n * The routes read an untrusted JSON body, so the check belongs here rather than\n * in the type system: a body that names an unknown mode is refused instead of\n * being stored as a mode no assembly would know what to do with.\n *\n * @param value - parsed request or document value.\n * @returns `true` when the value is a {@link ToolMode}.\n */\nexport function isToolMode(value: unknown): value is ToolMode {\n return typeof value === 'string' && (TOOL_MODES as readonly string[]).includes(value)\n}\n\n/**\n * The policy in force for one project.\n *\n * Pure: it reads the state only. An absent project is the shipped default rather\n * than an error, which is what makes a fresh install behave exactly like the\n * plugin before this document existed.\n *\n * @param state - policies before the read.\n * @param projectRoot - project root the policy belongs to.\n * @returns the stored policy, or {@link DEFAULT_TOOL_POLICY} when there is none.\n */\nexport function policyFor(state: PolicyState, projectRoot: string): ToolPolicy {\n return state[projectRoot] ?? DEFAULT_TOOL_POLICY\n}\n\n/**\n * Whether a value is one of the conflict answers this plugin stores.\n *\n * Read from an untrusted route body and from a hand-edited document, so the\n * check lives here: a body that names an answer no build knows is refused\n * instead of stored.\n *\n * @param value - parsed request or document value.\n * @returns `true` when the value is a {@link ConflictChoice}.\n */\nexport function isConflictChoice(value: unknown): value is ConflictChoice {\n return value === 'profile' || value === 'local' || value === 'native'\n}\n\n/**\n * What the user chose for one contested `serverName`.\n *\n * Pure: the absence of a choice is the shipped answer — the profile's instance\n * keeps the name — so a project that never saw the toggle behaves exactly like\n * the plugin before the choice existed.\n *\n * @param state - policies before the read.\n * @param projectRoot - project root the name belongs to.\n * @param server - contested `serverName` as declared.\n * @returns the stored answer, or `'profile'` when there is none.\n */\nexport function choiceFor(state: PolicyState, projectRoot: string, server: string): ConflictChoice {\n return aliasesOf(state[projectRoot])[server] ?? 'profile'\n}\n\n/** The choices of one policy, treating an absent map and an empty one alike. */\nexport function aliasesOf(policy: ToolPolicy | undefined): Readonly<Record<string, ConflictChoice>> {\n return policy?.aliases ?? {}\n}\n\n/**\n * Store one contested name's answer, keeping the mode, the pins and the other\n * names.\n *\n * Pure and idempotent. Choosing the profile again *removes* the entry rather\n * than storing `'profile'`, because the absence already says exactly that: a\n * document that kept both spellings of one answer would grow with every click\n * and hand-edit its way into disagreeing with itself.\n *\n * @param state - policies before the change.\n * @param projectRoot - project root the name belongs to.\n * @param server - contested `serverName` as declared.\n * @param choice - the answer to store.\n * @returns a new state, or the input when the answer did not change.\n */\nexport function withConflictChoice(\n state: PolicyState,\n projectRoot: string,\n server: string,\n choice: ConflictChoice,\n): PolicyState {\n const current = policyFor(state, projectRoot)\n if (choiceFor(state, projectRoot, server) === choice) return state\n const aliases: Record<string, ConflictChoice> = { ...aliasesOf(current) }\n if (choice === 'profile') delete aliases[server]\n else aliases[server] = choice\n return { ...state, [projectRoot]: normalizePolicy(current.mode, current.pins, aliases) }\n}\n\n/**\n * Store one project's mode, keeping its pins.\n *\n * Pure and idempotent: storing the mode already in force returns the input state\n * unchanged, so a panel that resubmits a switch does not schedule a write.\n *\n * @param state - policies before the change.\n * @param projectRoot - project root the mode applies to.\n * @param mode - the mode to store.\n * @returns a new state, or the input when the mode did not change.\n */\nexport function withMode(state: PolicyState, projectRoot: string, mode: ToolMode): PolicyState {\n const current = policyFor(state, projectRoot)\n if (current.mode === mode) return state\n return { ...state, [projectRoot]: normalizePolicy(mode, current.pins, aliasesOf(current)) }\n}\n\n/**\n * Pin or unpin one name of one project.\n *\n * Pins keep the order the user pinned them in — a pin is appended, an unpin\n * removes exactly that name — because the panel lists them in that order and a\n * re-pin after an unpin must not silently jump to the front. A name is never\n * validated against the project's mounts here: a pin of a tool the project does\n * not mount yet is kept, so a declaration that comes back finds its pin again.\n *\n * @param state - policies before the change.\n * @param projectRoot - project root the pin belongs to.\n * @param tool - public registry name, eg `mcp__tglider__workspace`.\n * @param pinned - `true` pins it, `false` unpins it.\n * @returns a new state, or the input when the list did not change.\n */\nexport function withPin(\n state: PolicyState,\n projectRoot: string,\n tool: string,\n pinned: boolean,\n): PolicyState {\n const current = policyFor(state, projectRoot)\n const has = current.pins.includes(tool)\n if (pinned === has) return state\n const pins = pinned ? [...current.pins, tool] : current.pins.filter((name) => name !== tool)\n return { ...state, [projectRoot]: normalizePolicy(current.mode, pins, aliasesOf(current)) }\n}\n\n/**\n * One policy entry as the store keeps it: the mode and the pins always, the\n * choices only when there are any.\n *\n * Written through here rather than assembled field by field at each call site,\n * so the state the panel changes and the document that is flushed have one\n * shape — an entry that carries an empty map in memory but not on disk would be\n * a difference nothing could explain from the file.\n *\n * @param mode - mode in force.\n * @param pins - pinned names, in order.\n * @param aliases - choices per contested name.\n * @returns the entry to store.\n */\nfunction normalizePolicy(\n mode: ToolMode,\n pins: readonly string[],\n aliases: Readonly<Record<string, ConflictChoice>>,\n): ToolPolicy {\n return Object.keys(aliases).length === 0 ? { mode, pins } : { mode, pins, aliases }\n}\n\n/**\n * Parse one durable policy document.\n *\n * Anything this version cannot trust — malformed JSON, a foreign shape, or\n * another version — yields `undefined` so the caller starts from the shipped\n * default instead of throwing. A project entry is sanitized field by field: an\n * unknown mode falls back to `disclosure` and a pin list keeps only non-empty\n * deduplicated strings, so a hand-edited document cannot poison a request.\n *\n * @param text - raw document contents.\n * @returns the policies, or `undefined` when the document is not usable.\n */\nexport function parsePolicyDocument(text: string): PolicyState | undefined {\n let value: unknown\n try {\n value = JSON.parse(text)\n } catch {\n return undefined\n }\n if (!isRecord(value)) return undefined\n if (value.version !== POLICY_VERSION) return undefined\n if (!isRecord(value.projects)) return undefined\n const projects: PolicyState = {}\n for (const [root, raw] of Object.entries(value.projects)) {\n const policy = sanitizePolicy(raw)\n if (policy === undefined) continue\n // An entry that carries no mode, no pin and no choice says nothing the\n // default would not say, so it is dropped rather than written back.\n if (\n policy.mode === DEFAULT_TOOL_POLICY.mode &&\n policy.pins.length === 0 &&\n Object.keys(aliasesOf(policy)).length === 0\n ) {\n continue\n }\n projects[root] = policy\n }\n return projects\n}\n\n/**\n * The durable policy: one versioned document under `$DSH_HOME`, loaded once when\n * the plugin applies and written atomically on a debounce.\n *\n * Every failure mode is non-fatal by design, exactly like the counters. A\n * missing, unreadable, foreign or older-version document starts from the shipped\n * default, and a write that fails is logged and forgotten, because a panel click\n * must never fail on a policy that could not be stored.\n */\nexport class PolicyStore {\n private state: PolicyState\n private timer: ReturnType<typeof setTimeout> | undefined\n private dirty = false\n private disposed = false\n private readonly file: string\n private readonly flushMs: number\n private readonly logger: PolicyLogger | undefined\n\n /** @param options - document path, debounce and log sink. */\n constructor(options: PolicyStoreOptions = {}) {\n this.file = options.file ?? join(dshHome(), POLICY_FILE_NAME)\n this.flushMs = options.flushMs ?? DEFAULT_FLUSH_MS\n this.logger = options.logger\n this.state = this.load()\n }\n\n /** Policy of one project root; the shipped default when it has none. */\n forProject(projectRoot: string): ToolPolicy {\n return policyFor(this.state, projectRoot)\n }\n\n /** Store one project's mode and schedule the debounced write. */\n setMode(projectRoot: string, mode: ToolMode): ToolPolicy {\n this.commit(withMode(this.state, projectRoot, mode))\n return policyFor(this.state, projectRoot)\n }\n\n /** Pin or unpin one name of one project and schedule the debounced write. */\n setPin(projectRoot: string, tool: string, pinned: boolean): ToolPolicy {\n this.commit(withPin(this.state, projectRoot, tool, pinned))\n return policyFor(this.state, projectRoot)\n }\n\n /**\n * Store which of two conflicting declarations one name shows and schedule the\n * debounced write.\n *\n * Durable on purpose: the answer is what the user decided about their project,\n * not what one session happened to mount, so it survives the restart that\n * would otherwise bring the profile's instance back unopposed.\n */\n setConflictChoice(\n projectRoot: string,\n server: string,\n choice: ConflictChoice,\n ): ToolPolicy {\n this.commit(withConflictChoice(this.state, projectRoot, server, choice))\n return policyFor(this.state, projectRoot)\n }\n\n /** Write the policy atomically now. Best effort: it never throws. */\n flush(): void {\n if (!this.dirty) return\n const document: PolicyDocument = { version: POLICY_VERSION, projects: this.state }\n const temporary = `${this.file}.${process.pid}.tmp`\n try {\n mkdirSync(dirname(this.file), { recursive: true })\n writeFileSync(temporary, `${JSON.stringify(document, undefined, 2)}\\n`, 'utf8')\n renameSync(temporary, this.file)\n this.dirty = false\n } catch (error) {\n this.logger?.warn(\n `project-mcp: writing the tool policy to ${this.file} failed: ${errorText(error)}`,\n )\n }\n }\n\n /**\n * Cancel the pending write, flush what is dirty, and stop storing. Safe to\n * call more than once; the plugin fiber calls it on disposal.\n */\n dispose(): void {\n if (this.timer !== undefined) {\n clearTimeout(this.timer)\n this.timer = undefined\n }\n if (this.disposed) return\n this.disposed = true\n this.flush()\n }\n\n /** Adopt a state a pure change produced, and schedule the write when it moved. */\n private commit(next: PolicyState): void {\n if (this.disposed || next === this.state) return\n this.state = next\n this.dirty = true\n if (this.timer !== undefined) return\n this.timer = setTimeout(() => {\n this.timer = undefined\n this.flush()\n }, this.flushMs)\n this.timer.unref?.()\n }\n\n private load(): PolicyState {\n let text: string\n try {\n text = readFileSync(this.file, 'utf8')\n } catch {\n return {}\n }\n const state = parsePolicyDocument(text)\n if (state === undefined) {\n this.logger?.warn(\n `project-mcp: ignoring the tool policy in ${this.file} (unreadable or unsupported version); starting from the default`,\n )\n return {}\n }\n return state\n }\n}\n\n/** Sanitize one project entry; `undefined` when it is not even a record. */\nfunction sanitizePolicy(value: unknown): ToolPolicy | undefined {\n if (!isRecord(value)) return undefined\n const pins: string[] = []\n if (Array.isArray(value.pins)) {\n for (const pin of value.pins) {\n if (typeof pin !== 'string' || pin === '' || pins.includes(pin)) continue\n pins.push(pin)\n }\n }\n const aliases: Record<string, ConflictChoice> = {}\n if (isRecord(value.aliases)) {\n for (const [server, choice] of Object.entries(value.aliases)) {\n // The profile is what an absent entry means, so storing it would only\n // duplicate the default; an answer this build does not know is dropped.\n // A key that is no `serverName` at all — empty, or a bare index — is a\n // hand-edit or an array that JSON turned into an object, and is dropped\n // with the answer it carried.\n if (!SERVER_NAME_SHAPE.test(server) || !isConflictChoice(choice) || choice === 'profile') continue\n aliases[server] = choice\n }\n }\n return normalizePolicy(isToolMode(value.mode) ? value.mode : DEFAULT_TOOL_POLICY.mode, pins, aliases)\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction errorText(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n","/**\n * F-19 forwarding bridge: one `mcp-client` per project, a thin definition per\n * session.\n *\n * A preset composition mounts each session's tools from its own preset subtree,\n * and `agent-presets` binds every composed agent's scope key to the preset's\n * standing key *before* the agent is published. `dsh-scope` binds a key to one\n * parent exactly once, so the project's scope can never join that session's\n * chain — `bindScopeParent` throws, and the runtime's only remaining option was\n * to mount the same declarations again under the session's own scope: one child\n * process per session.\n *\n * The bridge takes the other path. The project keeps its one instance mounted in\n * the project's own scope; a session whose chain cannot reach that scope gets a\n * *forwarding* definition registered in its own layer instead. The forwarder\n * carries the project tool's model-facing surface, and each call resolves the\n * project's live definition by name and runs it:\n *\n * ```\n * project scope session scope (per session)\n * ┌────────────────────────┐ ┌──────────────────────────────────┐\n * │ mcp-client instance │ │ register(\"mcp__a__run\") ──────┐ │\n * │ register(\"mcp__a__run\")│◄────────┼── get(\"mcp__a__run\", project) │ │\n * │ execute(args, exec) │ │ → projectDefinition.execute │ │\n * └────────────────────────┘ └──────────────────────────────────┘\n * ```\n *\n * The resolution is by name at call time, not a captured definition object,\n * because `mcp-client` swaps its whole tool generation on every `tools/list`\n * refresh: a captured definition would keep executing a disposed generation.\n *\n * One session owns one live batch of forwarders, and {@link ForwardBatch} keeps\n * it level with the project's live set: the set is re-read on every trigger,\n * the batch is replaced as a whole (released before the replacement is\n * registered), and the re-entry every registration forces on the sync through\n * `tools/change` is owned rather than left to tear the batch down. Because that\n * event is emitted once per entry registered and once per entry disposed, the\n * subscription takes {@link ForwardBatch.note} — which folds a whole burst into\n * one queued pass — and never {@link ForwardBatch.sync}, whose work belongs to\n * the frame that asked for it.\n *\n * The module is import-free of `@deepseek-ai/dsh-tools` on purpose, exactly like\n * {@link ./activation.ts}: the registry, definition and schema surfaces are\n * described by the minimal structural types below, so the plugin stays\n * installable in a deployment that does not carry the tools package.\n *\n * @module dsh-project-mcp/bridge\n */\n\n/**\n * Minimal structural view of one model-facing content block.\n *\n * Deliberately open: every block the harness vocabulary carries has a `type` and\n * its own fields, so this is a supertype of all of them. That is what lets a\n * project definition typed against the real `ContentBlock` be copied into a\n * forwarder without a cast at the seam.\n */\nexport interface TextBlockLike {\n /** Block discriminant, eg `text`. */\n readonly type: string\n /** Every other block field, unread here. */\n readonly [key: string]: unknown\n}\n\n/**\n * Minimal structural view of one model-facing tool schema.\n *\n * It is the shape of `ctx.tools.schemas(scope)` entries, described locally\n * because `@deepseek-ai/dsh-tools` is a peer this plugin does not import.\n */\nexport interface BridgeToolSchema {\n /** Public registry name, eg `mcp__alpha__run`. */\n readonly name: string\n /** Model-facing description. */\n readonly description: string\n /** JSON Schema object arguments. */\n readonly parameters: Record<string, unknown>\n}\n\n/**\n * Minimal structural view of one registered tool definition.\n *\n * Every field except `execute` is carried over from the project's definition\n * verbatim — copied as a whole (`forwarder` spreads the definition), never by\n * enumerating the fields this module happens to know, so the forwarding entry is\n * indistinguishable from the original to everything that reads a definition:\n * schema projection, presentation metadata and callbacks, the concurrency\n * classifier, the timeout budget, the output renderer and the last-mile\n * `finalizeContent` the registry snapshots from the definition the session\n * resolves.\n */\nexport interface ForwardableDefinition extends BridgeToolSchema {\n /** Canonical output contract: schema plus model-facing renderer. */\n readonly output: {\n /** Enforced JSON Schema of the canonical value `execute` returns. */\n readonly schema: Record<string, unknown>\n /**\n * Project the canonical value onto model-facing content.\n * @param args - parsed call arguments.\n * @param value - the validated canonical value.\n * @returns the content blocks the model sees.\n */\n render(args: unknown, value: never): readonly TextBlockLike[]\n /**\n * Optional presentation projection, preserved so a call renders the same\n * card through either layer.\n * @param args - parsed call arguments.\n * @param value - the validated canonical value.\n * @returns the presentation metadata.\n */\n presentationMeta?(args: unknown, value: never): unknown\n }\n /** Cooperative timeout budget, preserved for the timeout policy wrapper. */\n readonly timeoutMs?: number\n /**\n * Deferred-loading request, owned by the presentation rather than by the\n * project.\n *\n * The harness projects this flag onto the model-facing schema\n * (`projectToolSchema`), and an adapter that understands it (the shipped\n * `dsh-llm-pi-ai` route omits such a schema from the wire request) then leaves\n * the definition out of the model's tool list while the registry keeps the\n * tool admitted for dispatch — a tool the model does not see but can still\n * call by its exact full name. It is set on the forwarder, never copied from\n * the project, because which of a session's tools are offered is this plugin's\n * presentation decision.\n */\n readonly deferLoading?: true\n /**\n * Pure sibling-overlap classifier. Preserved: a forwarder that dropped it\n * would make every forwarded call exclusive while the project tool is\n * parallel-safe.\n * @param args - parsed call arguments.\n * @returns whether this call may join a parallel group.\n */\n isConcurrencySafe?(args: unknown): boolean\n /**\n * Last-mile transform of the model-facing content, preserved.\n *\n * The registry snapshots this from the definition the *session* resolves —\n * which is the forwarder, not the project's entry — and calls it once per\n * normalized outcome. A forwarder that dropped it would silently degrade\n * every provider result that relies on it: an MCP result's stored images, for\n * one, would arrive as the adapter's plain text fallback.\n * @param exec - the execution identity, passed through unchanged.\n * @param result - the normalized outcome before materialization.\n * @returns replacement content, or `undefined` to preserve the current one.\n */\n finalizeContent?(exec: unknown, result: unknown): readonly TextBlockLike[] | undefined\n /**\n * Pending-state presentation, preserved so a forwarded call renders the same\n * card as the project's own entry.\n * @param args - parsed call arguments.\n * @returns the presentation intent, or `undefined` for the generic card.\n */\n presentCall?(args: unknown): unknown\n /**\n * Completed-state presentation, preserved for the same reason.\n * @param args - parsed call arguments.\n * @param result - the durable result projection.\n * @returns the presentation intent, or `undefined` to keep the pending one.\n */\n presentResult?(args: unknown, result: unknown): unknown\n /**\n * Run one accepted call.\n * @param args - parsed call arguments.\n * @param exec - execution identity, cancellation, and context deferral.\n * @returns the canonical value declared by `output.schema`.\n */\n execute(args: unknown, exec: never): Promise<unknown>\n}\n\n/**\n * The registry surface the bridge reads: one scoped lookup and one scoped\n * schema probe.\n *\n * `get(name, scope)` is the registry's public lookup and `schemas(scope)` its\n * public schema projection (`@deepseek-ai/dsh-tools` `ToolRuntime`); passing the\n * project's scope key reads the project's own layer and its ancestors, which is\n * where the shared instance registered its tools.\n */\nexport interface BridgeRegistryLike {\n /**\n * Resolve one tool as one scope sees it.\n * @param name - registered tool name.\n * @param scope - viewing scope key; omitted reads the global view.\n * @returns the visible definition, or `undefined` when none is.\n */\n get(name: string, scope?: object): ForwardableDefinition | undefined\n /**\n * Project one scope's visible definitions onto their model-facing schemas.\n * @param scope - viewing scope key; omitted reads the global view.\n * @returns one schema per visible tool, in registry order.\n */\n schemas(scope?: object): readonly BridgeToolSchema[]\n}\n\n/**\n * The registration context slices the bridge touches.\n *\n * A session's scope context is passed in, so `register` files every entry into\n * that session's own layer — the one layer this session owns, where the name is\n * visible to itself and to nobody else.\n */\nexport interface BridgeContextLike {\n /** Resolve one service, the injection-free read the plugin already uses. */\n get(name: string): unknown\n}\n\n/** Options for {@link forwardProjectTools}. */\nexport interface ForwardProjectToolsOptions {\n /** Session-scope context; every forwarder is registered through it. */\n readonly ctx: BridgeContextLike\n /** Project scope key whose definitions are executed. */\n readonly project: object\n /** Names to forward, as {@link projectToolNames} resolved them. */\n readonly names: readonly string[]\n /**\n * Names this pass forwards as deferred, so their schemas stay out of the\n * model's tool list while the registry keeps them callable. Absent defers\n * none, which is what a session with nothing hidden gets.\n * @param name - one forwarded name.\n * @returns whether the forwarder of that name carries `deferLoading`.\n */\n readonly deferred?: (name: string) => boolean\n /** Registry lookup used to resolve the live project definition per call. */\n readonly registry: BridgeRegistryLike\n}\n\n/**\n * Marker a forwarder carries, naming the definition it delegates to.\n *\n * The harness's registry has no \"forwarded\" concept and needs none — this is\n * addressed only to a test double standing in for the registry, which must tell\n * a forwarder from one of the session's own tools to resolve a call the way the\n * registry would.\n */\nexport const FORWARDED_TO = Symbol('dsh-project-mcp.forwarded-to')\n\n/**\n * Build one forwarding definition over a project's live definition.\n *\n * The schema fields are copied once, at registration time; the executable\n * delegate is resolved per call, so a project re-sync (which disposes and\n * re-registers every tool) never leaves a forwarder pointing at a dead\n * generation. Calling the project's definition directly — rather than\n * dispatching through the registry — is deliberate: the outer call already\n * traversed the policy pipeline under this session's identity, and a second\n * dispatch would apply pre-execute listeners and guards twice.\n * @param project - the definition to forward, read for its surface.\n * @param lookup - resolves the current project definition of this name.\n * @param deferred - whether this forwarder asks for deferred loading, so the\n * model's tool list leaves it out while the registry keeps it callable.\n * @returns the definition to register in a session's layer.\n */\nfunction forwarder(\n project: ForwardableDefinition,\n lookup: () => ForwardableDefinition | undefined,\n deferred: boolean,\n): ForwardableDefinition {\n // The marker rides outside the definition's own surface: it is addressed to a\n // test double standing in for the registry, never to the harness.\n return Object.assign(\n {\n // Every field the project declared rides along verbatim, including the\n // ones this module never reads — `finalizeContent`, `presentCall`,\n // `presentResult`, and whatever a future provider adds. Enumerating them\n // is what silently lost `dsh-mcp-client`'s finalizer: the registry takes\n // it from the definition the session resolves, which is this one.\n ...project,\n // After the spread, because the presentation decides this flag and the\n // project has no say in it. A forwarder that is not deferred carries no\n // flag at all rather than `deferLoading: false`, which is not part of the\n // harness's schema vocabulary.\n ...deferred ? { deferLoading: true as const } : {},\n async execute(args: unknown, exec: never): Promise<unknown> {\n const live = lookup()\n if (live === undefined) {\n throw new Error(`the project's \"${project.name}\" is no longer registered; the shared instance was released or replaced`)\n }\n return await live.execute(args, exec)\n },\n },\n { [FORWARDED_TO]: project },\n )\n}\n\n/**\n * Register one thin definition per name in the session's layer.\n *\n * A name the session already resolves to a definition of its own is skipped:\n * registering over it would either shadow the session's registration (if the\n * session's own layer holds it) or throw on a duplicate, and either way the\n * session's own tool is the one it should call.\n * @param options - session context, project key, names, and registry lookup.\n * @returns the exact releaser that drops every forwarder this call added.\n */\nexport function forwardProjectTools(options: ForwardProjectToolsOptions): () => void {\n // `ctx.get(name)` rather than `ctx.tools`: the session's scope context is a\n // raw extended context (the runtime mints it with `createScope`, not with a\n // plugin that injects `tools`), and a dot-read there throws\n // `cannot get property \"tools\" without inject`.\n const tools = options.ctx.get('tools') as {\n register(definition: ForwardableDefinition): () => void\n }\n const disposes: (() => void)[] = []\n for (const name of options.names) {\n const project = options.registry.get(name, options.project)\n if (project === undefined) continue\n try {\n disposes.push(tools.register(forwarder(\n project,\n () => options.registry.get(name, options.project),\n options.deferred?.(name) === true,\n )))\n } catch {\n // A duplicate in this session's own layer is the session's own tool: it\n // keeps the name, and the bridge steps aside rather than failing a mount.\n continue\n }\n }\n let released = false\n return () => {\n if (released) return\n released = true\n for (const dispose of disposes.reverse()) {\n try {\n dispose()\n } catch {\n // Disposal is idempotent at the registry, and a failure here must not\n // keep the remaining forwarders registered.\n }\n }\n }\n}\n\n/**\n * The names to forward, and how to register one batch of them.\n *\n * Both are read fresh on every pass: `names` because a server publishing a late\n * `tools/list` (or dropping one) is the ordinary life of a project, and\n * `register` because a pass can be requested from inside a pass.\n */\nexport interface ForwardBatchOptions {\n /**\n * The project's live tool names, probed on every pass.\n *\n * `undefined` reports a probe that failed: it says nothing about what the\n * project publishes, so the batch it could not describe is the batch that\n * stays live.\n * @returns the names this session should forward, or `undefined` on failure.\n */\n readonly names: () => readonly string[] | undefined\n /**\n * The names this session presents as deferred — hidden from the model's tool\n * list while the registry keeps them callable — read once on every pass.\n *\n * A pass whose names matched but whose deferred set moved still re-registers:\n * `deferLoading` is baked into the definition at registration, so the flag a\n * schema carries is exactly the flag its forwarder was registered with.\n * Absent defers none, which is the presentation of a session with nothing\n * hidden.\n * @returns the deferred names, or none.\n */\n readonly deferred?: () => readonly string[]\n /**\n * Register one batch of forwarders over the session's layer, which this call\n * reaches empty-handed: the batch it replaces is released first.\n * @param names - the names to forward, in registry order.\n * @param deferred - the names of this batch that carry `deferLoading`.\n * @returns the exact releaser that drops the whole batch.\n */\n readonly register: (names: readonly string[], deferred: ReadonlySet<string>) => () => void\n /**\n * Report a failure thrown by a pass this batch ran on its own.\n *\n * A pass requested by {@link ForwardBatch.note} runs off the caller's stack:\n * the registry call that announced the change has already returned, and so\n * has every frame that could have propagated the failure. Without this the\n * batch would go quiet — no forwarder, and no trace of why.\n * @param error - what the scheduled pass threw.\n */\n readonly onError?: (error: unknown) => void\n}\n\n/**\n * How many synchronous passes one {@link ForwardBatch.sync} may run.\n *\n * Two is the ordinary ceiling: a pass that replaced the batch is re-entered once\n * by its own announcements and short-circuits on the second round, and a pass\n * that found the set unchanged exits on the first. The extra room is for a set\n * that genuinely moved while the batch was registering — and the ceiling itself\n * is what stops a registry that keeps moving under the batch from holding the\n * event loop for as long as it likes.\n */\nexport const MAX_SYNC_PASSES = 4\n\n/**\n * One session's live forwarding batch, kept level with the project's live tools.\n *\n * The registry announces every registration by emitting `tools/change`\n * synchronously from inside the insertion, and a bridged session is subscribed\n * to exactly that event (`src/runtime.ts`, `installBridge`). A pass therefore\n * re-enters itself once per forwarder it registers. Nothing else owns that\n * re-entry, and left unowned it tears the batch down: the nested pass finds a\n * batch still being built, releases it, and registers a second copy of it —\n * which the live first copy refuses as a duplicate. A bridge that steps aside\n * for a duplicate (it must, for the session's own tools) then drops those names\n * silently, and a full pass records `namesIn` as the whole set, so the loss is\n * frozen for every later pass. That is the first defect this class exists to\n * close.\n *\n * So: a pass requested from inside a pass only marks the batch dirty, and the\n * frame that owns the batch runs one more pass when it is complete — which is\n * also how a project set that changed mid-registration is still honoured. And\n * the old batch is released **before** the new one is registered, because one\n * layer holds one entry per name: registering over a live batch would refuse\n * every name it already had.\n *\n * Owning the re-entry is not enough on its own, and the shape of the event is\n * why. Replacing a batch of N entries announces 2·N changes — one per disposal\n * and one per registration — and the event carries no origin, so every session\n * watching the stream runs a pass for every one of them, and every pass begins\n * by projecting the project's whole catalog, which the registry answers by deep\n * cloning each visible definition's JSON schema. The registry per pass is what\n * makes that cost real: one MCP generation swap was measured holding the event\n * loop for the full 54 seconds of a CPU profile (47% of its samples inside this\n * sync, 52% in the collector the projections feed), while the plugin's own\n * frames were 0.46% of it. So {@link note} is the seat a `tools/change`\n * subscription takes, not {@link sync}: a change that arrives during a pass is\n * absorbed by it, and a burst that arrives between passes costs **one** queued\n * pass however many events it carries. A stale forwarder is safe in the window\n * that opens — it resolves the project entry at call time and fails closed when\n * there is none (`forwarder`) — and every read path brings the batch level\n * before it reads, so a reader never waits for the queue.\n */\nexport class ForwardBatch {\n /** The names the live batch was registered for; `undefined` before the first pass. */\n #namesIn: readonly string[] | undefined = undefined\n /** The names the live batch registered as deferred; `undefined` with no live batch. */\n #deferredIn: ReadonlySet<string> | undefined = undefined\n /** Disposer of the live registration batch; `undefined` while none is live. */\n #release: (() => void) | undefined = undefined\n /** Whether an owning frame is inside {@link sync}, registering right now. */\n #building = false\n /** Whether a pass asked for while {@link #building} still needs a run. */\n #again = false\n /** Whether a scheduled pass is already waiting for a burst of changes. */\n #queued = false\n\n constructor(private readonly options: ForwardBatchOptions) {}\n\n /**\n * The names the live batch was registered for.\n *\n * `undefined` before the first successful pass, and again after a pass whose\n * registration failed: an unset state is what makes the next pass retry\n * rather than short-circuit on a set that never landed.\n */\n get namesIn(): readonly string[] | undefined {\n return this.#namesIn\n }\n\n /**\n * Bring the session's layer level with the project's live tool set, now.\n *\n * Cheap when it already is: an unchanged set short-circuits and leaves the\n * live batch — and its generation of definitions — untouched. Re-entrant\n * while registering, and bounded to {@link MAX_SYNC_PASSES} synchronous\n * rounds so no registry state can hold the caller's frame: see the class note.\n * @returns nothing; a failure from the probe or the registry propagates.\n */\n sync(): void {\n if (this.#building) {\n this.#again = true\n return\n }\n // A queued pass would read the very registry this one is about to read, so\n // it is dropped here rather than left to repeat the probe.\n this.#queued = false\n this.#building = true\n try {\n for (let pass = 0; pass < MAX_SYNC_PASSES; pass += 1) {\n this.#again = false\n this.#syncOnce()\n if (!this.#again) return\n }\n // Still moving after a full round: hand the rest to the queue. A registry\n // that keeps changing under the batch must not hold the caller's frame.\n this.#schedule(true)\n } finally {\n this.#building = false\n }\n }\n\n /**\n * Note that the registry changed, and bring the batch level — off this stack.\n *\n * This is the seat a `tools/change` subscription takes, and the reason it is\n * not {@link sync}: the event is emitted once per entry registered and once\n * per entry disposed, from inside the registry's own insertion and removal,\n * so one MCP generation swap is a burst of thousands. A change that arrives\n * while a pass is running is absorbed by that pass — it re-reads the set it is\n * replacing before it returns — and a burst that arrives between passes costs\n * one pass: the first queues, every later one folds into it.\n *\n * Nothing reads a stale layer for it. Every read path brings the batch level\n * first (`src/runtime.ts`, `mountedSchemas`), and the queued pass has run\n * before any turn that could read the layer at all.\n */\n note(): void {\n if (this.#building) {\n this.#again = true\n return\n }\n this.#schedule(false)\n }\n\n /**\n * Drop the live batch: the session keeps no forwarder, and the next\n * {@link sync} starts from nothing rather than amending a stale set.\n * Idempotent.\n *\n * The release announces itself (`tools/change`) once per entry, and the\n * session is subscribed to that event; a pass re-entered from there must not\n * resurrect the batch it is watching being dropped. So the guard is held for\n * the whole release, and the pass it queues is discarded rather than run.\n *\n * The guard is *held*, not taken: a drop that runs inside a pass — a detach\n * driven from a listener, a scope torn down under a registration — restores\n * the pass's own `building` rather than clearing it. Clearing it there would\n * let the next `tools/change` start a nested pass inside a frame that still\n * owns one, which is exactly the re-entry this class exists to own.\n */\n drop(): void {\n const building = this.#building\n this.#building = true\n try {\n this.#releaseBatch()\n } finally {\n this.#building = building\n this.#again = false\n this.#queued = false\n }\n }\n\n /**\n * Queue the one deferred pass a burst of changes needs.\n * @param yielding - run it on the timer queue rather than the microtask queue.\n * A pass that overran {@link MAX_SYNC_PASSES} asks for this: a chain of\n * microtasks still starves timers and I/O, a round of timers does not.\n */\n #schedule(yielding: boolean): void {\n if (this.#queued) return\n this.#queued = true\n const run = (): void => {\n if (!this.#queued) return\n this.#queued = false\n try {\n this.sync()\n } catch (error) {\n this.options.onError?.(error)\n }\n }\n if (yielding) setTimeout(run, 0)\n else queueMicrotask(run)\n }\n\n /** One pass: read the project's set, then replace the batch when it moved. */\n #syncOnce(): void {\n const names = this.options.names()\n if (names === undefined) return\n // A name that enters or leaves the deferred set is a definition change even\n // when the name set itself is identical: the flag is part of the schema the\n // registry projects, so a batch registered before the flip would keep\n // presenting the old answer for every later request.\n const deferred = new Set(this.options.deferred?.() ?? [])\n if (this.#namesIn !== undefined\n && sameNames(this.#namesIn, names)\n && sameNameSet(this.#deferredIn, deferred)) return\n // Released first, and deliberately — see the class note. Until the new batch\n // is registered the session's layer is empty for the length of one\n // synchronous call, which is the price of every forwarded name being free.\n try {\n this.#releaseBatch()\n } catch {\n // The registry's disposer is exact and idempotent, and a failure here must\n // not keep the new batch from registering.\n }\n this.#release = this.options.register(names, deferred)\n this.#namesIn = names\n this.#deferredIn = deferred\n }\n\n /**\n * Release the live batch and forget it.\n *\n * The fields are cleared before the disposer runs, so a throw leaves the batch\n * in the retryable empty state rather than half-released and half-claimed.\n */\n #releaseBatch(): void {\n const release = this.#release\n this.#release = undefined\n this.#namesIn = undefined\n this.#deferredIn = undefined\n release?.()\n }\n}\n\n/**\n * The project scope's tool names, restricted to the servers the project\n * actually mounted.\n *\n * The probe reads the PROJECT scope, not the session's: the shared instance\n * registered its tools there, so a session's own view would also carry its own\n * registrations (and could not tell them apart). `servers` keeps a name another\n * scope's server happens to publish from being forwarded.\n * @param project - project scope key whose view is probed.\n * @param schemas - reads one scope's visible schemas, as `ctx.tools.schemas`.\n * @param servers - server namespaces the project mounted.\n * @returns the tool names to forward, in registry order.\n */\nexport function projectToolNames(\n project: object,\n schemas: (scope: object) => readonly BridgeToolSchema[],\n servers: ReadonlySet<string>,\n): string[] {\n const names: string[] = []\n for (const schema of schemas(project)) {\n const match = /^mcp__([A-Za-z0-9_-]+?)__/.exec(schema.name)\n if (match === null) continue\n if (!servers.has(match[1] as string)) continue\n names.push(schema.name)\n }\n return names\n}\n\n/**\n * Whether two name lists are the same set in the same order.\n *\n * A sync is skipped when the project publishes exactly what the last one\n * forwarded: re-registering an unchanged batch would dispose and rebuild every\n * forwarder for nothing, and the registry announces each change to every\n * watcher.\n * @param left - the names the last sync forwarded.\n * @param right - the names this sync found.\n * @returns whether the two lists match entry for entry.\n */\nexport function sameNames(left: readonly string[], right: readonly string[]): boolean {\n return left.length === right.length && left.every((name, index) => name === right[index])\n}\n\n/**\n * Whether two deferred-name sets are the same set.\n *\n * The batch short-circuits a pass whose forwarded names did not move, and it\n * must not do that when the *deferred* subset moved instead: the flag rides in\n * the registered definition, so a stale batch presents a stale answer. Order\n * carries no meaning here, hence a set comparison rather than {@link sameNames}.\n * @param left - the deferred set of the live batch; `undefined` with no live batch.\n * @param right - the deferred set this pass read.\n * @returns whether the two describe the same names.\n */\nexport function sameNameSet(\n left: ReadonlySet<string> | undefined,\n right: ReadonlySet<string>,\n): boolean {\n if (left === undefined || left.size !== right.size) return false\n for (const name of right) if (!left.has(name)) return false\n return true\n}\n","/**\n * The plugin's own event ring, and its only owner.\n *\n * The Logs tab of the sidebar panel answers \"what happened to this project's\n * servers\" from the plugin's own lifecycle events — mounting, `is up`, stall,\n * unmount, failure — and from nothing else. The DSH log is deliberately not a\n * source: no foreign line can be attributed to one project, and attribution is\n * exactly what the tab promises (contract C1, decision 2 of the review).\n *\n * The ring is per project root and bounded by {@link LOG_RING_LIMIT}, the oldest\n * event evicted first. It is written from the single runtime point that already\n * writes the matching lifecycle line to the DSH log, so both readers see the\n * same facts and there is no second write path to keep in sync. The newest\n * {@link LOG_PAGE_SIZE} events travel inside the snapshot the tab is drawn from;\n * {@link page} is what \"show older\" asks for the rest.\n *\n * Nothing here touches the disk, and the clock belongs to the caller. A module\n * map rather than runtime state on purpose: the route handler ({@link module:dsh-project-mcp/ui})\n * answers `GET logs` without a runtime, and the panel and the runtime must read\n * one buffer. {@link record} never throws — a ring write must not fail the pass\n * that reported the event.\n *\n * @module dsh-project-mcp/logs\n */\n\nimport type { LogEvent } from './types.ts'\n\n/** Events one project's ring holds; the oldest is evicted past it. */\nexport const LOG_RING_LIMIT = 200\n\n/** Events one page carries: the snapshot's tail, and {@link page}'s default window. */\nexport const LOG_PAGE_SIZE = 50\n\n/**\n * One ring per project root, oldest event first.\n *\n * Kept per root because two projects of one host are two histories; the history\n * lives exactly as long as the process, since the panel's `Clear` is client-side\n * and there is no `Clear` route (contract C1).\n */\nconst rings = new Map<string, LogEvent[]>()\n\n/**\n * Add one event to its project's ring.\n *\n * Called from the runtime points that write the lifecycle line to the DSH log,\n * in addition to it. An event identical to one already held is dropped, so a\n * repeated pass can never make the tab show the same line twice. Total: a\n * malformed event or a ring bug is swallowed rather than thrown into the pass\n * that reported it.\n * @param event - the event to record; `message` is folded onto one line.\n */\nexport function record(event: LogEvent): void {\n try {\n if (typeof event.projectRoot !== 'string' || event.projectRoot === '') return\n const ring = ringOf(event.projectRoot)\n if (ring.some((existing) => sameEvent(existing, event))) return\n ring.push({ ...event, message: oneLine(event.message) })\n if (ring.length > LOG_RING_LIMIT) ring.splice(0, ring.length - LOG_RING_LIMIT)\n } catch {\n // Nothing a ring write can raise is worth failing the pass for.\n }\n}\n\n/**\n * The newest events of one project, oldest first.\n *\n * This is what a snapshot carries, and it hands out a copy: a reader that kept\n * the array could otherwise watch it change under a later pass.\n * @param projectRoot - project whose ring is read.\n * @param limit - how many of the newest events to return; clamped to\n * `1…{@link LOG_RING_LIMIT}`, {@link LOG_PAGE_SIZE} when omitted.\n * @returns the events, oldest first; empty for a project with no history.\n */\nexport function latest(projectRoot: string, limit: number = LOG_PAGE_SIZE): LogEvent[] {\n const ring = rings.get(projectRoot)\n if (ring === undefined) return []\n const size = clampLimit(limit)\n return ring.slice(Math.max(0, ring.length - size))\n}\n\n/**\n * One page of a project's history, for \"show older\".\n *\n * Without `before` the page is the newest `limit` events — the same window a\n * snapshot carries, which is what the tab asks for on a refresh. With `before`\n * it is the newest `limit` events strictly older than that instant: the cursor\n * is the `at` of the oldest event already on screen, so consecutive pages do\n * not overlap.\n * @param input - the project to read, and the optional window.\n * @param input.projectRoot - project whose ring is read.\n * @param input.before - exclusive cursor in epoch ms; `at < before` only.\n * @param input.limit - page size; clamped to `1…{@link LOG_RING_LIMIT}`,\n * {@link LOG_PAGE_SIZE} when omitted.\n * @returns the page, the ring's total size, and whether older events remain\n * beyond the page — `more` is true when the window had to cut the history short.\n */\nexport function page(input: { projectRoot: string; before?: number; limit?: number }): {\n events: LogEvent[]\n total: number\n more: boolean\n} {\n const ring = rings.get(input.projectRoot) ?? []\n const older = input.before === undefined ? ring : ring.filter((event) => event.at < (input.before as number))\n const events = older.slice(Math.max(0, older.length - clampLimit(input.limit)))\n return { events, total: ring.length, more: older.length > events.length }\n}\n\n/**\n * How many events one project's ring holds right now.\n * @param projectRoot - project whose ring is read.\n * @returns the count, `0` for a project with no history.\n */\nexport function countOf(projectRoot: string): number {\n return rings.get(projectRoot)?.length ?? 0\n}\n\n/**\n * How many events of one project's ring belong to one session.\n *\n * Events the lifecycle line itself attributes to a session — `mounting`, `is up`,\n * a stall — are counted here; a project-level event (a shared instance's unmount)\n * carries no session and is counted by no session.\n * @param projectRoot - project whose ring is read.\n * @param sessionId - agent (session) id to count.\n * @returns the count, `0` for a session that produced nothing.\n */\nexport function countForSession(projectRoot: string, sessionId: string): number {\n return (rings.get(projectRoot) ?? []).filter((event) => event.sessionId === sessionId).length\n}\n\n/**\n * Drop one project's history, or every project's, for tests.\n *\n * Not a route: the panel's `Clear` is client-side (contract C1), so nothing in\n * the product calls this — a test that asserts on a ring starts from no history.\n * @param projectRoot - project to forget; omitted forgets every project.\n */\nexport function clear(projectRoot?: string): void {\n if (projectRoot === undefined) rings.clear()\n else rings.delete(projectRoot)\n}\n\n/** The ring of one root, created empty on first use. */\nfunction ringOf(projectRoot: string): LogEvent[] {\n const existing = rings.get(projectRoot)\n if (existing !== undefined) return existing\n const ring: LogEvent[] = []\n rings.set(projectRoot, ring)\n return ring\n}\n\n/**\n * Whether two events are the same event, field by field. The project is the ring\n * they share, so it is the one field not compared here.\n */\nfunction sameEvent(left: LogEvent, right: LogEvent): boolean {\n return (\n left.at === right.at &&\n left.level === right.level &&\n left.sessionId === right.sessionId &&\n left.server === right.server &&\n left.message === right.message &&\n left.detail === right.detail\n )\n}\n\n/**\n * Fold a message onto one line, as {@link LogEvent.message} promises: the tab\n * renders a row per event, and a newline inside one would break the column.\n */\nfunction oneLine(message: string): string {\n return message.replace(/\\s*\\n\\s*/g, ' ').trim()\n}\n\n/**\n * A page size clamped to what the ring can serve: a caller cannot ask for more\n * than {@link LOG_RING_LIMIT} events, and a zero or a negative size is raised to\n * the one event every page is at least worth.\n */\nfunction clampLimit(limit: number | undefined): number {\n if (limit === undefined || !Number.isFinite(limit)) return LOG_PAGE_SIZE\n return Math.min(LOG_RING_LIMIT, Math.max(1, Math.trunc(limit)))\n}\n","/**\n * The plugin's event service: one publication point, and its consumers.\n *\n * A lifecycle fact used to be written three times by the runtime — a line in the\n * DSH log, the same fact into the ring (`src/logs.ts`), and the snapshot\n * announcement the panel watches. Three writes that had to agree. Here they are\n * one: the runtime publishes a {@link PluginEvent} through {@link emitEvent}, and\n * every reader is a subscriber —\n *\n * 1. the ring, subscribed here against {@link module:dsh-project-mcp/logs}\n * `record`, so the tab and the log are fed by one publication;\n * 2. the DSH log, subscribed by the runtime's own\n * {@link module:dsh-project-mcp/runtime} wiring through {@link logConsumer},\n * because only the runtime holds the host `ctx`;\n * 3. anything else a test or a later surface attaches through\n * {@link subscribeEvent}.\n *\n * Publication is synchronous and total: listeners run in subscription order, a\n * listener that throws is swallowed rather than failing the pass that reported\n * the event, and {@link emitEvent} never throws into its caller. The clock\n * belongs to the caller ({@link PluginEvent.at}), as it does in the ring, so a\n * test can pin an event to a moment.\n *\n * @module dsh-project-mcp/notifications\n */\n\nimport { record } from './logs.ts'\nimport type { LogLevel } from './types.ts'\n\n/**\n * One lifecycle event, as every consumer reads it.\n *\n * The same fields the ring keeps, because the ring is a subscriber — the tab\n * draws exactly the event this service published. The one field with two\n * readers is {@link PluginEvent.level}: the ring colours the row with it, and\n * the DSH log writes the line through the matching level method.\n */\nexport interface PluginEvent {\n /** When the event happened, epoch ms. */\n readonly at: number\n /** How serious it is, as the Logs tab colours it. */\n readonly level: LogLevel\n /** Project root the event belongs to; the ring is keyed by it. */\n readonly projectRoot: string\n /**\n * Session the event is attributed to. Set exactly when the lifecycle line it\n * mirrors names one — `mounting`, `is up`, a stall — and absent on a\n * project-level event such as a shared instance's unmount.\n */\n readonly sessionId?: string\n /** `serverName` the event is about; absent for an event with no server. */\n readonly server?: string\n /** One line, without the `project-mcp:` prefix the log line carries. */\n readonly message: string\n /** The three facts an error carries — the failure, the endpoint, the document. */\n readonly detail?: string\n /**\n * Wire code of {@link PluginEvent.message} (F-48), into the client's\n * `projectMcp.host` namespace. The prose fields stay byte-identical English\n * and remain the fallback: a consumer that never resolves codes — the DSH\n * log is one — reads exactly what it read before the code existed.\n */\n readonly code?: string\n /**\n * Flat params of {@link PluginEvent.code}; numbers stringify at emission. A\n * param whose name ends in `Code` (`reasonCode`, `sharingCode`) is itself a\n * wire code the client resolves two-level, substituting it under the plain\n * name.\n */\n readonly params?: Record<string, string>\n /** Wire code of {@link PluginEvent.detail}, the same additive companion. */\n readonly detailCode?: string\n /** Flat params of {@link PluginEvent.detailCode}. */\n readonly detailParams?: Record<string, string>\n /**\n * The DSH log line, when it says more than {@link PluginEvent.message}.\n *\n * `message` is what the tab lists one row per event; the line is what an\n * operator reads in the host log, and for two events it names what the row's\n * own columns already carry — the declaring path and the endpoint of a failed\n * mount, the server and the root of a release. The runtime passes the very\n * text the line had before the event existed, so the log is unchanged; absent\n * means `message` is the line.\n */\n readonly line?: string\n /**\n * Severity the DSH log writes this event under, when it differs from\n * {@link PluginEvent.level}.\n *\n * The tab's level is about the row — a release is a warning there, a failed\n * mount is an error — while the host log keeps the level the line always had\n * (`info` for the whole lifecycle except a failure or a stall, which are\n * `warn`). Two readers, two vocabularies: without this field, wiring the log\n * through the event would silently promote `unmounting` to `warn` and\n * `mount failed` to `error` in the operator's log. Absent means the host log\n * follows {@link PluginEvent.level}.\n */\n readonly logLevel?: LogLevel\n}\n\n/** One subscriber, told the whole event at publication time. */\nexport type PluginEventListener = (event: PluginEvent) => void\n\n/**\n * The one level method this module calls on a host logger.\n *\n * Structural on purpose: the runtime's `ctx.logger` satisfies it, and so does a\n * test double with no error method.\n */\nexport type LoggerMethod = (format: unknown, ...parameters: unknown[]) => void\n\n/**\n * The host logger as this module needs it: the level methods, and nothing else.\n *\n * Deliberately not `LoggerService` — the service has a call signature and a\n * `debug` method this module never uses, so declaring only the three makes a\n * partial double (`{ warn }`) a valid logger.\n */\nexport interface PluginLoggerLike {\n error?: LoggerMethod\n info?: LoggerMethod\n warn?: LoggerMethod\n}\n\n/** Listeners in subscription order; publication walks a copy of it. */\nconst listeners = new Set<PluginEventListener>()\n\n/**\n * Publish one plugin event to every subscriber, and swallow what they raise.\n *\n * Called from the runtime points that used to write the DSH log and the ring by\n * hand, and the only publication point there is. Listeners run synchronously in\n * subscription order — so a consumer registered first sees the event first —\n * over a snapshot of the set, which keeps a listener that unsubscribes itself\n * (or subscribes another) during the walk from corrupting it.\n * @param event - the event to publish.\n */\nexport function emitEvent(event: PluginEvent): void {\n for (const listener of [...listeners]) {\n try {\n listener(event)\n } catch {\n // A consumer's failure is not the reporting pass's failure: the ring\n // already promises the same, and one broken reader must not cost the\n // others the event.\n }\n }\n}\n\n/**\n * Subscribe a consumer.\n *\n * The ring is one such consumer, installed here for the life of the module; a\n * host logger and a test are others. Subscribing the same listener twice keeps\n * the one entry it already has, so a wrapper re-registered around the same touch\n * does not make the event arrive twice, and unsubscribing is idempotent:\n * {@link PluginEventListener} is unique in the set, and removing what is absent\n * is a no-op.\n * @param listener - told every event published from now on.\n * @returns the disposer that stops it; safe to call more than once.\n */\nexport function subscribeEvent(listener: PluginEventListener): () => void {\n listeners.add(listener)\n return () => {\n listeners.delete(listener)\n }\n}\n\n/**\n * Whether a listener is subscribed right now.\n *\n * A diagnostic for the subscription itself: the disposer returns nothing, so\n * this is how a caller — a test proving that a disposer detached its listener,\n * or memory after a re-mount — reads the fact without counting a publication.\n * @param listener - the listener to look up.\n * @returns `true` while it is subscribed.\n */\nexport function isSubscribed(listener: PluginEventListener): boolean {\n return listeners.has(listener)\n}\n\n/**\n * The DSH log as a consumer: one line per event, under the plugin's own prefix\n * and level.\n *\n * Returns the listener rather than attaching anything itself: the logger lives\n * on the host context, which only the runtime holds, so the runtime owns the\n * subscription (and drops it when it is disposed). The line is `project-mcp: `\n * plus {@link logText}, so the text a reader has seen does not change; the level\n * method is {@link PluginEvent.logLevel} when the event names one, because that\n * is the level the line has always had, and the tab's own level otherwise — and\n * a partial logger gets the nearest method it has ({@link levelMethod}).\n * @param logger - host logger whose level methods carry the line.\n * @returns the listener to subscribe; detach it with the disposer\n * {@link subscribeEvent} returned.\n */\nexport function logConsumer(logger: PluginLoggerLike): PluginEventListener {\n return (event) => {\n const method = levelMethod(logger, event.logLevel ?? event.level)\n if (method === undefined) return\n method(`project-mcp: ${logText(event)}`)\n }\n}\n\n/**\n * The one line the DSH log writes for an event.\n *\n * An event that named the line it replaces carries it ({@link PluginEvent.line}),\n * so the log is byte-for-byte what it was. The rest compose it: where the\n * lifecycle line named the server in front of the message, the event carries the\n * name as its own field, because the tab draws it as a column and does not repeat\n * it in the message — `mounting`, `is up` and `unmounting` put the name back in\n * here. The stall and the failure already open their message with the name (it is\n * the first line of the row's detail).\n * @param event - the event to render.\n * @returns the line, without the `project-mcp: ` prefix.\n */\nfunction logText(event: PluginEvent): string {\n if (event.line !== undefined) return event.line\n const server = event.server\n if (server !== undefined) {\n if (event.message.startsWith('mounting ')) return `${server}: ${event.message}`\n if (event.message.startsWith('is up — ')) return `${server} ${event.message}`\n if (event.message.startsWith('unmounting — ')) {\n return `unmounting ${server} in ${event.projectRoot} — ${event.message.slice('unmounting — '.length)}`\n }\n }\n return event.message\n}\n\n/**\n * The logger method one level writes through; `up` is an info-level success.\n *\n * A partial logger falls back to the levels it does have — `error`, then `warn`,\n * then `info` — rather than losing the line: the harnesses that publish only\n * `warn` are the reason, and a deployment's logger has all three.\n */\nfunction levelMethod(logger: PluginLoggerLike, level: LogLevel): LoggerMethod | undefined {\n if (level === 'warn') return logger.warn ?? logger.info\n if (level === 'error') return logger.error ?? logger.warn ?? logger.info\n return logger.info\n}\n\n/**\n * The ring as a consumer, installed once for the module.\n *\n * Subscribed here rather than called by the runtime so the runtime has exactly\n * one write path: it publishes, and the tab and the DSH log both read that one\n * publication. {@link record} stays the ring's only writer, and stays total —\n * it is written to be called from an event the pass must not fail over.\n */\nsubscribeEvent((event) => {\n record(event)\n})\n","/**\n * Durable per-project MCP usage counters for `dsh-project-mcp`.\n *\n * The host half counts the `tools/result` events whose tool belongs to a server\n * it mounted itself, keyed by project root and `serverName`. The numbers are\n * remembered across sessions and restarts in one versioned document under\n * `$DSH_HOME`, written atomically on a debounce so a tool call never waits for\n * the filesystem, and a failed write is logged and dropped rather than allowed\n * to disturb the call.\n *\n * Counting itself is pure ({@link recordUsage}) and the document only sits\n * behind {@link UsageStore}, so the model is testable without a filesystem.\n *\n * @module dsh-project-mcp/usage\n */\n\nimport { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { dshHome } from './discovery.ts'\nimport type { ServerUsage, SessionUsage } from './types.ts'\n\n/** Current on-disk document version; another version is ignored, not migrated. */\nexport const USAGE_VERSION = 1\n\n/** Counter document name under `$DSH_HOME`. */\nexport const USAGE_FILE_NAME = 'dsh-project-mcp-usage.json'\n\n/** Counters keyed by project root, then by `serverName`. */\nexport type UsageState = Record<string, Record<string, ServerUsage>>\n\n/** The durable counter document as written to disk. */\nexport interface UsageDocument {\n /** Document version; a reader that does not know it starts clean. */\n version: typeof USAGE_VERSION\n /** Counters of every project ever seen. */\n projects: UsageState\n}\n\n/** One registry call, before it is attributed to a mounted server. */\nexport interface UsageCall {\n /** Project root the calling agent resolved to. */\n projectRoot: string\n /** Server names this plugin currently mounts for that project. */\n servers: ReadonlySet<string>\n /**\n * Public tool name delivered by `tools/result`, ie `mcp__<serverName>__<name>`.\n * A name the registry had to truncate to the function-name budget keeps this\n * prefix, so the server is still identifiable.\n */\n toolName: string\n /** `true` when the settled result carried an error. */\n isError: boolean\n /** Epoch milliseconds of the call. */\n at: number\n /**\n * Session the call belongs to: the id of the agent that made it.\n *\n * The host resolves an agent from the call's own event, and every other\n * surface of this plugin already calls that id the session id (a `LogEvent`,\n * a `SessionSnapshot`). Counting is therefore attributable without a second\n * lookup, which is what lets the panel answer \"and how much of this is mine?\"\n * (F-34).\n */\n sessionId: string\n}\n\n/** One counted call, attributed to a project and a server this plugin mounted. */\nexport interface UsageEvent {\n /** Project root the calling agent resolved to. */\n projectRoot: string\n /** `serverName` this plugin mounted for that project. */\n serverName: string\n /**\n * Tool name as declared by the server, ie without the `mcp__<serverName>__`\n * prefix. A name the registry truncated to its function-name budget cannot be\n * reversed, so its key is the public suffix the registry published.\n */\n tool: string\n /** `true` when the settled result carried an error. */\n isError: boolean\n /** Epoch milliseconds of the call. */\n at: number\n /** Session (agent) id this call is counted under, besides the project total. */\n sessionId: string\n}\n\n/** The `tools/result` execution view this module reads. */\nexport interface ToolResultEventLike {\n /** Public tool name, `mcp__<serverName>__<name>`. */\n readonly name: string\n /** Agent the call ran for; absent on a host-level call, which is not counted. */\n readonly agent?: { readonly id: string } | undefined\n}\n\n/** The settled `tools/result` outcome view this module reads. */\nexport interface ToolResultLike {\n /** `true` when the call settled as an error. */\n readonly isError: boolean\n}\n\n/** Everything {@link observeToolResults} needs, injected so it is testable. */\nexport interface ToolResultObserverOptions {\n /** Register the `tools/result` listener; returns its disposer. */\n on(\n name: 'tools/result',\n handler: (exec: ToolResultEventLike, result: ToolResultLike) => undefined,\n ): (() => void) | undefined\n /** Resolve the project and the mounted servers of the agent that made a call. */\n mountsFor(agentId: string): { projectRoot: string; servers: ReadonlySet<string> } | undefined\n /** Durable store the attributed calls are recorded in. */\n store: Pick<UsageStore, 'record'>\n /** Clock override; defaults to `Date.now`. */\n now?: () => number\n}\n\n/** The logger surface the store uses; a Cordis logger satisfies it. */\nexport interface UsageLogger {\n /** Non-fatal report; the store never throws at its caller. */\n warn(message: string): void\n}\n\n/** Construction options for {@link UsageStore}; production uses the defaults. */\nexport interface UsageStoreOptions {\n /** Absolute document path; defaults to `$DSH_HOME/dsh-project-mcp-usage.json`. */\n file?: string\n /** Debounce before a recorded call reaches disk. */\n flushMs?: number\n /** Sink for a corrupt document or a failed write. */\n logger?: UsageLogger\n}\n\n/** Debounce that keeps a tool call off the filesystem. */\nconst DEFAULT_FLUSH_MS = 1_000\n\n/**\n * Attribute one registry tool name to a server this plugin mounted.\n *\n * The prefix is never parsed blindly: only mounted names are candidates, and\n * the longest match wins, so a mounted `alpha_` is never shadowed by a mounted\n * `alpha` when both publish tools into one scope.\n *\n * @param toolName - public registry name, `mcp__<serverName>__<name>`.\n * @param servers - names this plugin mounted for the calling agent's project.\n * @returns the matched `serverName`, or `undefined` for a foreign tool.\n */\nexport function matchServer(toolName: string, servers: ReadonlySet<string>): string | undefined {\n let match: string | undefined\n for (const server of servers) {\n if (!toolName.startsWith(`mcp__${server}__`)) continue\n if (match === undefined || server.length > match.length) match = server\n }\n return match\n}\n\n/**\n * Attribute one registry call, or `undefined` when no server this plugin\n * mounted for the project claims the name.\n * @param call - the raw `tools/result` view plus the caller's mounts.\n * @returns the counted event, ready for {@link recordUsage}.\n */\nexport function usageEventFor(call: UsageCall): UsageEvent | undefined {\n const serverName = matchServer(call.toolName, call.servers)\n if (serverName === undefined) return undefined\n return {\n projectRoot: call.projectRoot,\n serverName,\n tool: call.toolName.slice(`mcp__${serverName}__`.length),\n isError: call.isError,\n at: call.at,\n sessionId: call.sessionId,\n }\n}\n\n/**\n * Count one call into the state.\n *\n * Pure: it reads and returns counters only, touching no filesystem, clock or\n * logger, so the model is testable on its own.\n *\n * @param state - counters before the call.\n * @param event - one attributed call.\n * @returns a new state carrying the increment; `lastUsedAt` moves and is set\n * only on a success, while a failure keeps the previous stamp.\n */\nexport function recordUsage(state: UsageState, event: UsageEvent): UsageState {\n const project = state[event.projectRoot] ?? {}\n const previous = project[event.serverName]\n const tools: Record<string, number> = { ...previous?.tools }\n tools[event.tool] = (tools[event.tool] ?? 0) + 1\n const lastUsedAt = event.isError ? previous?.lastUsedAt : new Date(event.at).toISOString()\n const sessions: Record<string, SessionUsage> = { ...previous?.sessions }\n const previousSession = sessions[event.sessionId]\n const sessionTools: Record<string, number> = { ...previousSession?.tools }\n sessionTools[event.tool] = (sessionTools[event.tool] ?? 0) + 1\n const sessionLastUsedAt = event.isError\n ? previousSession?.lastUsedAt\n : new Date(event.at).toISOString()\n sessions[event.sessionId] = {\n calls: (previousSession?.calls ?? 0) + 1,\n errors: (previousSession?.errors ?? 0) + (event.isError ? 1 : 0),\n tools: sessionTools,\n ...(sessionLastUsedAt === undefined ? {} : { lastUsedAt: sessionLastUsedAt }),\n }\n const usage: ServerUsage = {\n calls: (previous?.calls ?? 0) + 1,\n errors: (previous?.errors ?? 0) + (event.isError ? 1 : 0),\n tools,\n sessions,\n ...(lastUsedAt === undefined ? {} : { lastUsedAt }),\n }\n return {\n ...state,\n [event.projectRoot]: { ...project, [event.serverName]: usage },\n }\n}\n\n/**\n * Subscribe the durable counters to `tools/result`.\n *\n * Counting is per event, never deduplicated against a parent: a programmatic\n * sub-dispatch is its own call with its own result, while the enclosing\n * `run_code` carries a name no server claims, so each MCP call is counted\n * exactly once on either path.\n *\n * @param options - registry subscription, agent resolver, store and clock.\n * @returns the disposer that unregisters the listener.\n */\nexport function observeToolResults(options: ToolResultObserverOptions): () => void {\n const now = options.now ?? Date.now\n const listener = (exec: ToolResultEventLike, result: ToolResultLike): undefined => {\n const agentId = exec.agent?.id\n if (agentId === undefined) return undefined\n const mounts = options.mountsFor(agentId)\n if (mounts === undefined) return undefined\n const event = usageEventFor({\n projectRoot: mounts.projectRoot,\n servers: mounts.servers,\n toolName: exec.name,\n isError: result.isError,\n at: now(),\n sessionId: agentId,\n })\n if (event === undefined) return undefined\n options.store.record(event)\n return undefined\n }\n const dispose = options.on('tools/result', listener)\n return () => {\n dispose?.()\n }\n}\n\n/**\n * The durable counters: one versioned document under `$DSH_HOME`, loaded once\n * when the plugin applies and written atomically on a debounce.\n *\n * Every failure mode is non-fatal by design. A missing, unreadable, foreign or\n * older-version document starts clean, and a write that fails is logged and\n * forgotten, because a tool call must never fail on a counter that could not\n * be stored.\n */\nexport class UsageStore {\n private state: UsageState\n private timer: ReturnType<typeof setTimeout> | undefined\n private dirty = false\n private disposed = false\n private readonly file: string\n private readonly flushMs: number\n private readonly logger: UsageLogger | undefined\n\n /** @param options - document path, debounce and log sink. */\n constructor(options: UsageStoreOptions = {}) {\n this.file = options.file ?? join(dshHome(), USAGE_FILE_NAME)\n this.flushMs = options.flushMs ?? DEFAULT_FLUSH_MS\n this.logger = options.logger\n this.state = this.load()\n }\n\n /** Counters of one project root, or `undefined` when it has none yet. */\n forProject(projectRoot: string): Record<string, ServerUsage> | undefined {\n return this.state[projectRoot]\n }\n\n /** Count one attributed call and schedule the debounced write. */\n record(event: UsageEvent): void {\n if (this.disposed) return\n this.state = recordUsage(this.state, event)\n this.dirty = true\n if (this.timer !== undefined) return\n this.timer = setTimeout(() => {\n this.timer = undefined\n this.flush()\n }, this.flushMs)\n this.timer.unref?.()\n }\n\n /** Write the counters atomically now. Best effort: it never throws. */\n flush(): void {\n if (!this.dirty) return\n const document: UsageDocument = { version: USAGE_VERSION, projects: this.state }\n const temporary = `${this.file}.${process.pid}.tmp`\n try {\n mkdirSync(dirname(this.file), { recursive: true })\n writeFileSync(temporary, `${JSON.stringify(document, undefined, 2)}\\n`, 'utf8')\n renameSync(temporary, this.file)\n this.dirty = false\n } catch (error) {\n this.logger?.warn(\n `project-mcp: writing usage counters to ${this.file} failed: ${errorText(error)}`,\n )\n }\n }\n\n /**\n * Cancel the pending write, flush what is dirty, and stop counting. Safe to\n * call more than once; the plugin fiber calls it on disposal.\n */\n dispose(): void {\n if (this.timer !== undefined) {\n clearTimeout(this.timer)\n this.timer = undefined\n }\n if (this.disposed) return\n this.disposed = true\n this.flush()\n }\n\n private load(): UsageState {\n let text: string\n try {\n text = readFileSync(this.file, 'utf8')\n } catch {\n return {}\n }\n const state = parseUsageDocument(text)\n if (state === undefined) {\n this.logger?.warn(\n `project-mcp: ignoring usage counters in ${this.file} (unreadable or unsupported version); starting clean`,\n )\n return {}\n }\n return state\n }\n}\n\n/**\n * Parse one durable counter document.\n *\n * Anything this version cannot trust — malformed JSON, a foreign shape, or\n * another version — yields `undefined` so the caller starts clean instead of\n * throwing, and each counter is validated so a hand-edited document cannot\n * poison later arithmetic.\n *\n * @param text - raw document contents.\n * @returns the counters, or `undefined` when the document is not usable.\n */\nexport function parseUsageDocument(text: string): UsageState | undefined {\n let value: unknown\n try {\n value = JSON.parse(text)\n } catch {\n return undefined\n }\n if (!isRecord(value)) return undefined\n if (value.version !== USAGE_VERSION) return undefined\n if (!isRecord(value.projects)) return undefined\n return sanitizeProjects(value.projects)\n}\n\nfunction sanitizeProjects(raw: Record<string, unknown>): UsageState {\n const projects: UsageState = {}\n for (const [root, servers] of Object.entries(raw)) {\n if (!isRecord(servers)) continue\n const rows: Record<string, ServerUsage> = {}\n for (const [server, usage] of Object.entries(servers)) {\n const parsed = sanitizeUsage(usage)\n if (parsed !== undefined) rows[server] = parsed\n }\n if (Object.keys(rows).length > 0) projects[root] = rows\n }\n return projects\n}\n\nfunction sanitizeUsage(value: unknown): ServerUsage | undefined {\n if (!isRecord(value)) return undefined\n if (!isCount(value.calls) || !isCount(value.errors)) return undefined\n return {\n calls: value.calls,\n errors: value.errors,\n tools: countMap(value.tools),\n // The per-session split is carried through, not rebuilt: a reader that\n // dropped it would lose every session figure on the first restart, while\n // the project totals it kept looked perfectly healthy.\n ...sanitizeSessions(value.sessions),\n ...(typeof value.lastUsedAt === 'string' ? { lastUsedAt: value.lastUsedAt } : {}),\n }\n}\n\n/** A record of non-negative integer counts, with every other entry dropped. */\nfunction countMap(value: unknown): Record<string, number> {\n const counts: Record<string, number> = {}\n if (isRecord(value)) {\n for (const [name, count] of Object.entries(value)) {\n if (isCount(count)) counts[name] = count\n }\n }\n return counts\n}\n\n/** The `sessions` half of a stored record, as the `...` spread a caller wants. */\nfunction sanitizeSessions(value: unknown): { sessions?: Record<string, SessionUsage> } {\n if (!isRecord(value)) return {}\n const sessions: Record<string, SessionUsage> = {}\n for (const [id, usage] of Object.entries(value)) {\n const parsed = sanitizeSessionUsage(usage)\n if (parsed !== undefined) sessions[id] = parsed\n }\n return Object.keys(sessions).length === 0 ? {} : { sessions }\n}\n\nfunction sanitizeSessionUsage(value: unknown): SessionUsage | undefined {\n if (!isRecord(value)) return undefined\n if (!isCount(value.calls) || !isCount(value.errors)) return undefined\n return {\n calls: value.calls,\n errors: value.errors,\n tools: countMap(value.tools),\n ...(typeof value.lastUsedAt === 'string' ? { lastUsedAt: value.lastUsedAt } : {}),\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction isCount(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0\n}\n\nfunction errorText(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n","/**\n * Write half of the entry editor: every decision one save makes, plus the\n * atomic document write those decisions guard.\n *\n * The host and the browser half agree on the outcome through the contract\n * (`docs/design/contracts/write-path.md`): a save replaces `mcpServers[<server>]`\n * wholesale, keeps every other key of the document, normalizes the formatting\n * (two spaces, trailing newline) and never writes a value the editor could not\n * see. Everything here is pure except {@link writeDocument}, so the rules are\n * testable without a filesystem.\n *\n * @module dsh-project-mcp/write\n */\n\nimport { createHash, randomUUID } from 'node:crypto'\nimport { copyFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'\nimport { basename, dirname, join, resolve } from 'node:path'\nimport { DEFAULT_LOCAL_FILES } from './discovery.ts'\nimport { hasReference } from './parse.ts'\nimport type { EntryField, EntrySnapshot, WriteScope } from './types.ts'\n\n/** Characters of the SHA-256 digest published as a document revision. */\nconst REVISION_LENGTH = 16\n\n/**\n * Key names whose literal value is treated as a credential. The document is the\n * only place such a value exists, so the host shows the key and withholds the\n * value; a save keeps whatever the document declares for it.\n */\nconst SECRET_KEY_PATTERN =\n /(?:^|[^a-z0-9])(?:password|passwd|secret|token|credential|credentials|apikey|api[_-]?key|private[_-]?key|access[_-]?key|auth)/i\n\n/**\n * Keys the editor presents, whatever the transport.\n */\nconst COMMON_KEYS = ['type', 'transport', 'enabled', 'disabled', 'connectTimeoutMs'] as const\n\n/** Keys that belong to one transport alone; the other section is not modelled. */\nconst SECTION_KEYS: Record<'stdio' | 'streamable-http', readonly string[]> = {\n stdio: ['command', 'args', 'cwd', 'env'],\n 'streamable-http': ['url', 'headers'],\n}\n\n/** Every presented key, whichever transport an entry declares. */\nconst PRESENTED_KEYS = new Set([...COMMON_KEYS, ...SECTION_KEYS.stdio, ...SECTION_KEYS['streamable-http']])\n\n/**\n * Opaque content revision of one document.\n *\n * A save carries the revision the editor was built from, so a document changed\n * underneath the form is refused instead of merged. The value is a prefix of a\n * SHA-256 digest: stable for identical bytes, different for any change, and\n * carrying nothing about the content.\n * @param text - exact document bytes as read from disk.\n * @returns a short hexadecimal digest of the content.\n */\nexport function documentRevision(text: string): string {\n return createHash('sha256').update(text, 'utf8').digest('hex').slice(0, REVISION_LENGTH)\n}\n\n/** How one declaring document may be written, and why not when it may not. */\nexport interface WriteScopeInfo {\n /** Tier of the declaring document. */\n readonly scope: WriteScope\n /** One line saying why a write is unavailable, when one is. */\n readonly reason?: string\n /**\n * Stable wire code of `reason` (`projectMcp.host` namespace), for\n * client-side translation; the prose `reason` keeps its byte-identical\n * English and stays the fallback.\n */\n readonly blockedCode?: string\n /** Flat params of {@link blockedCode}. */\n readonly blockedParams?: Record<string, string>\n}\n\n/**\n * Which tier one declaring document belongs to.\n *\n * The two lists are the deployment's own: `projectDocuments` — the project\n * documents it reads (`localFiles`) — are always writable, and `globalDocuments`\n * — the ones its `globalFiles` names — are writable only with an explicit\n * per-write consent and a deployment that enables `allowGlobalWrite`. Anything\n * else (a profile document, a bundled one, an in-memory pseudo-path) is never\n * written.\n * @param document - absolute path of the declaring document.\n * @param projectRoot - project root the row belongs to.\n * @param options - the deployment's document lists and the `allowGlobalWrite` switch.\n * @returns the tier plus the blocking sentence, when there is one.\n */\nexport function writeScopeFor(\n document: string,\n projectRoot: string,\n options: {\n projectDocuments?: readonly string[]\n globalDocuments?: readonly string[]\n allowGlobalWrite?: boolean\n } = {},\n): WriteScopeInfo {\n const target = resolve(document)\n const projectDocuments = (options.projectDocuments ?? DEFAULT_LOCAL_FILES).map((path) =>\n resolve(projectRoot, path),\n )\n if (projectDocuments.includes(target)) return { scope: 'project' }\n const globalDocuments = (options.globalDocuments ?? []).map((path) => resolve(path))\n if (!globalDocuments.includes(target)) {\n const writable = [...projectDocuments, ...globalDocuments]\n // The prose is the fallback and never changes by a character; the code\n // and its flat params are the additive companions the client translates\n // (`projectMcp.host` namespace).\n const notConfigured = writable.length === 0\n return {\n scope: 'readonly',\n reason: notConfigured\n ? `${document} is not a document this deployment reads, and it configures none to write`\n : `${document} is not one of this deployment's MCP documents; only ${writable.join(', ')} can be written`,\n blockedCode: notConfigured ? 'write.blocked.notConfigured' : 'write.blocked.notWritable',\n blockedParams: notConfigured ? { document } : { document, writable: writable.join(', ') },\n }\n }\n if (options.allowGlobalWrite === true) return { scope: 'global' }\n return {\n scope: 'global',\n reason: `writing the global tier is disabled by this deployment (allowGlobalWrite: false); ${document} stays read-only here`,\n blockedCode: 'write.blocked.globalDisabled',\n blockedParams: { document },\n }\n}\n\n/** Raw `env`/`headers` keys whose declared value is answered outside the document. */\nexport interface CredentialKeys {\n /** Keys of the entry's `env` object. */\n readonly env?: ReadonlySet<string>\n /** Keys of the entry's `headers` object. */\n readonly headers?: ReadonlySet<string>\n}\n\n/** Mutable local view of {@link EntrySnapshot}, so the builder can assign fields. */\ninterface MutableEntry {\n transport: 'stdio' | 'streamable-http'\n command?: string\n args?: string[]\n cwd?: string\n env?: EntryField[]\n url?: string\n headers?: EntryField[]\n enabled?: boolean\n connectTimeoutMs?: number\n extra?: Record<string, unknown>\n}\n\n/**\n * Parse one declared entry into the body the editor is given.\n *\n * Every field is what the document declares: a resolved default (the project\n * root folded into `cwd`, for example) is never copied in, because a save\n * replaces the declaration, not the runtime config. A `env`/`headers` value is\n * handed over only when the document really holds it as a literal and the key\n * is not credential-shaped — otherwise the key is published with `masked` (and\n * `fromCredentials` when the project `.env` or the credentials file answered it)\n * and the value stays on the host.\n * @param declared - raw `mcpServers[<server>]` value as parsed from the document.\n * @param transport - transport of the parsed config, which decides the shape used.\n * @param credentials - key names per section that are answered outside the document.\n * @returns the entry body for the snapshot.\n */\nexport function buildEntrySnapshot(\n declared: unknown,\n transport: 'stdio' | 'streamable-http',\n credentials: CredentialKeys = {},\n): EntrySnapshot {\n const record = isRecord(declared) ? declared : {}\n const snapshot: MutableEntry = { transport }\n if (transport === 'stdio') {\n if (typeof record.command === 'string') snapshot.command = record.command\n const args = record.args\n if (Array.isArray(args) && args.every((item) => typeof item === 'string')) {\n snapshot.args = [...(args as string[])]\n }\n if (typeof record.cwd === 'string') snapshot.cwd = record.cwd\n const env = entryFields(record.env, credentials.env)\n if (env !== undefined) snapshot.env = env\n } else {\n if (typeof record.url === 'string') snapshot.url = visibleUrl(record.url)\n const headers = entryFields(record.headers, credentials.headers)\n if (headers !== undefined) snapshot.headers = headers\n }\n if (record.enabled === false || record.disabled === true) snapshot.enabled = false\n if (typeof record.connectTimeoutMs === 'number') {\n snapshot.connectTimeoutMs = record.connectTimeoutMs\n }\n const extra: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(record)) {\n // A key of the other transport is neither shown nor carried in `extra`:\n // {@link entryToDeclaration} keeps it from the declaration itself, so a\n // value the editor never saw cannot travel through the payload.\n if (PRESENTED_KEYS.has(key)) continue\n extra[key] = value\n }\n if (Object.keys(extra).length > 0) snapshot.extra = extra\n return snapshot\n}\n\n/**\n * Build the JSON object a save writes for one server.\n *\n * The declaration starts from the raw document entry, so keys the editor never\n * showed survive verbatim — including the other transport's section, which the\n * editor of the declared transport does not model and a switch drops on\n * purpose. `type`/`transport` keeps its declared spelling while the transport is\n * unchanged. `env`/`headers` follow the contract's three-way rule per key: a\n * masked key submitted without a `value` keeps the declared one, a key with a\n * `value` writes that value, and a declared key the submission omits is removed.\n * A key marked `fromCredentials` never writes the submitted value: the declared\n * text (usually a `${input:NAME}` reference) stays exactly as it is, so a\n * resolved secret can never reach the document.\n * @param entry - the entry body the panel submitted.\n * @param declared - raw `mcpServers[<server>]` value as parsed from the document.\n * @returns the declaration object to write in its place.\n */\nexport function entryToDeclaration(entry: EntrySnapshot, declared: unknown): Record<string, unknown> {\n const base: Record<string, unknown> = isRecord(declared) ? { ...declared } : {}\n const declaredUrl = typeof base.url === 'string' ? base.url : undefined\n const declaredEnv = stringRecord(base.env) ?? {}\n const declaredHeaders = stringRecord(base.headers) ?? {}\n const declaredTypeKey =\n typeof base.type === 'string' ? 'type' : typeof base.transport === 'string' ? 'transport' : undefined\n const declaredTypeValue = declaredTypeKey === undefined ? undefined : base[declaredTypeKey]\n const declaredType = declaredTransport(base)\n const sameTransport = declaredType === entry.transport\n\n for (const key of COMMON_KEYS) delete base[key]\n for (const key of SECTION_KEYS[entry.transport]) delete base[key]\n // A switched transport drops the other transport's keys with it; an unchanged\n // one keeps them, because the editor of this transport never modelled them.\n if (!sameTransport) {\n for (const key of [...SECTION_KEYS.stdio, ...SECTION_KEYS['streamable-http']]) delete base[key]\n }\n\n if (entry.extra !== undefined) {\n for (const [key, value] of Object.entries(entry.extra)) {\n if (PRESENTED_KEYS.has(key)) continue\n base[key] = value\n }\n }\n // `type`/`transport` is a presented key, but its declared spelling is kept\n // while the transport is unchanged (`sse`, for example, would otherwise be\n // rewritten as `streamable-http`).\n if (declaredTypeKey !== undefined && sameTransport) base[declaredTypeKey] = declaredTypeValue\n\n if (entry.transport === 'stdio') {\n if (entry.command !== undefined) base.command = entry.command\n if (entry.args !== undefined) base.args = [...entry.args]\n if (entry.cwd !== undefined) base.cwd = entry.cwd\n if (entry.env !== undefined) base.env = fieldsToRecord(entry.env, declaredEnv)\n } else {\n if (entry.url !== undefined) base.url = urlToWrite(entry.url, declaredUrl)\n if (entry.headers !== undefined) base.headers = fieldsToRecord(entry.headers, declaredHeaders)\n }\n if (entry.enabled === false) base.enabled = false\n if (entry.connectTimeoutMs !== undefined) base.connectTimeoutMs = entry.connectTimeoutMs\n return base\n}\n\n/**\n * A refusal {@link applyEntry} throws: the English message, byte-identical to\n * what the site threw before codes existed, plus the `projectMcp.host` wire\n * code and its flat params beside it (F-48). The save path catches it and\n * reuses the companions as its own `messageCode`/`messageParams`, so the\n * client translates the refusal instead of wrapping raw English.\n */\nexport class WriteDocError extends Error {\n constructor(\n message: string,\n /** The dotted wire code, into the client's `projectMcp.host` namespace. */\n readonly code: string,\n /** Flat params of the code, when it has any. */\n readonly params?: Record<string, string>,\n ) {\n super(message)\n this.name = 'WriteDocError'\n }\n}\n\n/**\n * Replace one entry in a document's text.\n *\n * Only `mcpServers[server]` changes: the rest of the server map and every other\n * key of the document are serialized back as they were, with two-space\n * indentation and a trailing newline.\n * @param documentText - current document bytes.\n * @param server - key inside `mcpServers` to replace.\n * @param declaration - object to write in its place.\n * @returns the full new document text.\n * @throws {@link WriteDocError} when the text is not valid JSON or holds no\n * `mcpServers` object.\n */\nexport function applyEntry(\n documentText: string,\n server: string,\n declaration: Record<string, unknown>,\n): string {\n let root: unknown\n try {\n root = JSON.parse(documentText) as unknown\n } catch (error) {\n throw new WriteDocError(`the document is not valid JSON: ${errorText(error)}`, 'write.doc.invalidJson', {\n error: errorText(error),\n })\n }\n if (!isRecord(root)) throw new WriteDocError('the document is not a JSON object', 'write.doc.notObject')\n const servers = root.mcpServers\n if (!isRecord(servers)) throw new WriteDocError('the document has no \"mcpServers\" object', 'write.doc.noMcpServers')\n const next = { ...servers, [server]: declaration }\n return `${JSON.stringify({ ...root, mcpServers: next }, null, 2)}\\n`\n}\n\n/**\n * Write one document so that a failure at any step leaves it exactly as it was.\n *\n * Order: a `<document>.bak` copy of the current bytes first, then the new text\n * into a temporary file in the same directory, then a `rename` over the\n * document. The `rename` is the only operation that touches the original path,\n * so a failure while copying or while writing the temporary file cannot leave\n * half a document behind; a failed write drops the temporary file and rethrows.\n * @param document - absolute path of the document to replace.\n * @param text - the full new content.\n * @throws when the backup, the temporary write or the rename fails.\n */\nexport function writeDocument(document: string, text: string): void {\n copyFileSync(document, `${document}.bak`)\n const temporary = join(dirname(document), `.${basename(document)}.${randomUUID()}.tmp`)\n try {\n writeFileSync(temporary, text, 'utf8')\n renameSync(temporary, document)\n } catch (error) {\n try {\n unlinkSync(temporary)\n } catch {\n // The temporary file was never created, or is already gone.\n }\n throw error\n }\n}\n\n/**\n * URL as the editor sees it: a query string or fragment can carry a credential\n * (`?token=…`), so it is dropped from the panel. A save that leaves the visible\n * URL untouched keeps the declared one, query included.\n * @param url - declared or submitted endpoint.\n * @returns the endpoint without its query string or fragment.\n */\nexport function visibleUrl(url: string): string {\n const index = url.search(/[?#]/)\n return index === -1 ? url : url.slice(0, index)\n}\n\n/** The URL a declaration writes: keep the declared query when unchanged. */\nfunction urlToWrite(submitted: string, declaredUrl: string | undefined): string {\n if (declaredUrl !== undefined && visibleUrl(declaredUrl) === submitted) return declaredUrl\n return submitted\n}\n\n/** The three-way rule of one `env`/`headers` section, applied to one record. */\nfunction fieldsToRecord(\n fields: readonly EntryField[],\n declared: Record<string, string>,\n): Record<string, string> {\n const result: Record<string, string> = {}\n for (const field of fields) {\n const declaredValue = declared[field.key]\n if (field.fromCredentials === true) {\n // Never write an externally answered value: the declared text stays.\n if (declaredValue !== undefined) result[field.key] = declaredValue\n continue\n }\n if (field.value !== undefined) {\n result[field.key] = field.value\n continue\n }\n // No value at all: a masked key keeps what the document declares, so an\n // editor that cannot see a secret can never erase or replace it. A shape\n // with neither `value` nor `masked` has nothing to contribute either, and\n // is kept for the same reason — removal is expressed by omitting the key.\n if (declaredValue !== undefined) result[field.key] = declaredValue\n }\n return result\n}\n\n/** One `env`/`headers` section as entry fields, values masked where needed. */\nfunction entryFields(\n record: unknown,\n credentials: ReadonlySet<string> | undefined,\n): EntryField[] | undefined {\n if (!isRecord(record)) return undefined\n const fields: EntryField[] = []\n for (const [key, value] of Object.entries(record)) {\n if (typeof value !== 'string') return undefined\n if (credentials?.has(key) === true) {\n fields.push({ key, masked: true, fromCredentials: true })\n continue\n }\n // A `${...}` reference is resolved on the host and is not a literal the\n // document holds, so its value is withheld as well.\n if (SECRET_KEY_PATTERN.test(key) || hasReference(value)) {\n fields.push({ key, masked: true })\n continue\n }\n fields.push({ key, value })\n }\n return fields\n}\n\n/**\n * Transport a declaration names, normalized the way `parse.ts` reads it: an\n * explicit `type`/`transport` wins, otherwise the presence of `url` decides.\n */\nfunction declaredTransport(record: Record<string, unknown>): 'stdio' | 'streamable-http' {\n const raw = record.type ?? record.transport\n if (typeof raw === 'string') {\n const normalized = raw.toLowerCase()\n if (normalized === 'stdio') return 'stdio'\n if (normalized === 'http' || normalized === 'streamable-http' || normalized === 'sse') {\n return 'streamable-http'\n }\n }\n return record.url !== undefined ? 'streamable-http' : 'stdio'\n}\n\n/** Flat string map, or `undefined` when the value is not one. */\nfunction stringRecord(value: unknown): Record<string, string> | undefined {\n if (!isRecord(value)) return undefined\n const result: Record<string, string> = {}\n for (const [key, item] of Object.entries(value)) {\n if (typeof item !== 'string') return undefined\n result[key] = item\n }\n return result\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction errorText(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n","/**\n * Project-scoped MCP mounting runtime.\n *\n * Isolation model: every live agent (session) resolves its own working\n * directory to a project root, and the servers declared by that project are\n * mounted **once for the project** inside a Cordis scope minted for it\n * (`createScope(hostCtx, projectKey)`), exactly the pattern the in-box\n * browser-use runtime uses for MCP servers. Each session additionally gets its\n * own scope, parented to its project's (`bindScopeParent(agent, projectKey)`):\n * a session sees its project's layer through the scope chain, which is how one\n * child process serves every session of that project — subagents included —\n * while a session of another project never resolves it. Because mcp-client\n * reserves a `serverName` per registration scope, two projects may declare the\n * same name without a conflict, and the plugin's own teardown disposes every\n * scope it minted: the project scope when its last holder releases it, so a\n * shared instance goes away on exactly the trigger a per-session one did.\n *\n * @module dsh-project-mcp/runtime\n */\n\nimport { readFileSync, statSync, watch } from 'node:fs'\nimport type { FSWatcher } from 'node:fs'\nimport { homedir } from 'node:os'\nimport * as mcpClient from '@deepseek-ai/dsh-mcp-client'\nimport { bindScopeParent, createScope, scopeOf } from '@deepseek-ai/dsh-scope'\nimport type { Scope, ScopeParentBinding } from '@deepseek-ai/dsh-scope'\nimport type { Context } from '@deepseek-ai/cordis'\nimport { ForwardBatch, forwardProjectTools, projectToolNames } from './bridge.ts'\nimport type { BridgeContextLike, BridgeRegistryLike } from './bridge.ts'\nimport {\n DEFAULT_ACTIVATION_ENABLED,\n DEFAULT_ACTIVATION_MIN_CALLS,\n DEFAULT_ACTIVATION_SEEDED,\n DEFAULT_TOOL_BUDGET_CHARS,\n DEFAULT_TOOL_IDLE_MS,\n SEARCH_TOOL_NAME,\n autoPresentedNames,\n createActivationState,\n createAutoOfferState,\n installActivation,\n noteUse,\n overToolBudget,\n presentedNames,\n pruneIdle,\n schemaChars,\n seedFromUsage,\n surfaceChars,\n toolsFor,\n} from './activation.ts'\nimport type {\n ActivationContextLike,\n ActivationState,\n AutoOfferState,\n ToolSchemaLike,\n} from './activation.ts'\nimport {\n configDirectories,\n findProjectRoot,\n globalConfigPaths,\n localConfigPaths,\n projectEnvPaths,\n readEnvFile,\n readSecrets,\n} from './discovery.ts'\nimport {\n DEFAULT_GUIDANCE_ENABLED,\n buildGuidance,\n installGuidance,\n projectLabel,\n} from './guidance.ts'\nimport type { GuidanceContextLike, GuidanceServer } from './guidance.ts'\n// The volatile key list lives at the entry (`src/index.ts`) because the schema\n// declares it; the import cycles back here, but it is read only inside\n// `applyLiveConfig`, long after both modules finished evaluating.\nimport { VOLATILE_CONFIG_KEYS } from './index.ts'\nimport { LOG_PAGE_SIZE, countForSession, countOf, latest } from './logs.ts'\nimport { emitEvent, logConsumer, subscribeEvent } from './notifications.ts'\nimport type { PluginEvent } from './notifications.ts'\nimport {\n SERVER_NAME_PATTERN,\n extractServerMap,\n mergeEntries,\n parseDocument,\n referencesCredentials,\n slugifyServerName,\n} from './parse.ts'\nimport type { ParsedEntry, ParseIssue, ResolveContext } from './parse.ts'\nimport { isValidLocalPrefix, resolveConflictNames } from './naming.ts'\nimport { aliasesOf, isConflictChoice, isToolMode } from './policy.ts'\nimport type { ConflictRequest, PinRequest, PolicyRequest, SaveErrorCode, SaveRequest } from './shared.ts'\nimport { DEFAULT_TOOL_POLICY } from './types.ts'\nimport type {\n ConfiguredFile,\n ConflictChoice,\n EntrySnapshot,\n McpSnapshot,\n ProjectSnapshot,\n PresentationOwner,\n ServerConflict,\n ServerRow,\n ServerStatus,\n ServerUsage,\n SessionSnapshot,\n SessionTools,\n SnapshotChange,\n SnapshotIssue,\n ToolFacts,\n ToolField,\n ToolMode,\n ToolPolicy,\n ToolReason,\n WriteScope,\n} from './types.ts'\nimport { matchServer } from './usage.ts'\nimport {\n applyEntry,\n buildEntrySnapshot,\n documentRevision,\n entryToDeclaration,\n visibleUrl,\n WriteDocError,\n writeDocument,\n writeScopeFor,\n} from './write.ts'\nimport type { CredentialKeys, WriteScopeInfo } from './write.ts'\n\n/** Live agent handle: only the fields this plugin consumes. */\nexport interface AgentLike {\n /** Session id, unique per agent. */\n readonly id: string\n /** Session header carrying the working directory. */\n readonly session: { readonly header?: { readonly cwd?: string } }\n /**\n * Host-reported lifecycle status, when the composition publishes one. Read\n * live where a release decision needs the truth rather than the last event\n * this plugin happened to see.\n */\n readonly status?: 'idle' | 'running'\n /** The agent's own Cordis context. */\n readonly ctx: Context\n}\n\n/** The subset of `ctx.agents` used here. */\nexport interface AgentsLike {\n /** All live agents. */\n list(): AgentLike[]\n}\n\n/** One agent-plane event, as far as this plugin consumes it. */\nexport interface AgentEventLike {\n /** The subject agent. */\n agent: AgentLike\n /** `agent/status` only: whether a turn is currently running. */\n status?: 'idle' | 'running'\n /**\n * `agent/pre-step` only: the model selection this step captured. Read to ask\n * the llm service what the route can do — a hand-declared provider cannot take\n * tool declarations after the first request, and the presentation has to know\n * before it decides how to hide anything.\n */\n modelSelection?: { readonly provider: string; readonly model: string }\n}\n\n/** The subset of the hosting scope used here. */\nexport interface AgentScopeLike {\n /** Agent registry (injected). */\n readonly agents: AgentsLike\n /**\n * Subscribe to an agent lifecycle or turn event. `agent/pre-step` is a\n * waterfall hook, so its handler receives a continuation and must return it.\n */\n on(name: string, handler: (event: AgentEventLike, next: () => Promise<unknown>) => unknown): unknown\n /** Register a fiber-scoped cleanup. */\n effect(fn: () => unknown, label?: string): unknown\n}\n\n/** Resolved plugin configuration. */\nexport interface RuntimeConfig {\n /**\n * Project-relative MCP documents to read, lowest priority first. A spec is\n * relative to the project root, or absolute / `~/…` / `$DSH_HOME/…`.\n */\n localFiles: string[]\n /**\n * Global MCP documents read before a project's own, lowest priority first;\n * `[]` reads none.\n */\n globalFiles: string[]\n /**\n * Read the project's own dotenv documents (`<project>/.env` and\n * `<project>/.dsh/.env`) for `${...}` values.\n */\n envFiles?: boolean\n inputs: Record<string, string>\n projectMarkers: string[]\n fileMarkers: string[]\n toolCallTimeoutMs: number\n failOnStartupError: boolean\n /** Window after which a mount that produced no tool is reported as an error; `0` disables. */\n connectTimeoutMs: number\n /** Mount a session's project on its first turn instead of at session creation. */\n lazy: boolean\n /** Release a session's mounts after this much inactivity; `0` disables. */\n idleTimeoutMs: number\n /** How long the first step of a turn may wait for a pending mount; `0` never waits. */\n activationWaitMs: number\n profileWins: boolean\n /**\n * Local namespace a project entry takes when a profile-level instance already\n * owns its `serverName` and the user chose to see the project's copy too.\n * Empty asks for one derived from the project's own folder\n * (`src/naming.ts`, {@link isValidLocalPrefix}); never longer than five\n * characters, because it is a name a person has to read in front of every\n * tool of that server.\n */\n localPrefix: string\n watch: boolean\n debounceMs: number\n rescanIntervalMs: number\n credentialsFile: string\n /**\n * Offer the session's MCP tools through `mcp_search_tools` + activation, and\n * put the active ones back into each assembled request. Optional so a config\n * object that predates this feature keeps the shipped default.\n */\n activationEnabled?: boolean\n /** Total tools the durable counters may seed into the baseline; `0` seeds none. */\n activationSeeded?: number\n /** Calls one tool needs in the counters before it is seeded into the baseline. */\n activationMinCalls?: number\n /** Drop a session-activated tool after this long without a call; `0` disables. */\n toolIdleMs?: number\n /**\n * Publish one short project-MCP guidance section in the session's system\n * prompt, just ahead of the per-server `mcp:<server>` instruction blocks.\n * `false` registers no section at all. Optional so a config object that\n * predates this feature keeps the shipped default.\n */\n guidanceEnabled?: boolean\n /**\n * Cap on the names the context-driven tier offers at once; `0` disables the\n * tier. Optional so a config object that predates this feature keeps the\n * shipped default.\n */\n activationAutoLimit?: number\n /** Extra advances one context-driven offer survives after leaving the ranking. */\n activationAutoStickySteps?: number\n /**\n * Serialized size of a session's MCP surface, in characters, above which its\n * tools are offered on demand instead of being listed; `0` defers every\n * surface, however small.\n */\n activationToolBudgetChars?: number\n /**\n * Permit writes to the documents of the `globalFiles` list. Off by default:\n * a global write needs both this switch and an explicit per-write `consent`,\n * so a panel mistake cannot rewrite every project's servers. Optional so a\n * config object that predates this feature keeps it disabled.\n */\n allowGlobalWrite?: boolean\n}\n\n/**\n * Outcome of {@link ProjectMcpRuntime.saveEntry}: the fresh snapshot after a\n * write, or the code the route maps to a status.\n */\nexport type SaveOutcome =\n | { readonly ok: true; readonly snapshot: McpSnapshot }\n | {\n readonly ok: false\n readonly code: SaveErrorCode\n readonly message: string\n /**\n * Stable wire code of `message` (`projectMcp.host` namespace), for\n * client-side translation (F-48); the prose `message` keeps its\n * byte-identical English and stays the fallback.\n */\n readonly messageCode?: string\n /** Flat params of {@link messageCode}, stringified at emission. */\n readonly messageParams?: Record<string, string>\n }\n\n/**\n * Outcome of {@link ProjectMcpRuntime.setPin} and\n * {@link ProjectMcpRuntime.setPolicy}: the fresh snapshot after the store was\n * changed, or the code the route maps to a status. Both refusals are `400`s:\n * `not-found` for a project this host has no live session in, `invalid` for a\n * mode no assembly knows, `failed` when the host was built without a policy\n * store.\n */\nexport type PolicyOutcome =\n | { readonly ok: true; readonly snapshot: McpSnapshot }\n | {\n readonly ok: false\n readonly code: SaveErrorCode\n readonly message: string\n /** Wire code of `message`, the same contract as {@link SaveOutcome}'s. */\n readonly messageCode?: string\n /** Flat params of {@link messageCode}, stringified at emission. */\n readonly messageParams?: Record<string, string>\n }\n\n/**\n * Outcome of {@link ProjectMcpRuntime.toolFactsOf}: one tool's on-demand detail,\n * or the code the route maps to a status.\n *\n * A refusal is a `404`: the route only asks about a project root, a session id\n * and a name a panel read from a snapshot, so one this host does not know is a\n * stale read rather than a malformed request — the three parameters themselves\n * are checked by the route. The prose stays plain English and uncoded, the way\n * `GET logs` refuses.\n */\nexport type ToolFactsOutcome =\n | { readonly ok: true; readonly value: ToolFacts }\n | { readonly ok: false; readonly code: SaveErrorCode; readonly message: string }\n\n/**\n * Identity of the Cordis scope one project's servers are mounted in. Every\n * session of that project is parented to it, so the registrations inside are\n * visible to those sessions and to nobody else.\n */\nexport interface ProjectScopeKey {\n /** Project root whose sessions share this scope. */\n readonly projectRoot: string\n}\n\n/**\n * Whether one scope key names a project's shared registrations rather than a\n * session. A host that models scopes (a test double, a diagnostic) can tell the\n * two apart without the object identity the runtime keeps to itself.\n * @param key - key handed to {@link RuntimeOptions.createScope}.\n * @returns `true` when the key is a {@link ProjectScopeKey}.\n */\nexport function isProjectScopeKey(key: unknown): key is ProjectScopeKey {\n return isRecord(key) && typeof (key as { projectRoot?: unknown }).projectRoot === 'string'\n}\n\n/** Injection points that tests override; production uses the real defaults. */\nexport interface RuntimeOptions {\n /** Plugin object mounted per server; defaults to `@deepseek-ai/dsh-mcp-client`. */\n plugin?: unknown\n /**\n * Scope factory; defaults to `createScope` from `@deepseek-ai/dsh-scope`.\n * Called once per session and once per project that mounts something. The\n * parent link of a session scope is established by the runtime itself, before\n * this is called — the factory only mints the scope. A session key is the\n * agent's own scope key; a project key is a {@link ProjectScopeKey}.\n */\n createScope?: (ctx: Context, key: AgentLike | ProjectScopeKey) => Pick<Scope, 'ctx' | 'dispose'>\n /**\n * Registry surface the forwarding bridge reads: one scoped lookup. It is read\n * off the plugin's own context by default, which is the same `ctx.tools` the\n * registration path uses; tests override it with their double's registry.\n */\n registry?: BridgeRegistryLike\n /**\n * Bridge context factory; defaults to reading the scope tag\n * ({@link scopeOf}) from the minted scope's context and wiring the registry\n * getter to it. A test whose scope double is a plain object overrides this,\n * because its contexts carry no `dsh-scope` tag to read.\n */\n bridgeContext?: (scope: Pick<Scope, 'ctx' | 'dispose'>) => BridgeContextLike\n /** Durable counters `snapshot()` publishes alongside the rows; absent means none. */\n usage?: UsageSource\n /**\n * Durable per-project policy the snapshot publishes and the assembly reads;\n * absent means every project keeps {@link DEFAULT_TOOL_POLICY}.\n */\n policy?: PolicySource\n}\n\n/** Read-only view of the durable counters, consulted by {@link ProjectMcpRuntime.snapshot}. */\nexport interface UsageSource {\n /** Counters recorded for one project root, or `undefined` when it has none. */\n forProject(projectRoot: string): Record<string, ServerUsage> | undefined\n}\n\n/**\n * The durable policy as the runtime consumes it: read on every snapshot and\n * every assembly, written by the two panel service methods. Structural on\n * purpose, so a test can pass a plain object and the plugin does not depend on\n * the store class.\n */\nexport interface PolicySource {\n /** Policy of one project root; the shipped default when none is stored. */\n forProject(projectRoot: string): ToolPolicy\n /** Store one project's mode and return the policy now in force. */\n setMode(projectRoot: string, mode: ToolMode): ToolPolicy\n /** Pin or unpin one tool of one project and return the policy now in force. */\n setPin(projectRoot: string, tool: string, pinned: boolean): ToolPolicy\n /**\n * Store which declaration of one contested `serverName` the project shows and\n * return the policy now in force.\n */\n setConflictChoice(\n projectRoot: string,\n server: string,\n choice: ConflictChoice,\n ): ToolPolicy\n}\n\n/**\n * What this plugin currently mounts for one live agent: the project root the\n * agent resolved to and the server names it mounted there.\n */\nexport interface AgentMounts {\n /** Project root the agent's working directory resolved to. */\n projectRoot: string\n /** Names of the servers this plugin mounted for that agent right now. */\n servers: ReadonlySet<string>\n}\n\n/** Minimal fiber surface used for mount bookkeeping. */\ninterface MountFiber {\n dispose(): unknown\n await?(): Promise<unknown>\n}\n\n/** Result of a bounded wait on a fiber operation. */\ntype WaitOutcome<T> =\n | { kind: 'settled'; value: T }\n | { kind: 'failed'; error: unknown }\n | { kind: 'timeout' }\n\n/** Cordis fiber states (mirrors `@deepseek-ai/cordis`). */\nconst FIBER_ACTIVE = 2\n\n/** Plugin names that identify a profile-level mcp-client registration. */\nconst MCP_CLIENT_ENTRY_NAMES = new Set(['@deepseek-ai/dsh-mcp-client', 'dsh-mcp-client'])\n\n/**\n * Entry names that identify a second owner of the assembled tool list.\n *\n * Matched the way {@link MCP_CLIENT_ENTRY_NAMES} is: by the module specifier the\n * loader entry imports. A loader entry's `options.name` names a module, not a\n * capability, so a check that did not name the known owners could not tell a\n * presentation plugin from a logging one. The scoped spelling is included\n * because that is how a published plugin is mounted in a profile.\n */\nconst PRESENTATION_OWNER_ENTRY_NAMES = new Set([\n '@deepseek-ai/dsh-progressive-tools',\n 'dsh-progressive-tools',\n])\n\n/**\n * Why this plugin and another presentation owner cannot shape one request.\n *\n * One explanation for every owner, not one per artifact: the reason is about\n * the plumbing (`assembly.tools` waterfall, outer listener wins) and not about\n * what the other plugin is called. Short because a panel prints it in a single\n * line under the tools list.\n */\nconst PRESENTATION_OWNER_NOTE =\n 'a second presentation owner rewrites assembly.tools after this plugin does, so the two never combine in one request: either this plugin shapes only its own mcp__* entries, or the other owner is unmounted.'\n\n/**\n * Host prose plus its wire code (F-48): the English sentence, byte-identical\n * to what the site emitted before codes existed, and the `projectMcp.host`\n * code the client translates by. The two travel as one value so a call site\n * cannot reword the prose without touching the code, and so a reason passed\n * down a call chain (`detach` → `releaseProject` → `unmount`) keeps its code.\n */\ninterface CodedText {\n /** The English sentence, as it always read. */\n readonly text: string\n /** The dotted wire code, into the client's `projectMcp.host` namespace. */\n readonly code: string\n /** Flat params of the code, when it has any; numbers stringify here. */\n readonly params?: Record<string, string>\n}\n\n/** `detail` of a declared server that `lazy` has not mounted yet. */\nconst LAZY_DETAIL: CodedText = {\n code: 'idle.lazy',\n text: 'not mounted yet — this session has not started a turn (lazy mounting is on)',\n}\n\n/** Why one pass may start a project's servers for one session. */\nexport type MountTrigger = 'turn' | 'mounted' | 'eager' | 'operator'\n\n/** What one session contributes to the mount decision of one pass. */\nexport interface MountDecision {\n /** Whether `lazy` is on: without it a session mounts as soon as it exists. */\n lazy: boolean\n /** This session's own turn asked for its project (a pre-step or a `running` status). */\n activationPending: boolean\n /** This session already holds mounts, so a pass reconciles them live. */\n mounted: boolean\n /** An operator asked for exactly this session (`syncNow`, `retry`, an edit). */\n operatorRequested: boolean\n}\n\n/**\n * Sessions one pass may mount without their own turn asking: `'all'` for an\n * operator call that reconciles every session, a set of session ids for a pass\n * that belongs to one project, the project root itself for an operator call\n * scoped to a project — matched while the pass runs, so it also covers a session\n * whose working directory has not been read yet — and no requests at all for a\n * pass driven by a turn, an event or the rescan tick.\n */\nexport type PassRequests = 'all' | ReadonlySet<string> | { readonly projectRoot: string }\n\n/** The pass a turn, an event or the rescan tick runs: every session must ask. */\nconst NO_REQUESTS: PassRequests = new Set()\n\n/**\n * Decide whether one pass may start servers for one session, and why.\n *\n * The plugin's isolation rule lives here: a session starts the servers of the\n * project its working directory resolves to only when *that* session asks to\n * work there — its own turn, an operator request that names it, or a\n * deployment that turned `lazy` off. A session that is merely live (restored,\n * listed, idle, or another session's neighbour) never starts anything, and a\n * session that already holds mounts is reconciled so edits reach them.\n * @param decision - what one session contributes to one pass.\n * @returns the trigger, or `undefined` when the session must stay idle.\n */\nexport function mountTrigger(decision: MountDecision): MountTrigger | undefined {\n if (decision.operatorRequested) return 'operator'\n if (decision.activationPending) return 'turn'\n if (decision.mounted) return 'mounted'\n if (!decision.lazy) return 'eager'\n return undefined\n}\n\n/**\n * Run the parsed config through mcp-client's own Schemastery schema, exactly as\n * the in-box precedent does (`ctx.plugin(McpClient, McpClient.Config({...}))`):\n * this fills `maxInstructionBytes`/`reconnect` defaults and fails loudly on a\n * config the client would reject. A plugin without a callable `Config` keeps\n * the raw value.\n */\nfunction clientConfig(value: unknown): unknown {\n const schema = (mcpClient as { Config?: (input: unknown) => unknown }).Config\n return typeof schema === 'function' ? schema(value) : value\n}\n\ninterface LoaderEntryLike {\n options?: {\n id?: unknown\n name?: unknown\n config?: { serverName?: unknown }\n disabled?: unknown\n }\n fiber?: { state?: unknown }\n}\n\ninterface LoaderLike {\n entries?(): LoaderEntryLike[]\n}\n\ninterface MountedInstance {\n name: string\n /**\n * The `serverName` this mount actually registers under: the declared name, or\n * the local alias when a profile instance owns the declared one. It is what\n * the registry prefixes this server's tools with, so every lookup that goes by\n * tool prefix — status, guidance, the activation baseline — reads this and\n * never {@link name}.\n */\n runtimeName: string\n /** Project root whose declaration this instance was mounted from. */\n projectRoot: string\n fingerprint: string\n fiber: MountFiber | undefined\n status: ServerStatus\n detail: string | undefined\n /** Wire companions of {@link MountedInstance.detail} (F-48), set with it. */\n detailCode: string | undefined\n detailParams: Record<string, string> | undefined\n source: string | undefined\n transport: 'stdio' | 'streamable-http' | undefined\n /** Endpoint label already stripped of arguments and query strings. */\n endpoint: string\n /** When this mount started, for the connect watchdog. */\n startedAt: number\n /** `true` once the watchdog has reported the mount as never connected. */\n stalled: boolean\n /** `true` when activation itself failed, so no retry can revive this fiber. */\n failed: boolean\n}\n\n/**\n * The forwarding bridge one session holds when its key could not be joined to\n * its project's chain: the thin definitions registered in the session's own\n * layer, and the subscription that keeps them level with the project's live\n * tool set.\n */\ninterface BridgeForwarders {\n /**\n * The session's live registration batch. It owns the swap and the re-entrancy\n * every registration forces on it (`tools/change` is emitted from inside the\n * insertion, and the session is subscribed to it).\n */\n readonly batch: ForwardBatch\n /** Disposer of the project-scope `tools/change` subscription. */\n detach: () => void\n}\n\n/**\n * Where one session's MCP instances live — one home per project, forever.\n *\n * A session whose scope key could be parented to its project resolves the\n * project's shared home directly: one scope and one process per declared\n * server, shared by every session that works there. A session whose key the\n * harness already parented to something else cannot join that chain —\n * `dsh-scope` binds a key once, and the agent-preset roster binds every\n * composed agent before it is published — so it holds the SAME project home and\n * reads it through the forwarding bridge: a thin definition in its own layer\n * whose call runs the project's own. That is what makes \"one process per\n * project\" true in a preset composition too, instead of one instance per\n * session. See `docs/design/contracts/bridge.md`.\n */\ninterface MountHome {\n /** The project root whose declarations this home serves. */\n projectRoot: string\n /** Scope key the mcp-client instances are mounted under. */\n key: AgentLike | ProjectScopeKey\n /** The scope those instances live in; `undefined` before the first mount. */\n scope: Pick<Scope, 'ctx' | 'dispose'> | undefined\n /** One live instance per declared `serverName`. */\n mounts: Map<string, MountedInstance>\n /** `true` when every session of the project shares this home. */\n shared: boolean\n}\n\n/**\n * One project's shared mount state: the scope its sessions' servers are\n * registered in, and the live mounts those sessions share. The scope is minted\n * with the project's first mount and dropped with its last holder, so a project\n * costs one scope and one process per declared server however many sessions\n * work in it.\n */\ninterface ProjectState extends MountHome {\n projectRoot: string\n /** Scope key the project's registrations are tagged with. */\n key: ProjectScopeKey\n /** The project scope; `undefined` before the first mount and after teardown. */\n scope: Pick<Scope, 'ctx' | 'dispose'> | undefined\n /** One live instance per declared `serverName`, shared by every holder. */\n mounts: Map<string, MountedInstance>\n shared: true\n}\n\n/** No mounts: what a session that holds none sees. */\nconst NO_MOUNTS: ReadonlyMap<string, MountedInstance> = new Map()\n\n/**\n * Parent links minted for session scope keys, kept process-wide because the\n * relation they feed (`bindScopeParent`) is process-wide too: a second runtime\n * in one process reuses the handle the first bound instead of failing on a key\n * that is already linked.\n */\nconst parentBindings = new WeakMap<object, ScopeParentBinding>()\n\n/**\n * Point one scope key at the scope key it may resolve layers from, and keep the\n * binding that alone may re-link it later.\n *\n * This link is the mechanism that makes a project's shared servers visible to\n * exactly its sessions: the tools registry and the prompt assembly resolve a\n * session's catalog by walking `scopeChainOf(agentKey)`, so a project layer is\n * reachable only from a key parented to it. Re-linking is what a project change\n * and a release need, which is why the binding is retained rather than passed\n * to {@link createScope} and forgotten: the dsh-scope contract for a re-link\n * holds here — the runtime disposes the session scope and drops every\n * registration produced under the old parent before pointing the key\n * elsewhere.\n *\n * Reports who owns the resulting link: `true` when this runtime just created it\n * or already owns the key's binding, `false` when another composition parented\n * the key first — in which case the link is left untouched and the caller takes\n * the forwarding bridge instead of silently moving a binding it does not own.\n *\n * @param key - scope key to link.\n * @param parent - the key whose registrations the linked key may see.\n * @returns whether this runtime now owns the link.\n */\nfunction linkScopeParent(key: object, parent: object): boolean {\n const bound = parentBindings.get(key)\n if (bound !== undefined) {\n bound.rebind(parent)\n return true\n }\n try {\n parentBindings.set(key, bindScopeParent(key, parent))\n return true\n } catch {\n return false\n }\n}\n\ninterface AgentState {\n agent: AgentLike\n cwd: string | undefined\n projectRoot: string | undefined\n /**\n * Digest of the last reconciled pass: the document set, the profile\n * reservations, and the published state of the shared mounts. Identical means\n * \"nothing to do\" — including when another session of the same project\n * mounted, settled or dropped something this session would otherwise render\n * from a stale row.\n */\n digest: string | undefined\n scope: Pick<Scope, 'ctx' | 'dispose'> | undefined\n /**\n * The project whose shared mounts this session currently holds; `undefined`\n * while it holds none. Every holder resolves the one home, whether its own key\n * joined the project's chain or the bridge carries the tools to it.\n */\n project: ProjectState | undefined\n /**\n * The forwarding bridge this session holds when its key could not be parented\n * to its project (the harness bound that key first, and `dsh-scope` binds a\n * key once). `undefined` for a session whose own chain already resolves the\n * project's layer, which needs no bridge.\n */\n bridge: BridgeForwarders | undefined\n /**\n * Whether {@link linkScopeParent} linked this session's key, so a detach knows\n * it owns the re-link and not another plugin that parented the same key.\n */\n parentLinked: boolean\n /**\n * Layer-less scope key a released session is re-linked to. Without it a\n * session that let a project's servers go would keep resolving them from the\n * still-running shared layer — the one thing per-session mounting gave for\n * free, because disposing the session scope removed its whole chain.\n */\n detachedKey: object | undefined\n rows: ServerRow[]\n issues: SnapshotIssue[]\n /**\n * `serverName` conflicts of the last reconciled pass: a profile-level\n * instance that already owns a name, or one name two project documents\n * declare. Always the truth of that pass — an empty list is the answer \"no\n * conflicts\", not an absent one.\n */\n conflicts: ServerConflict[]\n /** Last observed activity (turn start, step, turn end); `undefined` until then. */\n lastActivityAt: number | undefined\n /** `true` while a turn runs, so idle release never fires in the middle of one. */\n busy: boolean\n /**\n * Set when a turn starts while nothing is mounted, so the next pass mounts\n * the project even in `lazy` mode. Cleared by the pass that mounts it.\n */\n activationPending: boolean\n /**\n * Session activation state (counter baseline + session-activated names).\n * `undefined` until the session's first scope is minted and seeds it; kept\n * across an idle release so the session keeps what it activated.\n */\n activation: ActivationState | undefined\n /**\n * Number of the agent step this session is on, counted from `agent/pre-step`\n * and starting at `1` for the first step the hook sees. `0` means no step has\n * started yet, and then no offer carries a number.\n */\n step: number\n /**\n * Step each session activation was recorded on, keyed by public name. Kept\n * next to {@link AgentState.activation} because the two outlive an idle\n * release together: the activation is what a row lists, and this is when it\n * was offered. Pruned with the activation it belongs to.\n */\n steps: Map<string, number>\n /**\n * Disposer of the activation wiring installed on the current scope. Kept so a\n * scope teardown unregisters `mcp_search_tools` explicitly: the scope fiber\n * owns that registration with the real registry, but a test host may publish a\n * plain `tools` stub, and the tool must disappear either way.\n */\n activationDispose: (() => void) | undefined\n /**\n * Disposer of the guidance-section wiring installed on the current scope. Kept\n * for the same reason as {@link AgentState.activationDispose}: the scope fiber\n * owns the registration with the real prompt registry, but a host that\n * publishes a plain `systemPrompt` stub has only this path.\n */\n guidanceDispose: (() => void) | undefined\n /**\n * Context-driven offer window (BM25 task ranking + sticky names). Kept next\n * to `activation` so a re-minted scope of the same session resumes the offers\n * it was showing instead of starting over — the same reason the activation\n * state outlives an idle release.\n */\n auto: AutoOfferState | undefined\n /**\n * Identity of the model route the last resolved {@link AgentState.toolUpdate}\n * belongs to, as `provider/model`. A selection change re-asks the llm service\n * and nothing else does, so a session keeps one answer per route.\n */\n routeKey: string | undefined\n /**\n * Whether this session's route accepts tool declarations after its first\n * request (`LlmResolvedModelInfo.toolUpdate`), read from the llm service on\n * `agent/pre-step`.\n *\n * `undefined` until a route is resolved. `true` lets the presentation hide a\n * tool behind `deferLoading` — declared, invisible, still callable. `false`\n * means the harness sends the whole declaration list in the first request of\n * every series, so a deferred tool is not hidden at all: it costs its schema\n * and the presentation must not declare it, which is what makes its name\n * reachable only through the discovery tool. The difference is the difference\n * between \"hidden but callable\" and \"not there\", and only the route decides\n * which one is even possible.\n */\n toolUpdate: boolean | undefined\n}\n\ninterface CachedDocument {\n mtimeMs: number\n size: number\n /** Exact bytes the parse was made from; the write path revises them. */\n text: string\n /**\n * Identity of the value sources the parse expanded `${...}` against. A\n * document whose own bytes did not move is still re-parsed when its sources\n * did, so an edit to a project `.env` or to the credentials file reaches the\n * mounts without `mcp.json` being touched at all.\n */\n stamp: string\n /** Raw `name -> entry` map the document declared, when it held one. */\n raw: Record<string, unknown> | undefined\n entries: ParsedEntry[]\n issues: ParseIssue[]\n}\n\n/** Everything the editor needs from one declaring document, per server name. */\ninterface DocumentInfo extends WriteScopeInfo {\n /** Content revision of the document at snapshot time. */\n revision: string\n /** Entry body per sanitized `serverName`, for the entries that parsed. */\n entries: Map<string, EntrySnapshot>\n}\n\n/**\n * Owns every project-scoped mount, the config watchers, and the rescan timer.\n * One instance per plugin fiber; `attach()` binds it to the agent service.\n */\nexport class ProjectMcpRuntime {\n private readonly states = new Map<string, AgentState>()\n /** Projects with a live shared scope, keyed by project root. */\n private readonly projects = new Map<string, ProjectState>()\n private readonly documents = new Map<string, CachedDocument>()\n /** Cached credentials document, re-read only when mtime/size change. */\n private secrets: { mtimeMs: number; size: number; values: Record<string, string> } | undefined\n /**\n * Dotenv values per project document, re-read only when mtime/size change.\n * Every pass of every session resolves `${...}` references, so an uncached\n * read here would cost one stat plus parse per file per session per pass.\n */\n private readonly envFiles = new Map<\n string,\n { mtimeMs: number; size: number; values: Record<string, string> }\n >()\n private readonly watchers = new Map<string, FSWatcher[]>()\n /** Config directories currently watched per project root. */\n private readonly watchedDirs = new Map<string, WatchTarget[]>()\n private readonly watchedRoots = new Set<string>()\n private timer: ReturnType<typeof setInterval> | undefined\n private debounce: ReturnType<typeof setTimeout> | undefined\n private chain: Promise<void> = Promise.resolve()\n /** The host's live-session registry, once `attach()` has bound one. */\n private listAgents: (() => AgentLike[]) | undefined\n /** `undefined` until a recursive watch has been attempted. */\n private recursiveWatch: boolean | undefined = undefined\n private ready = false\n private disposed = false\n /** Panels watching the picture through the status channel. */\n private readonly listeners = new Set<(change: SnapshotChange) => void>()\n /** Changes announced so far; the picture a stream opens on is revision `0`. */\n private revision = 0\n /** JSON of the last announced picture, so an unchanged pass announces nothing. */\n private announced: string | undefined\n /**\n * Disposer of the DSH-log subscriber this runtime installs on the notification\n * service in {@link ProjectMcpRuntime.attach}. One subscription per live\n * runtime, dropped in {@link ProjectMcpRuntime.disposeAll}, so a re-mount\n * cannot leave a second logger reading the same events.\n */\n private detachLog: (() => void) | undefined\n\n /**\n * @param ctx - the plugin's own context (host/root scope).\n * @param config - resolved plugin configuration.\n * @param options - mount overrides (tests only).\n */\n constructor(\n private readonly ctx: Context,\n private readonly config: RuntimeConfig,\n private readonly options: RuntimeOptions = {},\n ) {}\n\n /** Bind to the agent service: existing agents, lifecycle events, rescan timer. */\n attach(scope: AgentScopeLike): void {\n this.ready = true\n // The DSH log is a consumer of the notification service, not a second write\n // path: this runtime's own logger subscribes here, once, and is told every\n // event the runtime publishes.\n this.detachLog ??= subscribeEvent(logConsumer(this.ctx.logger))\n this.listAgents = () => scope.agents.list()\n scope.on('agent/created', ({ agent }) => {\n if (this.disposed) return\n this.states.set(agent.id, this.newState(agent))\n // The scope is owned by this plugin, but the agent may also be disposed\n // without a matching event reaching us first; this keeps teardown ordered.\n agent.ctx.effect(\n () => () => {\n this.dropAgent(agent.id)\n },\n 'project-mcp: session',\n )\n this.schedule('agent/created')\n })\n scope.on('agent/disposed', ({ agent }) => {\n if (this.disposed) return\n this.dropAgent(agent.id)\n })\n scope.on('agent/status', (event) => {\n this.onStatus(event)\n })\n scope.on('agent/pre-step', (event, next) => this.onPreStep(event, next))\n for (const agent of scope.agents.list()) this.states.set(agent.id, this.newState(agent))\n scope.effect(\n () => () => {\n void this.disposeAll()\n },\n 'project-mcp: lifecycle',\n )\n // The safety-net tick also drives idle release, so it runs whenever either\n // of the two needs it.\n if (this.config.watch || this.config.idleTimeoutMs > 0) {\n this.timer = setInterval(() => this.schedule('rescan'), this.config.rescanIntervalMs)\n // A rescan timer must not keep a headless DSH process alive on its own.\n this.timer.unref?.()\n }\n this.schedule('attach')\n }\n\n /**\n * Merge one live-edited config into the running one.\n *\n * A DSH ≥ 0.1.7 host serves the volatile config keys as a profile-backed\n * form and re-resolves them on `loader/volatile-update` instead of\n * restarting the entry. Only those keys are taken from `next` — every other\n * key (documents, markers, credentials, the watch switch) stays whatever the\n * entry booted with, because nothing here re-reads it safely at runtime.\n * All volatile keys are consumed at use time, so the merge alone moves the\n * behavior.\n *\n * The one exception is the safety-net tick: it is armed once in\n * {@link ProjectMcpRuntime.attach}, yet its need — `watch || idleTimeoutMs\n * > 0` — flips with a live edit of `idleTimeoutMs`, so it is re-armed or\n * cleared here. Arming is reserved to an attached runtime: before\n * `attach()` the merge alone is enough, because `attach()` arms from the\n * merged values; after disposal nothing may come back.\n *\n * @param next - the freshly resolved config; only the volatile keys are read.\n */\n applyLiveConfig(next: RuntimeConfig): void {\n const target = this.config as Record<keyof RuntimeConfig, unknown>\n for (const key of VOLATILE_CONFIG_KEYS) {\n const value = next[key]\n if (value !== undefined) target[key] = value\n }\n if (this.timer !== undefined && !this.config.watch && this.config.idleTimeoutMs === 0) {\n clearInterval(this.timer)\n this.timer = undefined\n } else if (\n this.timer === undefined &&\n this.ready &&\n !this.disposed &&\n (this.config.watch || this.config.idleTimeoutMs > 0)\n ) {\n this.timer = setInterval(() => this.schedule('rescan'), this.config.rescanIntervalMs)\n // A rescan timer must not keep a headless DSH process alive on its own.\n this.timer.unref?.()\n }\n }\n\n /**\n * Current snapshot: projects with live agents, their rows, and watched roots.\n *\n * Each project carries both a merge and the per-session split. The merge is\n * deliberately not \"first session wins\": sessions of one project mount\n * independently, so the same server can be mounted for one and idle for\n * another, and the panel must not report a running server as idle (or hide a\n * failing one) just because the idle session was registered first.\n *\n * A session that mounted tools also carries what it offers the model right\n * now (see {@link sessionTools}); the row is derived per call, never stored,\n * so a panel that polls after an activation sees it.\n */\n snapshot(): McpSnapshot {\n const byProject = new Map<string, ProjectSnapshot>()\n for (const state of this.states.values()) {\n if (state.projectRoot === undefined) continue\n let project = byProject.get(state.projectRoot)\n if (project === undefined) {\n project = { projectRoot: state.projectRoot, sessionIds: [], rows: [], issues: [], sessions: [], conflicts: [] }\n byProject.set(state.projectRoot, project)\n }\n project.sessionIds.push(state.agent.id)\n project.sessions.push(this.sessionSnapshot(state, state.projectRoot))\n mergeRows(project.rows, this.liveRows(state))\n for (const issue of state.issues) {\n if (!project.issues.some((existing) => existing.message === issue.message)) {\n project.issues.push(issue)\n }\n }\n // Conflicts merge exactly like issues do: every session of one root reads\n // the same documents and the same profile, so one name gets one report and\n // the first session to name it keeps it. The list is published even when\n // empty — that is the panel's \"no conflicts\", not a field it guesses about.\n if (state.conflicts.length > 0) {\n const merged: ServerConflict[] = [...(project.conflicts ?? [])]\n for (const conflict of state.conflicts) {\n if (!merged.some((existing) => existing.server === conflict.server)) merged.push(conflict)\n }\n // Code-unit order, the rule the rest of the plugin sorts names by, so a\n // project of two sessions reports one stable list.\n merged.sort((left, right) =>\n left.server < right.server ? -1 : left.server > right.server ? 1 : 0,\n )\n project.conflicts = merged\n }\n }\n // Counters outlive the sessions that produced them, so they are read from\n // the durable store instead of accumulated per session. The policy is\n // published for every project, stored or not: the panel reads a project's\n // mode and pins from here, and an absent field is meant for a host older\n // than the policy store rather than for a project that never changed one.\n for (const project of byProject.values()) {\n const usage = this.options.usage?.forProject(project.projectRoot)\n if (usage !== undefined) project.usage = usage\n project.policy = this.policyFor(project.projectRoot)\n // Which documents this project reads is a config fact, not a row fact, and\n // the panel needs it to number a row's priority: publish it per project so\n // the number matches the read order of this deployment.\n project.files = this.readFiles(project.projectRoot)\n // The tab is drawn from the snapshot, so the newest page rides here and the\n // ring's size says how much more the route can page. A project that never\n // recorded an event carries neither field — no empty array.\n const logs = latest(project.projectRoot, LOG_PAGE_SIZE)\n if (logs.length > 0) {\n project.logs = logs\n project.logCount = countOf(project.projectRoot)\n }\n }\n // A second presentation owner belongs to the loaded profile, not to one\n // project, so the scan runs once per snapshot and the record rides every\n // project. Absent means this plugin assembles alone, which is what keeps a\n // panel from drawing a coexistence notice that is not true.\n const presentation = this.presentationOwner()\n if (presentation !== undefined) {\n for (const project of byProject.values()) project.presentation = presentation\n }\n return {\n ready: this.ready,\n projects: [...byProject.values()],\n sources: { local: [...this.config.localFiles], global: [...this.config.globalFiles] },\n watchedFiles: [...this.watchedRoots],\n }\n }\n\n /**\n * Watch the picture instead of asking for it: the listener is told the current\n * state at once, then once per change that actually changes something — a pass\n * that committed, a mount that appeared or connected, a release, a save, a\n * policy write. A rescan that found the same servers announces nothing, so an\n * open panel receives no traffic for a project nothing is happening in.\n * @param listener - told the revision and the whole snapshot it belongs to.\n * @returns a disposer that stops watching.\n */\n subscribe(listener: (change: SnapshotChange) => void): () => void {\n this.listeners.add(listener)\n try {\n listener({ revision: this.revision, snapshot: this.snapshot() })\n } catch (error) {\n this.ctx.logger.warn(`project-mcp: announcing the first snapshot failed: ${errorText(error)}`)\n }\n return () => {\n this.listeners.delete(listener)\n }\n }\n\n /**\n * Announce the picture if it differs from the last one announced.\n *\n * The comparison is what keeps the status channel quiet: a pass runs on every\n * watcher event and every rescan tick, and almost all of them re-derive the\n * same rows. With no listener attached nothing is built at all — a headless\n * host pays nothing for a channel nobody reads.\n */\n private notify(): void {\n if (this.listeners.size === 0 || this.disposed) return\n const snapshot = this.snapshot()\n const digest = JSON.stringify(snapshot)\n if (digest === this.announced) return\n this.announced = digest\n this.revision += 1\n const change: SnapshotChange = { revision: this.revision, snapshot }\n for (const listener of [...this.listeners]) {\n try {\n listener(change)\n } catch (error) {\n this.ctx.logger.warn(`project-mcp: announcing a change failed: ${errorText(error)}`)\n }\n }\n }\n\n /**\n * One session's snapshot row, carrying its live tool presentation only when\n * the host has mounted tools for it, and how much of the project's log history\n * belongs to it when there is any.\n * @param state - the session's own runtime state.\n * @param projectRoot - the project the session works in.\n * @returns the row; `tools` stays absent for an unmounted session, and\n * `logCount` for a session that recorded nothing.\n */\n private sessionSnapshot(state: AgentState, projectRoot: string): SessionSnapshot {\n const session: SessionSnapshot = {\n id: state.agent.id,\n rows: this.liveRows(state),\n issues: state.issues,\n }\n const tools = this.sessionTools(state)\n if (tools !== undefined) session.tools = tools\n const logCount = countForSession(projectRoot, state.agent.id)\n if (logCount > 0) session.logCount = logCount\n session.conflicts = state.conflicts\n return session\n }\n\n /**\n * What one session offers the model, measured from its live state at call\n * time.\n *\n * The mounted set is the whole visible MCP surface — this plugin's project\n * mounts plus the profile plane and any F-19 forwarders — the same surface\n * the activation wiring measures against the budget, so the counts cannot\n * describe a different catalog than the one the request is built from. Total\n * on purpose: a probe that fails leaves the row out and warns instead of\n * failing the snapshot.\n * @param state - the session's own runtime state.\n * @returns the presentation row, or `undefined` when nothing is mounted.\n */\n private sessionTools(state: AgentState): SessionTools | undefined {\n try {\n const mounted = this.visibleSchemas(state)\n if (mounted.length === 0) return undefined\n const activationEnabled = this.config.activationEnabled ?? DEFAULT_ACTIVATION_ENABLED\n return toolsFor({\n sessionId: state.agent.id,\n mounted,\n activation: activationEnabled ? this.seedActivation(state) : state.activation,\n auto: state.auto,\n activationEnabled,\n policy: this.policyFor(state.projectRoot),\n steps: state.steps,\n ...(state.step === 0 ? {} : { step: state.step }),\n ...(this.config.activationToolBudgetChars === undefined\n ? {}\n : { budgetChars: this.config.activationToolBudgetChars }),\n })\n } catch (error) {\n this.ctx.logger.warn(\n `project-mcp: reading the tool presentation of session ${state.agent.id} failed: ${errorText(error)}`,\n )\n return undefined\n }\n }\n\n /**\n * One tool's on-demand detail, answered for a row a panel opened.\n *\n * A read, never a rescan: the definition comes from the same mount home the\n * snapshot's session row was measured from, so a **deferred** name answers\n * exactly like an offered one — the home's catalog carries the whole mounted\n * surface, and only the request's own deferral decision leaves a name out of\n * it. That is also what makes the reason honest: `budget` is reported exactly\n * when the session's own row lists the name in `deferred`, and every figure on\n * it is a host measurement — {@link schemaChars} of this definition, the\n * session's `budgetChars` and its `visibleChars`. A number the host does not\n * have is omitted rather than guessed.\n *\n * The published fields are the schema's top-level `parameters.properties`\n * only: a nested object or array is drawn as its type and never expanded, and\n * a property's `default` is never published — the schema a model reads is the\n * definition's, and this record is a *view* of it, not a second copy with\n * defaults baked in.\n *\n * @param projectRoot - project root the panel read the row from.\n * @param sessionId - live agent id the row belongs to.\n * @param name - public registry name, as the panel drew it.\n * @returns the tool's facts, or the `not-found` refusal the route maps to 404.\n */\n toolFactsOf(projectRoot: string, sessionId: string, name: string): ToolFactsOutcome {\n const state = this.states.get(sessionId)\n if (state === undefined || state.projectRoot !== projectRoot) {\n return {\n ok: false,\n code: 'not-found',\n message: `no live session ${sessionId} in ${projectRoot}`,\n }\n }\n const home = this.homeOf(state)\n if (home === undefined) {\n return {\n ok: false,\n code: 'not-found',\n message: `no live session ${sessionId} in ${projectRoot}`,\n }\n }\n const schema = this.schemasOf(home, state.agent.id).find(\n (candidate) => candidate.name === name,\n )\n if (schema === undefined) {\n return {\n ok: false,\n code: 'not-found',\n message: `${name} is not mounted in ${projectRoot}`,\n }\n }\n const fields = toolFieldsOf(schema.parameters)\n const description = schema.description === '' ? undefined : schema.description\n // Only a name the session's own row hides is unexplained by the request, so\n // only such a name carries a reason; an offered one has nothing to explain.\n const deferred = this.sessionTools(state)?.deferred ?? []\n const reason = deferred.includes(name) ? this.budgetReason(state, schema) : undefined\n return {\n ok: true,\n value: {\n name: schema.name,\n ...(description === undefined ? {} : { description }),\n fields,\n ...(reason === undefined ? {} : { reason }),\n },\n }\n }\n\n /**\n * Why the budget left one definition out of this session's request: the host's\n * own numbers, each omitted when the row that carries it did not measure it.\n * @param state - the session whose row and budget are read.\n * @param schema - the definition the row does not offer.\n * @returns the `budget` reason, carrying only figures the host holds.\n */\n private budgetReason(state: AgentState, schema: ToolSchemaLike): ToolReason {\n const tools = this.sessionTools(state)\n return {\n kind: 'budget',\n chars: schemaChars(schema),\n ...(tools === undefined\n ? {}\n : {\n budget: tools.budgetChars,\n ...(tools.visibleChars === undefined ? {} : { used: tools.visibleChars }),\n }),\n }\n }\n\n /**\n * What this plugin currently mounts for one live agent: the project root the\n * agent resolved to and the server names it mounted there. `undefined` when\n * the agent is unknown or resolved to no project, so a tool call from it is\n * simply not counted.\n * @param agentId - agent (session) id a tool call ran for.\n */\n mountsFor(agentId: string): AgentMounts | undefined {\n const state = this.states.get(agentId)\n if (state === undefined || state.projectRoot === undefined) return undefined\n return { projectRoot: state.projectRoot, servers: this.runtimeNamesOf(state) }\n }\n\n /**\n * Pin or unpin one tool of one project.\n *\n * The project must be one this host currently has a live session in: the panel\n * only ever names a root it read from a snapshot, so anything else is a stale\n * click and is refused rather than stored for a project nothing would show. No\n * rescan follows — the policy is part of no declaring document — so the answer\n * carries the current snapshot with the fresh pin list.\n * @param request - project root, public tool name and the wanted pin state.\n * @returns the fresh snapshot, or the refusal code the route maps to a status.\n */\n setPin(request: PinRequest): PolicyOutcome {\n const policy = this.options.policy\n if (policy === undefined) {\n return {\n ok: false,\n code: 'failed',\n message: 'this host has no tool-policy store',\n messageCode: 'save.noPolicyStore',\n }\n }\n if (!this.projectKnown(request.projectRoot)) {\n return {\n ok: false,\n code: 'not-found',\n message: `no live session in ${request.projectRoot}`,\n messageCode: 'save.noLiveSession',\n messageParams: { projectRoot: request.projectRoot },\n }\n }\n policy.setPin(request.projectRoot, request.tool, request.pinned)\n this.refreshPresentation(request.projectRoot)\n this.notify()\n return { ok: true, snapshot: this.snapshot() }\n }\n\n /**\n * Store one project's tool mode.\n *\n * The same two refusals as {@link setPin}, plus a mode no assembly knows: the\n * mode is read on every assembly, so a stored change applies to the next model\n * step without re-minting the session scope.\n * @param request - project root and the mode to store.\n * @returns the fresh snapshot, or the refusal code the route maps to a status.\n */\n setPolicy(request: PolicyRequest): PolicyOutcome {\n if (!isToolMode(request.mode)) {\n return {\n ok: false,\n code: 'invalid',\n message: `unknown tool mode ${JSON.stringify(request.mode)}`,\n messageCode: 'save.unknownMode',\n messageParams: { mode: JSON.stringify(request.mode) },\n }\n }\n const policy = this.options.policy\n if (policy === undefined) {\n return {\n ok: false,\n code: 'failed',\n message: 'this host has no tool-policy store',\n messageCode: 'save.noPolicyStore',\n }\n }\n if (!this.projectKnown(request.projectRoot)) {\n return {\n ok: false,\n code: 'not-found',\n message: `no live session in ${request.projectRoot}`,\n messageCode: 'save.noLiveSession',\n messageParams: { projectRoot: request.projectRoot },\n }\n }\n policy.setMode(request.projectRoot, request.mode)\n this.refreshPresentation(request.projectRoot)\n this.notify()\n return { ok: true, snapshot: this.snapshot() }\n }\n\n /**\n * Choose which declaration of one contested `serverName` this project shows.\n *\n * The same two refusals as {@link setPin}, plus an answer no build knows. The\n * choice is stored first and the project reconciled right away, because a\n * choice is a mount changing name: the row it produces must be the row the\n * registry ends up carrying, not one that waits for the next turn.\n *\n * Nothing is refused for a name the project does not conflict over: the store\n * keeps a choice for a name that is not contested yet, so a declaration that\n * comes back — or a profile entry that is added later — finds the answer the\n * user already gave.\n * @param request - project root, contested name and the declaration to show.\n * @returns the fresh snapshot, or the refusal code the route maps to a status.\n */\n setConflictChoice(request: ConflictRequest): PolicyOutcome {\n if (!isConflictChoice(request.choice)) {\n return {\n ok: false,\n code: 'invalid',\n message: `unknown conflict choice ${JSON.stringify(request.choice)}`,\n messageCode: 'save.unknownChoice',\n messageParams: { choice: JSON.stringify(request.choice) },\n }\n }\n if (!this.projectKnown(request.projectRoot)) {\n return {\n ok: false,\n code: 'not-found',\n message: `no live session in ${request.projectRoot}`,\n messageCode: 'save.noLiveSession',\n messageParams: { projectRoot: request.projectRoot },\n }\n }\n const policy = this.options.policy\n if (policy === undefined) {\n return {\n ok: false,\n code: 'failed',\n message: 'this host has no tool-policy store',\n messageCode: 'save.noPolicyStore',\n }\n }\n policy.setConflictChoice(request.projectRoot, request.server, request.choice)\n this.notify()\n // The pass that follows the click is what moves the entry between a\n // conflict report and a mount, and it is not awaited: an operator click\n // must not wait for a server to start.\n void this.syncNow(request.projectRoot)\n return { ok: true, snapshot: this.snapshot() }\n }\n\n /**\n * The policy in force for one project root.\n *\n * Read at snapshot and assembly time — never captured — so a stored change is\n * visible to the next model step and to the next panel poll. A host built\n * without a store follows the shipped default for every project.\n * @param projectRoot - project root, or `undefined` before a session resolves one.\n * @returns the stored policy, or {@link DEFAULT_TOOL_POLICY} when there is none.\n */\n private policyFor(projectRoot: string | undefined): ToolPolicy {\n if (projectRoot === undefined) return DEFAULT_TOOL_POLICY\n return this.options.policy?.forProject(projectRoot) ?? DEFAULT_TOOL_POLICY\n }\n\n /**\n * Re-apply the presentation of every session working in one project.\n *\n * A pin or a mode is read live by the panel and by the guidance, but the\n * forwarders carry their `deferLoading` flag from the pass that registered\n * them, so the sessions of that project have to run one — off the caller's\n * stack, like every other change note.\n * @param projectRoot - the project whose policy just moved.\n */\n private refreshPresentation(projectRoot: string): void {\n for (const state of this.states.values()) {\n if (state.projectRoot !== projectRoot) continue\n state.bridge?.batch.note()\n }\n }\n\n /**\n * The names one session's presentation offers the model right now.\n *\n * The counterpart of the assembly wiring's own `offeredNames`, read where the\n * presentation lives outside that assembly — in the bridge's forwarders. It is\n * the counter-seeded baseline, the session's activations, the context tier's\n * window, and the project's pins; the same four sources the assembly-side\n * `wanted` set is built from, so the two cannot drift.\n * @param state - the session to read.\n * @returns the offered public names.\n */\n private offeredNamesOf(state: AgentState): ReadonlySet<string> {\n const names = new Set<string>(presentedNames(this.seedActivation(state)))\n const auto = state.auto\n if (auto !== undefined) for (const name of autoPresentedNames(auto)) names.add(name)\n for (const pin of this.policyFor(state.projectRoot).pins) names.add(pin)\n return names\n }\n\n /**\n * Ask the llm service what the session's current route can do with tool\n * declarations, and re-present the session when the answer moves.\n *\n * One answer per route, keyed by `provider/model`: the service resolves it from\n * the adapter, which is not something to ask on every step. `toolUpdate` is the\n * one capability read here — `undefined` on a route means the harness sends the\n * complete current declaration list in every request and strips the deferral\n * marker, so the presentation cannot hide a tool that way at all.\n *\n * A service that is absent (a host without `ctx.llm`, a test composition) or an\n * answer that never arrives leaves the capability `undefined`, and the\n * presentation keeps the deferral path it shipped with rather than guessing.\n * @param state - the session whose route is being read.\n * @param selection - the step's captured selection; absent resolves nothing.\n */\n private async resolveRoute(\n state: AgentState,\n selection: AgentEventLike['modelSelection'],\n ): Promise<void> {\n if (selection === undefined || this.disposed) return\n const key = `${selection.provider}/${selection.model}`\n if (state.routeKey === key) return\n state.routeKey = key\n const llm = this.ctx.get('llm') as\n | { resolveModelInfo?: (provider: string, model: string) => Promise<{ toolUpdate?: unknown }> }\n | undefined\n if (typeof llm?.resolveModelInfo !== 'function') return\n try {\n const info = await llm.resolveModelInfo(selection.provider, selection.model)\n const supported = info?.toolUpdate !== undefined\n if (supported === state.toolUpdate) return\n state.toolUpdate = supported\n // The presentation is built from this answer, so a route that changed its\n // mind — or a session that was mounted before its first step — re-presents\n // on the queue rather than inside whoever asked.\n state.bridge?.batch.note()\n } catch (error) {\n // A route that cannot describe itself is not a reason to fail a session;\n // the previous answer (or none) stands.\n this.ctx.logger.debug?.(\n `project-mcp: reading the model route of session ${state.agent.id} failed: ${errorText(error)}`,\n )\n }\n }\n\n /**\n * The names one session presents as deferred: what it mounts that it does not\n * offer.\n *\n * Empty when there is nothing to defer — activation off, `direct`, or a\n * surface that fits the budget — because deferring a schema the request would\n * have carried anyway only makes the declaration list harder to read, and the\n * prefix-cache argument for it is gone. The budget is the same\n * {@link surfaceChars} reading the panel and the assembly gate use, so the\n * deferred set and the \"hidden\" number a panel shows are one decision.\n * @param state - the session whose presentation is being registered.\n * @returns the names whose forwarders carry `deferLoading`, in registry order.\n */\n private deferredNamesOf(state: AgentState): readonly string[] {\n if (!(this.config.activationEnabled ?? DEFAULT_ACTIVATION_ENABLED)) return []\n // A route without tool updates would send a deferred schema anyway (the\n // harness strips the marker), so \"deferred\" there means \"declared\": the\n // presentation gives way to the forwarder list itself, which carries only\n // what is offered.\n if (state.toolUpdate === false) return []\n const policy = this.policyFor(state.projectRoot)\n if (policy.mode === 'direct') return []\n // The home's catalog, read without {@link mountedSchemas}: this runs inside a\n // bridge pass, and that read syncs the very batch the pass is building.\n const home = this.homeOf(state)\n const mounted = home === undefined ? [] : this.schemasOf(home, state.agent.id)\n if (policy.mode === 'disclosure') {\n const budget = this.config.activationToolBudgetChars ?? DEFAULT_TOOL_BUDGET_CHARS\n if (!overToolBudget(surfaceChars(mounted), budget)) return []\n }\n const offered = this.offeredNamesOf(state)\n return mounted.map((schema) => schema.name).filter((name) => !offered.has(name))\n }\n\n /**\n * Whether one project root has a live session on this host.\n * @param projectRoot - project root a policy request names.\n * @returns `true` when a bound session resolved to that root.\n */\n private projectKnown(projectRoot: string): boolean {\n for (const state of this.states.values()) {\n if (state.projectRoot === projectRoot) return true\n }\n return false\n }\n\n /**\n * Write one edited entry back to the document that declares it.\n *\n * The checks run in the contract's order and every one of them must pass\n * before a byte is written: the row must still exist, its declaring document\n * must belong to the project or to the (consented, enabled) global tier, the\n * revision must be the one the editor read, and the resulting entry must pass\n * the same parse path the mount uses. The document is then replaced by\n * {@link writeDocument} (`.bak`, then temp file, then rename) and rescanned,\n * so the answer carries a fresh snapshot.\n * @param request - the entry body, its declaring document and the read revision.\n * @returns the fresh snapshot, or the refusal code the route maps to a status.\n */\n async saveEntry(request: SaveRequest): Promise<SaveOutcome> {\n const states = [...this.states.values()].filter((state) => state.projectRoot === request.projectRoot)\n const row = states\n .flatMap((state) => state.rows)\n .find((candidate) => candidate.name === request.server)\n if (row === undefined) {\n return {\n ok: false,\n code: 'not-found',\n message: `server \"${request.server}\" is not declared for ${request.projectRoot}`,\n messageCode: 'save.serverNotDeclared',\n messageParams: { server: request.server, projectRoot: request.projectRoot },\n }\n }\n const document = row.source\n if (document === undefined) {\n return {\n ok: false,\n code: 'blocked',\n message: `server \"${request.server}\" has no declaring document to write`,\n messageCode: 'save.noDeclaringDocument',\n messageParams: { server: request.server },\n }\n }\n const scope = writeScopeFor(document, request.projectRoot, {\n projectDocuments: localConfigPaths(request.projectRoot, this.config.localFiles),\n globalDocuments: this.globalFiles(),\n allowGlobalWrite: this.config.allowGlobalWrite === true,\n })\n if (scope.scope === 'readonly') {\n // The scope's own reason already carries its write.blocked.* code; the\n // save.notWritable fallback is for the reason-less shape alone.\n return {\n ok: false,\n code: 'blocked',\n message: scope.reason ?? `${document} is not writable`,\n messageCode: scope.blockedCode ?? 'save.notWritable',\n messageParams: scope.blockedParams ?? { document },\n }\n }\n if (scope.scope === 'global' && request.consent !== true) {\n return {\n ok: false,\n code: 'blocked',\n message: `writing ${document} needs explicit consent`,\n messageCode: 'save.needsConsent',\n messageParams: { document },\n }\n }\n if (scope.scope === 'global' && this.config.allowGlobalWrite !== true) {\n return {\n ok: false,\n code: 'blocked',\n message: `writing the global tier is disabled by this deployment (allowGlobalWrite: false)`,\n messageCode: 'save.globalDisabled',\n }\n }\n if (request.document !== document) {\n return {\n ok: false,\n code: 'not-found',\n message: `server \"${request.server}\" is now declared by ${document}`,\n messageCode: 'save.declaredElsewhere',\n messageParams: { server: request.server, document },\n }\n }\n let text: string\n try {\n text = readFileSync(document, 'utf8')\n } catch {\n return {\n ok: false,\n code: 'not-found',\n message: `the declaring document ${document} is gone`,\n messageCode: 'save.documentGone',\n messageParams: { document },\n }\n }\n if (documentRevision(text) !== request.revision) {\n return {\n ok: false,\n code: 'conflict',\n message: `${document} changed since the entry was read; reload it and edit again`,\n messageCode: 'save.documentChanged',\n messageParams: { document },\n }\n }\n let root: unknown\n try {\n root = JSON.parse(text) as unknown\n } catch (error) {\n return {\n ok: false,\n code: 'invalid',\n message: `the declaring document is not valid JSON: ${error instanceof Error ? error.message : String(error)}`,\n messageCode: 'save.invalidJson',\n messageParams: { document, error: error instanceof Error ? error.message : String(error) },\n }\n }\n const servers = isRecord(root) ? root.mcpServers : undefined\n if (!isRecord(servers)) {\n return {\n ok: false,\n code: 'blocked',\n message: `${document} does not use an \"mcpServers\" object, so this editor cannot rewrite it`,\n messageCode: 'save.noMcpServers',\n messageParams: { document },\n }\n }\n // The panel edits the sanitized `serverName`; the document key may differ\n // (`my server` vs `my-server`), so the declaration goes back under the key\n // the document actually holds.\n const key = Object.keys(servers).find(\n (candidate) => candidate === request.server || slugifyServerName(candidate) === request.server,\n )\n if (key === undefined) {\n return {\n ok: false,\n code: 'not-found',\n message: `server \"${request.server}\" is no longer declared in ${document}`,\n messageCode: 'save.noLongerDeclared',\n messageParams: { server: request.server, document },\n }\n }\n let next: string\n try {\n next = applyEntry(text, key, entryToDeclaration(request.entry, servers[key]))\n } catch (error) {\n // A WriteDocError already carries the refusal's wire code; anything else\n // crosses as prose alone.\n return {\n ok: false,\n code: 'invalid',\n message: error instanceof Error ? error.message : String(error),\n ...(error instanceof WriteDocError\n ? {\n messageCode: error.code,\n ...(error.params === undefined ? {} : { messageParams: error.params }),\n }\n : {}),\n }\n }\n // Same parse path the mount uses: what the host would not mount, it does\n // not write either.\n const parsed = parseDocument(next, document, this.resolveContext(request.projectRoot))\n const candidate = parsed.entries.find((entry) => entry.name === request.server)\n if (candidate === undefined || candidate.error !== undefined || candidate.config === undefined) {\n // A parse failure's prose already has its own parse.* code (Task 2);\n // save.entryNotParsed names only the shapeless fallback.\n return {\n ok: false,\n code: 'invalid',\n message: candidate?.error ?? `the edited entry \"${request.server}\" did not parse`,\n messageCode: candidate?.errorCode ?? 'save.entryNotParsed',\n ...(candidate?.errorCode === undefined\n ? { messageParams: { server: request.server } }\n : candidate.errorParams === undefined\n ? {}\n : { messageParams: candidate.errorParams }),\n }\n }\n try {\n writeDocument(document, next)\n } catch (error) {\n return {\n ok: false,\n code: 'failed',\n message: `writing ${document} failed: ${error instanceof Error ? error.message : String(error)}`,\n messageCode: 'save.writeFailed',\n messageParams: { document, error: error instanceof Error ? error.message : String(error) },\n }\n }\n // Drop the read cache and the pass digest for this project: a write that\n // only reformats the document keeps the same mounted config, so the digest\n // alone would skip the row rebuild the editor needs.\n this.documents.delete(document)\n for (const state of states) state.digest = undefined\n // An edit belongs to the project that declares the entry: reconcile it as an\n // operator request for *its* sessions — so the change reaches a live mount —\n // and never as a request for another project, whose sessions must not start\n // a server because an entry moved here.\n await this.enqueue(new Set(states.map((state) => state.agent.id)))\n return { ok: true, snapshot: this.snapshot() }\n }\n\n /**\n * Run one reconciliation pass and await it.\n *\n * The operator call: it requests every listed session — or, with a\n * `projectRoot`, only that project's — so a session whose declaration was\n * never mounted (or whose mount was dropped) may start here without a turn.\n * Every other pass — a turn, an event, the rescan tick — requests only the\n * sessions that asked. Scripted reconciliation uses this awaiting form; the\n * panel's `Sync` uses {@link syncSoon}.\n * @param projectRoot - restricts the pass to one project's sessions.\n */\n async syncNow(projectRoot?: string): Promise<void> {\n await this.enqueue(this.requestsFor(projectRoot))\n }\n\n /**\n * Ask for the same pass and return at once — the panel's `Sync`.\n *\n * Waiting for the pass is what turned a `Sync` on a project whose server was\n * still connecting into a hang: the HTTP answer, and with it the panel's busy\n * flag, stayed open for `connectTimeoutMs`. The pass runs in the background,\n * and the panel watches its outcome on the status channel.\n * @param projectRoot - restricts the pass to one project's sessions.\n */\n syncSoon(projectRoot?: string): void {\n this.kick(projectRoot)\n }\n\n /**\n * Queue the operator pass without awaiting it, containing a rejection the way\n * every other background pass does: by the time either operator route\n * answers, the pass is nobody's request to wait for.\n * @param projectRoot - restricts the pass to one project's sessions.\n */\n private kick(projectRoot: string | undefined): void {\n void this.enqueue(this.requestsFor(projectRoot)).catch((error: unknown) => {\n this.ctx.logger.warn(`project-mcp: operator pass failed: ${errorText(error)}`)\n })\n }\n\n /**\n * The sessions one operator pass may mount: every listed one, or the sessions\n * of a single project when the call came from a surface that shows one. The\n * project is named, not resolved here: {@link syncAgent} matches it against\n * each session's own working directory, so the very first operator call for a\n * session reaches the project it named.\n * @param projectRoot - the project the caller named, when it named one.\n * @returns the request the pass takes.\n */\n private requestsFor(projectRoot: string | undefined): PassRequests {\n return projectRoot === undefined ? 'all' : { projectRoot }\n }\n\n /** Queue one pass behind whatever is already running. */\n private enqueue(requests: PassRequests): Promise<void> {\n this.chain = this.chain.then(\n () => this.runPass(requests),\n () => this.runPass(requests),\n )\n return this.chain\n }\n\n /**\n * Drop the mounts currently in an `error` state and ask for a pass that mounts\n * them again, so a server that was fixed outside the plugin is picked up\n * without editing its declaration. A stalled mount is restarted from scratch.\n *\n * The drop is awaited — it is local and quick, and the answer the route sends\n * back must already show those rows as unmounted rather than failed. The pass\n * is not: a server that boots slowly would otherwise hold the `POST retry`\n * answer open for `connectTimeoutMs`, which the panel showed as a hang. A\n * `projectRoot` keeps both the drop and the pass inside that one project, so\n * retrying a row never starts a server for another one.\n *\n * The drop is per project: one failed instance is shared by every session of\n * its project, so retrying it must not try to unmount it once per session.\n * @param projectRoot - restricts the drop and the pass to one project.\n */\n async retry(projectRoot?: string): Promise<void> {\n // Every instance a session renders lives in its project's shared home — one\n // home per project, bridged or joined — so the project records are the whole\n // list of homes a retry has to walk.\n const homes: MountHome[] = [...this.projects.values()]\n for (const home of homes) {\n if (projectRoot !== undefined && home.projectRoot !== projectRoot) continue\n let dropped = false\n for (const [name, mount] of [...home.mounts]) {\n if (mount.status !== 'error') continue\n await this.unmount(home, name, { code: 'unmount.reason.operatorRetry', text: 'an operator retry replaces it' })\n dropped = true\n }\n // The documents are unchanged, so the pass below would take its steady\n // state shortcut — the dropped mount is exactly why it must not. Every\n // session that renders this home's rows must rebuild them. (A lazy\n // declaration that was never mounted needs no nudge: the operator pass\n // mounts it by itself, see the merge pass.)\n if (!dropped) continue\n for (const state of this.states.values()) {\n if (state.projectRoot === home.projectRoot) state.digest = undefined\n }\n }\n // The rows the drop just freed are visible now; the pass that mounts them\n // again reports for itself, one mount at a time.\n this.notify()\n this.kick(projectRoot)\n }\n\n /** Dispose every mount, scope, watcher and timer owned by this runtime. */\n async disposeAll(): Promise<void> {\n this.disposed = true\n if (this.timer !== undefined) clearInterval(this.timer)\n if (this.debounce !== undefined) clearTimeout(this.debounce)\n this.timer = undefined\n this.debounce = undefined\n for (const watchers of this.watchers.values()) {\n for (const watcher of watchers) watcher.close()\n }\n this.watchers.clear()\n this.watchedDirs.clear()\n this.watchedRoots.clear()\n const states = [...this.states.values()]\n this.states.clear()\n this.documents.clear()\n this.secrets = undefined\n this.envFiles.clear()\n // Sessions first — each hands its hold back — then whatever no session names\n // any more, so a shared project is released exactly once either way.\n await Promise.all(states.map((state) => this.disposeState(state, { code: 'unmount.reason.unloading', text: 'the plugin is unloading' })))\n for (const project of [...this.projects.values()]) {\n await this.releaseProject(project, { code: 'unmount.reason.unloading', text: 'the plugin is unloading' })\n }\n this.projects.clear()\n // Last, so the teardown events above still reach the log: this runtime stops\n // being a consumer once it has nothing left to report.\n this.detachLog?.()\n this.detachLog = undefined\n }\n\n private newState(agent: AgentLike): AgentState {\n return {\n agent,\n cwd: agent.session.header?.cwd,\n projectRoot: undefined,\n digest: undefined,\n scope: undefined,\n project: undefined,\n bridge: undefined,\n parentLinked: false,\n detachedKey: undefined,\n rows: [],\n issues: [],\n conflicts: [],\n lastActivityAt: undefined,\n busy: false,\n activationPending: false,\n activation: undefined,\n step: 0,\n steps: new Map(),\n activationDispose: undefined,\n guidanceDispose: undefined,\n auto: undefined,\n routeKey: undefined,\n toolUpdate: undefined,\n }\n }\n\n private dropAgent(id: string): void {\n const state = this.states.get(id)\n this.states.delete(id)\n if (state !== undefined) void this.disposeState(state, { code: 'unmount.reason.sessionGone', text: 'the session went away' })\n this.sweepProjects()\n this.syncWatchers()\n this.notify()\n }\n\n /**\n * Release the sessions the host registry no longer lists.\n *\n * A finished or abandoned session produces no further event — no\n * `agent/status`, no `idle` transition to clear the busy flag, nothing for\n * the idle sweep to time out from. The pass is the path that exists: whatever\n * the registry still lists is live, and anything else hands its servers back\n * here, even with the idle sweep disabled.\n */\n private async releaseAbandoned(): Promise<void> {\n const listed = this.listAgents?.()\n if (listed === undefined) return\n const live = new Set(listed.map((agent) => agent.id))\n for (const id of [...this.states.keys()]) {\n if (live.has(id)) continue\n const state = this.states.get(id)\n this.states.delete(id)\n if (state !== undefined) await this.disposeState(state, { code: 'unmount.reason.sessionUnlisted', text: 'the registry no longer lists the session' })\n }\n }\n\n /**\n * Whether one session is running a turn right now.\n *\n * The host's own status wins where it publishes one: `busy` only ever\n * reflects the events this plugin happened to see, so a session whose `idle`\n * transition never arrives would pin its mounts forever behind a stale flag.\n * @param state - the session to judge.\n * @returns true while the session must keep its mounts unconditionally.\n */\n private working(state: AgentState): boolean {\n const live = state.agent.status\n return live === undefined ? state.busy : live === 'running'\n }\n\n /**\n * Forget everything one session presented. The session's project is gone with\n * the scope (or the session is over), so a baseline seeded from that project's\n * counters must not leak into a different one. An idle release goes through\n * `releaseMounts`, not here.\n *\n * The hold on the old project's shared servers is given back here too: a\n * session that moves to another project — or disappears — must not keep the\n * project it left running for nobody.\n * @param state - the session state to clear.\n */\n private async disposeState(state: AgentState, reason: CodedText): Promise<void> {\n state.digest = undefined\n state.rows = []\n state.issues = []\n state.activation = undefined\n state.auto = undefined\n await this.detach(state, reason)\n }\n\n /**\n * Take one session's hold on a project: link its scope key to the project's\n * so the shared layer resolves for it, or install the forwarding bridge when\n * that link is impossible, then mint its own scope and install the session\n * wiring on it. Idempotent while the hold is unchanged.\n *\n * The link comes first because it is what makes the project's already-running\n * servers visible to this session from its first request on. A key the\n * harness already parented cannot be linked again — `dsh-scope` binds a key\n * once, and the agent-preset roster binds every composed agent to its\n * standing scope before the agent is published — so that session holds the\n * SAME project home and gets a forwarding bridge instead: thin definitions in\n * its own layer whose calls run the project's one instance (`src/bridge.ts`).\n * One process per project is the whole point; the alternative was one process\n * per session, which is what the panel showed in the web GUI.\n * @param state - the session taking the hold.\n * @param project - the project whose mounts it shares.\n * @returns the home the session now holds.\n */\n private async holdProject(state: AgentState, project: ProjectState): Promise<MountHome> {\n const held = this.homeOf(state)\n if (held !== undefined && held.projectRoot === project.projectRoot) return held\n if (held !== undefined) await this.detach(state, { code: 'unmount.reason.sessionMoved', text: 'the session moved to another project' })\n // The session's own layer key is private to this session, so the link either\n // succeeds (this runtime just bound it, or owns the binding) or another\n // composition already parented that key — a foreign hold this runtime must\n // not move. The session still holds the project — the servers run once for\n // the whole project — and the bridge carries their tools into this session's\n // own layer, where the registry resolves them for exactly this key.\n state.parentLinked = linkScopeParent(state.agent, project.key)\n if (!state.parentLinked) {\n this.ctx.logger.debug?.(\n `project-mcp: session ${state.agent.id} keeps a foreign scope parent, so its tools are forwarded from ${project.projectRoot}`,\n )\n }\n state.project = project\n const home: MountHome = project\n this.ensureSessionScope(state.agent, state)\n if (state.parentLinked) this.dropBridge(state)\n else this.installBridge(state, project)\n return home\n }\n\n /**\n * Give one session's hold back. Its own scope and wiring go away, its scope\n * key is unlinked from the project so the shared servers stop resolving for\n * it, and the project's instance is released exactly when this was the last\n * holder — a session that goes idle or leaves while another one still works\n * must not stop the servers that one is using.\n * @param state - the session releasing its hold.\n * @param reason - why the hold is going back; every instance this drops is\n * logged with it, so the log says why a server stopped, not only that it did.\n */\n private async detach(state: AgentState, reason: CodedText): Promise<void> {\n const project = state.project\n state.project = undefined\n this.dropBridge(state)\n if (project !== undefined && state.parentLinked) {\n state.parentLinked = false\n state.detachedKey ??= {}\n if (!linkScopeParent(state.agent, state.detachedKey)) {\n this.ctx.logger.warn(\n `project-mcp: unlinking session ${state.agent.id} from its project failed: its session key is held by another composition`,\n )\n }\n }\n await this.disposeSessionScope(state, reason)\n if (project !== undefined && !this.hasHolders(project)) await this.releaseProject(project, reason)\n }\n\n /** Drop the session scope and the wiring installed on it. Idempotent. */\n private async disposeSessionScope(state: AgentState, reason: CodedText): Promise<void> {\n const scope = state.scope\n state.scope = undefined\n this.releaseWiring(state)\n if (scope === undefined) return\n try {\n await scope.dispose()\n } catch (error) {\n this.ctx.logger.warn(`project-mcp: disposing session scope failed: ${errorText(error)}`)\n }\n }\n\n /**\n * Whether any live session still holds one project's shared mounts.\n * @param project - the project to look for.\n * @returns `true` while at least one session keeps the instance alive.\n */\n private hasHolders(project: ProjectState): boolean {\n for (const state of this.states.values()) {\n if (state.project === project) return true\n }\n return false\n }\n\n /**\n * Release one project's shared servers and the scope that owns them.\n *\n * Runs when the project's last holder lets go, so a shared instance goes away\n * on exactly the trigger a per-session one did: the project's last session\n * releasing it (idle release, request, disposal, a move to another project, or\n * a declaration that mounts nothing any more). Idempotent.\n * @param project - the project to tear down.\n */\n private async releaseProject(project: ProjectState, reason: CodedText): Promise<void> {\n for (const name of [...project.mounts.keys()]) await this.unmount(project, name, reason)\n const scope = project.scope\n project.scope = undefined\n if (scope !== undefined) {\n try {\n await scope.dispose()\n } catch (error) {\n this.ctx.logger.warn(\n `project-mcp: disposing the shared scope of ${project.projectRoot} failed: ${errorText(error)}`,\n )\n }\n }\n // The record itself stays while a session is still bound to this root: a\n // pass mounting concurrently (a session disposed while another one turns)\n // would otherwise create a second record — and a second instance — for one\n // root. `sweepProjects` forgets it once nothing is bound any more.\n this.sweepProjects()\n }\n\n /**\n * Forget the project records no live session is bound to any more. A record\n * with mounts or a scope is never dropped: either one means someone still\n * holds the project.\n */\n private sweepProjects(): void {\n for (const [projectRoot, project] of this.projects) {\n if (project.scope !== undefined || project.mounts.size > 0) continue\n if (this.hasRootSessions(projectRoot)) continue\n this.projects.delete(projectRoot)\n }\n }\n\n /** Whether any live session resolved its working directory to one root. */\n private hasRootSessions(projectRoot: string): boolean {\n for (const state of this.states.values()) {\n if (state.projectRoot === projectRoot) return true\n }\n return false\n }\n\n /**\n * The project record one root's sessions share, created with its first holder\n * and forgotten when its last one lets go.\n * @param projectRoot - resolved project root.\n * @returns the live record.\n */\n private ensureProject(projectRoot: string): ProjectState {\n const existing = this.projects.get(projectRoot)\n if (existing !== undefined) return existing\n const project: ProjectState = {\n projectRoot,\n key: { projectRoot },\n scope: undefined,\n mounts: new Map(),\n shared: true,\n }\n this.projects.set(projectRoot, project)\n return project\n }\n\n /**\n * The home one session mounts in: the project it holds, bridged or joined.\n * `undefined` while it holds nothing.\n * @param state - the session to read.\n * @returns the session's mount home, or `undefined` when it holds none.\n */\n private homeOf(state: AgentState): MountHome | undefined {\n return state.project\n }\n\n /**\n * The mounts one session renders right now: its own home's when it has one for\n * this root, otherwise the project's shared set, so a session that holds\n * nothing still notices another session's mounts and re-renders its rows.\n * @param state - the session to read.\n * @param projectRoot - the project root the pass is reconciling.\n * @returns the mount map whose changes this session's digest tracks.\n */\n private visibleMounts(state: AgentState, projectRoot: string): ReadonlyMap<string, MountedInstance> {\n const home = this.homeOf(state)\n if (home !== undefined && home.projectRoot === projectRoot) return home.mounts\n return this.projects.get(projectRoot)?.mounts ?? NO_MOUNTS\n }\n\n /**\n * The live mounts one session currently holds. Empty for a session that holds\n * nothing: the servers run for their project, and only a holder shares them.\n * @param state - the session to read.\n * @returns the shared mount map, or a shared empty one.\n */\n private mountsOf(state: AgentState): ReadonlyMap<string, MountedInstance> {\n return this.homeOf(state)?.mounts ?? NO_MOUNTS\n }\n\n /**\n * The `serverName` every one of the session's mounts registers under.\n *\n * The registry — and every name it publishes — is keyed by this, not by the\n * declared name: a shadowed declaration registers as its local alias, and a\n * lookup by the contested name would read as \"this project mounts nothing\".\n * @param state - the session to read.\n * @returns the runtime names, one per live mount.\n */\n private runtimeNamesOf(state: AgentState): Set<string> {\n return new Set([...this.mountsOf(state).values()].map((mount) => mount.runtimeName))\n }\n\n /**\n * Unregister everything the current scope's session wiring installed. The\n * scope fiber disposes the same registrations with the real services, while a\n * host that publishes plain `systemPrompt`/`tools` stubs has only this path.\n * Idempotent.\n */\n private releaseWiring(state: AgentState): void {\n this.releaseGuidance(state)\n this.releaseActivation(state)\n }\n\n /**\n * Unregister the guidance section of the current scope, if one is installed.\n * Released exactly where the scope is — an idle release and agent disposal —\n * so no section ever describes mounts that are gone.\n */\n private releaseGuidance(state: AgentState): void {\n const dispose = state.guidanceDispose\n state.guidanceDispose = undefined\n if (dispose === undefined) return\n try {\n dispose()\n } catch (error) {\n this.ctx.logger.warn(\n `project-mcp: releasing guidance for session ${state.agent.id} failed: ${errorText(error)}`,\n )\n }\n }\n\n /**\n * Unregister the activation wiring of the current scope. Idempotent: the\n * scope fiber disposes the same registrations with the real registry, while a\n * host that publishes a plain `tools` stub has only this path.\n */\n private releaseActivation(state: AgentState): void {\n const dispose = state.activationDispose\n state.activationDispose = undefined\n if (dispose === undefined) return\n try {\n dispose()\n } catch (error) {\n this.ctx.logger.warn(\n `project-mcp: releasing activation for session ${state.agent.id} failed: ${errorText(error)}`,\n )\n }\n }\n\n /**\n * Ask for a pass. A pending pass is kept instead of being pushed back: the\n * rescan tick is often shorter than the debounce, and restarting the timer on\n * every tick would starve reconciliation forever. Bursts of watcher events\n * still collapse into the one queued pass, and each pass re-reads the\n * documents through the digest, so a late event costs one cheap pass.\n */\n private schedule(reason: string): void {\n if (this.disposed) return\n this.ctx.logger.debug?.(`project-mcp: sync scheduled (${reason})`)\n if (this.debounce !== undefined) return\n this.debounce = setTimeout(() => {\n this.debounce = undefined\n void this.enqueue(NO_REQUESTS)\n }, this.config.debounceMs)\n this.debounce.unref?.()\n }\n\n /**\n * Turn boundary. `running` is the moment a session becomes active, which is\n * what `lazy` waits for; `idle` closes the busy window that idle release\n * watches. A plain notification, so it never delays a turn.\n */\n private onStatus(event: AgentEventLike): void {\n if (this.disposed) return\n const state = this.states.get(event.agent.id)\n if (state === undefined) return\n // Both transitions are an activity boundary: a tool that has not been called\n // for `toolIdleMs` falls out here, before the turn that follows can see it.\n this.pruneActivation(state)\n if (event.status === 'running') {\n this.touch(state, { activate: true, busy: true })\n return\n }\n this.touch(state, { activate: false, busy: false })\n }\n\n /**\n * Before every step of a turn: keep this session's project mounted, waiting\n * for a pending activation so that the step's request already sees the\n * project's tools. The waterfall always continues — a project MCP server is\n * never a reason to hold up an agent step.\n */\n private async onPreStep(event: AgentEventLike, next: () => Promise<unknown>): Promise<unknown> {\n try {\n const state = this.states.get(event.agent.id)\n if (state !== undefined) {\n // This hook is the harness's own step boundary, so it is where the\n // per-session counter advances: an activation made during this step,\n // and the row a panel reads after it, both carry the number of the step\n // they belong to instead of a placeholder.\n state.step += 1\n if (!this.disposed) {\n this.touch(state, { activate: true })\n // Route capability is asked for off this path: it is network-shaped on\n // some adapters, and a project MCP server is never a reason to hold up\n // an agent step.\n void this.resolveRoute(state, event.modelSelection)\n await this.awaitActivation(state)\n }\n }\n } catch (error) {\n this.ctx.logger.warn(`project-mcp: activation before a step failed: ${errorText(error)}`)\n }\n return next()\n }\n\n /** Record activity and, with nothing mounted, ask for an activation pass. */\n private touch(state: AgentState, options: { activate: boolean; busy?: boolean }): void {\n state.lastActivityAt = Date.now()\n if (options.busy !== undefined) state.busy = options.busy\n if (!options.activate || this.mountsOf(state).size > 0) return\n state.activationPending = true\n this.schedule('activity')\n }\n\n /**\n * Wait (bounded) for the activation pass a turn asked for.\n *\n * The pass carries no operator request on purpose: the caller's\n * `activationPending` is what entitles this session to mount, and leaving the\n * request empty is what keeps the pass from starting servers in every other\n * project whose sessions happen to be live.\n */\n private async awaitActivation(state: AgentState): Promise<void> {\n if (!state.activationPending) return\n const pass = this.enqueue(NO_REQUESTS).catch(() => undefined)\n const waitMs = this.config.activationWaitMs\n if (waitMs <= 0) return\n await Promise.race([pass, delay(waitMs)])\n }\n\n /**\n * Reconcile every known session once, then the sweep and the watchers.\n * @param requests - the sessions that may mount without their own turn asking.\n */\n private async runPass(requests: PassRequests): Promise<void> {\n if (this.disposed) return\n // A session the host no longer lists is finished: no later event will ever\n // report it, so this pass is the path that hands its mounts back.\n await this.releaseAbandoned()\n // Sessions are independent: one slow connect must not serialize the rest.\n await Promise.all(\n [...this.states.values()].map(async (state) => {\n try {\n await this.syncAgent(state, requests)\n } catch (error) {\n this.ctx.logger.warn(\n `project-mcp: sync failed for session ${state.agent.id}: ${errorText(error)}`,\n )\n }\n }),\n )\n await this.evictIdle()\n this.sweepProjects()\n this.syncWatchers()\n this.notify()\n }\n\n /**\n * Release the mounts of sessions that have been quiet for `idleTimeoutMs`.\n * Their rows stay visible as `idle`, so the project's declaration remains\n * discoverable while not a single child process is running for it.\n */\n private async evictIdle(): Promise<void> {\n const timeout = this.config.idleTimeoutMs\n if (timeout <= 0) return\n const now = Date.now()\n for (const state of [...this.states.values()]) {\n if (this.mountsOf(state).size === 0 || this.working(state)) continue\n const since = state.lastActivityAt\n if (since === undefined || now - since < timeout) continue\n await this.releaseMounts(\n state,\n (count) => ({\n code: 'idle.releasedInactive',\n text: `released after ${formatSeconds(now - since)} without activity — ${count} server(s) stopped; the next turn mounts them again`,\n params: { seconds: formatSeconds(now - since), count: String(count) },\n }),\n { code: 'unmount.reason.sessionIdle', text: 'the session went idle' },\n )\n }\n }\n\n /**\n * Give one session's servers back now, or every mounted session's when no id\n * is given. Drives the panel's \"release\" action; the rows stay as `idle` and\n * the next turn mounts them again. A session that releases the last hold on a\n * project takes the shared instance down with it, and one that releases while\n * another session of the project holds leaves it running for that session.\n */\n async release(agentId?: string): Promise<void> {\n for (const state of [...this.states.values()]) {\n if (agentId !== undefined && state.agent.id !== agentId) continue\n if (this.mountsOf(state).size === 0) continue\n await this.releaseMounts(\n state,\n (count) => ({\n code: 'idle.releasedRequest',\n text: `released on request — ${count} server(s) stopped; the next turn mounts them again`,\n params: { count: String(count) },\n }),\n { code: 'unmount.reason.operatorReleased', text: 'an operator released it' },\n )\n }\n this.notify()\n }\n\n /**\n * Give one session's hold back, keeping its rows as `idle`.\n *\n * The shared servers themselves follow the last holder: this detaches the\n * session (its scope, wiring and parent link) and releases the project only\n * when no other session holds it, so releasing one session of a project that\n * another session is still working in leaves that session's servers running.\n * @param state - the session releasing.\n * @param describe - reason for its rows, given the number of servers it held.\n */\n private async releaseMounts(\n state: AgentState,\n describe: (count: number) => CodedText,\n reason: CodedText,\n ): Promise<void> {\n const held = this.homeOf(state)\n const mounted = new Set(held === undefined ? [] : held.mounts.keys())\n const diagnostics = new Set(\n [...(held?.mounts.values() ?? [])].flatMap((mount) =>\n mount.detail === undefined ? [] : [mount.detail],\n ),\n )\n state.activationPending = false\n state.busy = false\n await this.detach(state, reason)\n const summary = describe(mounted.size)\n state.rows = state.rows.map((row) => (mounted.has(row.name) ? idleRow(row, summary) : row))\n state.issues = state.issues.filter((issue) => !diagnostics.has(issue.message))\n this.ctx.logger.debug?.(`project-mcp: session ${state.agent.id}: ${summary.text}`)\n }\n\n /**\n * Re-read one agent's project and reconcile its mounts.\n * @param state - the session to reconcile.\n * @param operatorRequested - an operator pass named this exact session.\n */\n async syncAgent(state: AgentState, requests: PassRequests = NO_REQUESTS): Promise<void> {\n const agent = state.agent\n const cwd = agent.session.header?.cwd\n state.cwd = cwd\n const projectRoot =\n cwd === undefined || cwd === ''\n ? undefined\n : findProjectRoot(cwd, this.config.projectMarkers, this.config.fileMarkers)\n // An operator asks for a session directly, or for a project — the second\n // only matches once the session's own working directory has been read,\n // which is why it is decided here rather than before the pass.\n const operatorRequested =\n requests === 'all' ||\n ('projectRoot' in requests\n ? requests.projectRoot === projectRoot\n : requests.has(state.agent.id))\n\n if (projectRoot === undefined) {\n // The root was just read and none was found. A session's working directory\n // cannot stop being inside its project without the session changing, so\n // this is a stale read — a concurrent sweep of the working tree, a temp\n // directory removed under a test. Either way the session keeps the hold it\n // has: a release here would tear down live mounts that the next read finds\n // again, and a session that genuinely has no project holds nothing to\n // release. A pending first mount still has to be cleared, because no turn\n // should wait for a pass that has nothing to do.\n state.activationPending = false\n return\n }\n // A session that moved to another project starts from a clean scope.\n if (projectRoot !== state.projectRoot) {\n await this.disposeState(state, { code: 'unmount.reason.sessionMoved', text: 'the session moved to another project' })\n state.projectRoot = projectRoot\n }\n\n const { entries, issues, documents, sources } = this.readProject(projectRoot)\n const reserved = this.config.profileWins ? this.profileServerNames() : new Set<string>()\n // The local names this project's shadowed declarations would take, resolved\n // once for the whole pass: the row, the mount and the conflict report all\n // read this one answer, so the alias the panel offers is the alias the\n // registry ends up carrying.\n const policy = this.policyFor(projectRoot)\n const aliases = resolveConflictNames({\n entries: entries.map((entry) => ({ name: entry.name, reserved: reserved.has(entry.name) })),\n prefix: this.config.localPrefix,\n projectRoot,\n })\n /**\n * The shadowed names this pass actually mounts, and under which name.\n *\n * A name whose user kept the profile's copy is deliberately absent: it is a\n * conflict report, not a mount. `local` mounts this project's entry under the\n * alias the panel offers; `native` mounts it under the name it declares,\n * where it is the nearer declaration for this project's own sessions and so\n * shadows the profile instance's tools of that name there. The profile\n * instance itself is never touched: it keeps running, and every other project\n * keeps resolving it. A `native` entry is therefore mapped to `undefined` and\n * is still a chosen mount — `has` is the question, never the value.\n */\n const choices = aliasesOf(policy)\n const chosen = new Map<string, string | undefined>()\n for (const [name, alias] of aliases) {\n const choice = choices[name] ?? 'profile'\n if (choice === 'local') chosen.set(name, alias)\n else if (choice === 'native') chosen.set(name, undefined)\n }\n state.conflicts = conflictsFor(entries, sources, reserved, aliases, policy)\n\n const rows: ServerRow[] = []\n const desired = new Map<string, ParsedEntry>()\n for (const entry of entries) {\n const base = baseRow(entry, projectRoot, documents.get(entry.source))\n if (entry.error !== undefined) {\n rows.push({\n ...base,\n status: 'error',\n detail: entry.error,\n ...(entry.errorCode === undefined ? {} : { detailCode: entry.errorCode }),\n ...(entry.errorParams === undefined ? {} : { detailParams: entry.errorParams }),\n })\n continue\n }\n if (!entry.enabled) {\n rows.push({ ...base, status: 'disabled', detail: 'declared with enabled: false', detailCode: 'idle.disabled' })\n continue\n }\n if (reserved.has(entry.name)) {\n const alias = aliases.get(entry.name)\n // The user chose this project's copy, and the pass has a name to mount it\n // under: the local alias, or the contested name itself when they opted to\n // shadow the profile's instance in this project's sessions. Either way the\n // declaration mounts like any other, and the profile's instance is left\n // running for every other project.\n if (chosen.has(entry.name)) {\n desired.set(entry.name, entry)\n // The row is `active` and carries no detail of its own: `decorate` drops\n // a row's detail while it has a mount, so a line explaining the choice\n // would never reach a surface. The conflict report below is where a\n // mounted name still says which of the three readings it is.\n const detail = conflictDetail(entry.name, alias)\n rows.push({\n ...base,\n detail: detail.text,\n detailCode: detail.code,\n ...(detail.params === undefined ? {} : { detailParams: detail.params }),\n })\n continue\n }\n const detail = conflictDetail(entry.name, alias)\n rows.push({\n ...base,\n status: 'conflict',\n detail: detail.text,\n detailCode: detail.code,\n ...(detail.params === undefined ? {} : { detailParams: detail.params }),\n })\n continue\n }\n desired.set(entry.name, entry)\n rows.push(base)\n }\n\n const documentIssues: SnapshotIssue[] = issues.map((issue) => ({\n source: issue.source,\n ...(issue.server === undefined ? {} : { server: issue.server }),\n level: issue.level,\n message: issue.message,\n ...(issue.code === undefined ? {} : { code: issue.code }),\n ...(issue.params === undefined ? {} : { params: issue.params }),\n }))\n\n // The project's shared instance, if it already has one. Its mounts are what\n // this session holds when it is already attached, and what it is about to\n // share when it attaches below — both are read live, never copied.\n const existing = this.projects.get(projectRoot)\n // The mounts whose changes this session's digest tracks: its own home's\n // when it has one, otherwise the project's shared set. A session that holds\n // nothing must still notice another session mounting, settling or dropping\n // a server, because its rows are a rendering of exactly those mounts.\n const mounts = this.visibleMounts(state, projectRoot)\n\n // Steady state: the documents, their resolved configs, the profile\n // reservations and the published state of the shared mounts are identical\n // and every mount has settled, so this pass has nothing to reconcile — no\n // merge, no tool-catalog scan, no remount. The shared-mount part of the\n // digest matters because another session of this project can have mounted,\n // settled or dropped a server without any document changing, and this\n // session's rows are a rendering of exactly those mounts.\n //\n // One state is *not* settled even so: a session whose project declares\n // something mountable and which `lazy` has mounted nothing for. Its inputs\n // are byte-identical to the pass that only published the declaration, so the\n // digest cannot tell them apart — an operator pass (`syncNow`, `retry`) has\n // to mount it now instead of waiting for a turn that may never come.\n const mountable = desired.size > 0\n // Whether *this* session already holds mounts. The project can be running\n // for another session of it while this one holds nothing, and such a\n // session must not be attached by a pass of its own: holding would make it\n // keep an instance it never asked for alive past its last real holder, and\n // would put the project's tools into a session that never turned.\n const held = this.mountsOf(state).size > 0\n // What this session is allowed to start in this pass, and why. `undefined`\n // is the answer for every session that is not working in its project: it is\n // live, it declares servers, and none of them may run.\n const trigger = mountTrigger({\n lazy: this.config.lazy,\n activationPending: state.activationPending,\n mounted: held,\n operatorRequested,\n })\n const awaitedMount = trigger === 'operator' && this.config.lazy && !held && mountable\n /**\n * Identity of this pass's inputs, recomputed once the mounts settled — a\n * mount created or dropped by this very pass is then part of it, so the\n * next pass recognizes the steady state instead of rebuilding one more time.\n */\n const settle = (): void => {\n state.digest = digestOf(entries, reserved, this.visibleMounts(state, projectRoot), chosen)\n }\n /**\n * The project record; only a session that may run something takes a hold,\n * and minting the record is what lets every other session of the root share\n * the instance it starts.\n */\n const project = trigger === undefined || desired.size === 0 ? existing : this.ensureProject(projectRoot)\n const digest = digestOf(entries, reserved, mounts, chosen)\n if (!awaitedMount && state.digest === digest && this.settled(state) && !state.activationPending) return\n\n // `lazy` defers a session's *first* mount to its first turn. Removals and\n // edits are always reconciled below; an operator call (`syncNow`, `retry`)\n // and a pending activation mount regardless.\n //\n // `mounted` in the decision above makes `undefined` unreachable while this\n // session holds servers, so publishing rows here never hides a live mount.\n if (trigger === undefined) {\n // Nothing runs for this session: publish what the project declares (it is\n // what the next turn will mount) without starting a single server.\n state.rows = rows.map((row) => (desired.has(row.name) ? idleRow(row, LAZY_DETAIL) : row))\n state.issues = documentIssues\n settle()\n return\n }\n\n // A session that may mount takes its hold first: the parent link is what\n // makes the project's already running servers visible to it, and minting\n // the session scope is what carries the session wiring. A session whose\n // scope key the harness already parented cannot take that link at all and\n // gets a home of its own, which is why the hold returns the home the pass\n // reconciles instead of the pass assuming the project's. A project that\n // declares nothing mountable mints no session scope at all — the\n // declarations below are published and nothing runs.\n let home: MountHome | undefined\n if (desired.size > 0 && project !== undefined) {\n home = await this.holdProject(state, project)\n } else {\n home = this.homeOf(state) ?? existing\n }\n\n if (home !== undefined) {\n // One home is reconciled, not one session's share of it: an edit or a\n // removal in the document is every holder's business, and a declaration\n // either exists for all sessions that resolve the home or for none.\n for (const [name, mount] of [...home.mounts]) {\n const entry = desired.get(name)\n if (entry?.config === undefined) {\n // A reserved name this project was mounting leaves for one of two\n // reasons — the declaration is gone, or the user went back to the\n // profile's copy — and the lifecycle log is where a reader tells them\n // apart.\n await this.unmount(\n home,\n name,\n reserved.has(name)\n ? { code: 'unmount.reason.profileShown', text: 'this project shows the profile-level copy instead' }\n : { code: 'unmount.reason.undeclared', text: 'the documents no longer declare it' },\n )\n continue\n }\n // A mount that no longer carries the local name this pass chose is\n // remounted, not kept: the alias is the whole of what the user changed,\n // and a registration is only ever created under one name.\n if (mount.runtimeName !== runtimeNameOf(entry, chosen.get(name))) {\n await this.unmount(home, name, { code: 'unmount.reason.nameChanged', text: 'its local name changed' })\n continue\n }\n if (mount.fingerprint !== fingerprint(entry.config)) {\n await this.unmount(home, name, { code: 'unmount.reason.declarationChanged', text: 'its declaration changed' })\n }\n }\n\n // Registration only: no `mount` here waits for its server, so this loop\n // is what a pass costs per declaration, not the handshake behind it.\n for (const [name, entry] of desired) {\n if (entry.config === undefined || home.mounts.has(name)) continue\n this.mount(state, home, name, entry, trigger, chosen.get(name))\n }\n if (home.mounts.size === 0) {\n // Nothing is mounted by design: this session keeps no hold, and a\n // shared scope goes with its last holder, so no server outlives the\n // session that asked for it.\n await this.detach(state, { code: 'unmount.reason.nothingMountable', text: 'nothing it declares is mountable any more' })\n if (home.shared && !this.hasHolders(home as ProjectState)) {\n await this.releaseProject(home as ProjectState, { code: 'unmount.reason.nothingMountable', text: 'nothing it declares is mountable any more' })\n }\n }\n }\n\n // The declarations as the documents give them. A mounted server keeps its\n // declared row here: the mount's own status is applied when the picture is\n // read ({@link liveRows}), so a drop, a new mount or a connect that happens\n // between two passes is visible without waiting for the next one.\n state.rows = rows.map((row) =>\n desired.has(row.name) && home?.mounts.has(row.name) !== true\n // A declaration that `lazy` has not mounted yet, or a newly added one.\n ? idleRow(row, LAZY_DETAIL)\n : row,\n )\n state.issues = documentIssues\n state.activationPending = false\n // Start the idle clock for a session that never reported activity, so an\n // unused one still releases its servers.\n state.lastActivityAt ??= Date.now()\n this.refreshStatuses(agent, state)\n // After the status scan, so a mount the watchdog has just flagged reports\n // its stall in the same pass that turned its row into an error.\n state.issues.push(...this.mountDiagnostics(state, projectRoot))\n settle()\n // The rows this session contributes are what they are now: announce them\n // before the pass moves on, so a mount that needed its full connect window\n // does not hold the whole picture back.\n this.notify()\n }\n\n /**\n * Start one declared server in the session's mount home and record the mount,\n * which every session that home serves then resolves.\n *\n * Exactly one `info` line is written per created process — never on a rescan\n * that re-derives the same mount, and never when another session of the\n * project attaches to a shared instance that is already running — so an\n * operator can tell which session caused a server to start, in which project,\n * and what asked for it.\n *\n * The registration is the whole of what this pass does here: the fiber's\n * activation is *watched*, never awaited, so a server that never answers\n * costs the pass — and with it every turn waiting on that pass — nothing.\n * The mount is recorded before the wait, so a later pass finds it in place\n * and mounts nothing a second time; the outcome reaches the row through\n * {@link observeActivation} on failure and through {@link refreshStatuses}\n * on success.\n * @param state - the session whose pass creates the instance.\n * @param home - the scope the instance belongs to: the project's shared one,\n * or the session's own when it could not join the project's chain.\n * @param name - declared `serverName`.\n * @param entry - the parsed declaration to mount.\n * @param trigger - why this pass was allowed to start it.\n * @param alias - local name to register under, when a profile instance owns\n * the declared one and the user chose to see the project's copy too.\n */\n private mount(\n state: AgentState,\n home: MountHome,\n name: string,\n entry: ParsedEntry,\n trigger: MountTrigger,\n alias?: string,\n ): void {\n const config = entry.config\n if (config === undefined) return\n const runtimeName = runtimeNameOf(entry, alias)\n const mount: MountedInstance = {\n name,\n runtimeName,\n projectRoot: home.projectRoot,\n fingerprint: fingerprint(config),\n fiber: undefined,\n status: 'connecting',\n detail: undefined,\n detailCode: undefined,\n detailParams: undefined,\n source: entry.source,\n transport: config.transport,\n endpoint: describeEndpoint(config),\n startedAt: Date.now(),\n stalled: false,\n failed: false,\n }\n home.mounts.set(name, mount)\n // The row turns `connecting` the moment the mount exists; announcing it here\n // is what makes a `Retry` visible in the panel while the server is still\n // booting, instead of only when the pass that started it returns.\n this.notify()\n try {\n const scope = this.ensureProjectScope(home as ProjectState)\n if (scope === undefined) {\n throw new Error('the project scope could not be minted, so the instance has no scope to register in')\n }\n const plugin = this.options.plugin ?? mcpClient\n // Call through the receiver: `ctx.plugin` is a context-bound method and\n // an extracted reference would lose `this`.\n const target = scope.ctx as unknown as {\n plugin(plugin: unknown, config: unknown): MountFiber\n }\n const fiber = target.plugin(plugin, clientConfig(runtimeConfigOf(config, runtimeName)))\n mount.fiber = fiber\n const sharing: CodedText = state.parentLinked\n ? { code: 'mount.sharingShared', text: 'one shared instance for every session of this project' }\n : {\n code: 'mount.sharingForwarded',\n text: \"one shared instance for this project, forwarded into this session's own layer\",\n }\n this.logLifecycle({\n at: Date.now(),\n level: 'info',\n logLevel: 'info',\n projectRoot: mount.projectRoot,\n sessionId: state.agent.id,\n server: name,\n message: `mounting for session ${state.agent.id} (trigger: ${trigger}; ${sharing.text})`,\n code: 'mount.starting',\n params: { sessionId: state.agent.id, trigger, sharingCode: sharing.code },\n line: `mounting ${name}${runtimeName === name ? '' : ` as ${runtimeName}`} for session ${state.agent.id} in ${home.projectRoot} (trigger: ${trigger}; ${sharing.text})`,\n })\n // Not awaited: the pass returns with the mount recorded and `connecting`,\n // and whatever the activation turns out to be is written from behind it.\n this.observeActivation(home, mount, `activation of ${name}`, fiber)\n } catch (error) {\n this.recordMountFailure(home, mount, error)\n }\n }\n\n /**\n * Publish one lifecycle event, and announce it.\n *\n * The plugin's five lifecycle facts — mounting, `is up`, a stall, a failed\n * mount, unmounting — leave the runtime through this one method and no other,\n * and the snapshot announcement follows every one of them, as it did when each\n * site kept the three writes in step by hand. What the DSH log prints and what\n * the ring holds are the subscribers' business now: the runtime only says what\n * happened (`src/notifications.ts`).\n * @param event - the fact, already carrying its level, session and server.\n */\n private logLifecycle(event: PluginEvent): void {\n emitEvent(event)\n this.notify()\n }\n\n /**\n * Watch one mount's activation in the background, so the registering pass\n * never waits for it.\n *\n * A failure is the one outcome the pass used to report itself, and it is\n * written exactly as it was when it did: the row turns `error`, `failed`\n * keeps {@link refreshStatuses} from polling a dead fiber, and the detail is\n * {@link failureDetail}. A success and a timeout write nothing — a mount\n * whose tools became visible is turned `active` by the status scan of the\n * next pass, which logs the `is up` line, and a mount that is merely slow is\n * the watchdog's stall to report.\n *\n * Nothing awaits the returned promise, so it must never reject: `waitFor`\n * already answers a rejected fiber with `{ kind: 'failed' }`, and the final\n * `catch` is the backstop for the recorder itself.\n * @param home - the home the mount was recorded in, read to see it is current.\n * @param mount - the mount whose activation this watches.\n * @param label - the wait label, as `waitFor` names it in the debug line.\n * @param fiber - the fiber whose activation this watches.\n */\n private observeActivation(\n home: MountHome,\n mount: MountedInstance,\n label: string,\n fiber: MountFiber,\n ): void {\n void this.settleActivation(home, mount, label, fiber).catch((error: unknown) => {\n this.ctx.logger.warn(\n `project-mcp: watching the activation of ${mount.name} failed: ${errorText(error)}`,\n )\n })\n }\n\n /**\n * The watched wait itself: one activation to its outcome, then the failure\n * written if it had one.\n * @param home - the home the mount was recorded in.\n * @param mount - the mount whose activation this waits for.\n * @param label - the wait label, as `waitFor` names it in the debug line.\n * @param fiber - the fiber whose activation this waits for.\n */\n private async settleActivation(\n home: MountHome,\n mount: MountedInstance,\n label: string,\n fiber: MountFiber,\n ): Promise<void> {\n const outcome = await this.waitFor(label, activation(fiber))\n // A later pass may already have dropped or replaced this mount — an operator\n // retry, an edited declaration, a teardown. The fiber going down with its\n // home is not a failure of a mount nobody serves any more.\n if (home.mounts.get(mount.name) !== mount) return\n if (outcome.kind === 'failed') {\n this.recordMountFailure(home, mount, outcome.error)\n this.announceHome(home)\n return\n }\n // The server's tools exist as of this moment, so this is where the sessions\n // that read the project through the bridge actually receive them: the mount\n // was registered before its fiber had published anything, and a session whose\n // key predates that registration has no other signal. On a real registry the\n // `tools/change` subscription carries the same news.\n this.syncBridgesOf(home)\n // Success: the tools may have appeared long after the pass that registered\n // the mount returned, and a deployment with `watch: false` and no idle sweep\n // has no rescan timer to notice. Announcing here is what turns `connecting`\n // into `active` — and logs `is up` — the moment it is true, instead of up to\n // `rescanIntervalMs` later.\n this.announceHome(home)\n }\n\n /**\n * Re-read one home's mounts for every session that holds it, then tell the\n * panels.\n *\n * Called from behind a pass — a mount settles after its pass has returned —\n * so for a deployment without a rescan timer this is the only moment that\n * moves a row off `connecting`. Idempotent: the transition log fires on a\n * change, so a second call for the same mount writes nothing.\n * @param home - the home whose instances settled.\n */\n private announceHome(home: MountHome): void {\n if (this.disposed) return\n for (const state of this.states.values()) {\n if (this.homeOf(state) !== home) continue\n this.refreshStatuses(state.agent, state)\n }\n this.notify()\n }\n\n /**\n * Record a mount that could not be activated: the row's `error`, the detail\n * an operator reads, and the one warning line. Shared by the synchronous\n * registration failures and the watched activations above, so both report\n * the same three facts in the same words.\n * @param home - the home the failed instance belongs to.\n * @param mount - the mount to mark failed.\n * @param error - what the fiber or the registration failed with.\n */\n private recordMountFailure(home: MountHome, mount: MountedInstance, error: unknown): void {\n mount.status = 'error'\n mount.failed = true\n const failure = failureDetail(mount, error)\n mount.detail = failure.text\n mount.detailCode = failure.code\n mount.detailParams = failure.params\n // The Logs tab gets the same three facts, first line as the row's message and\n // the whole detail for its second line. The instance serves every session of\n // its project, so the failure is a project event and names no session.\n this.logLifecycle({\n at: Date.now(),\n level: 'error',\n logLevel: 'warn',\n projectRoot: mount.projectRoot,\n server: mount.name,\n message: `mount failed — ${errorText(error)}`,\n code: 'mount.failed',\n params: { error: errorText(error) },\n detail: mount.detail,\n detailCode: failure.code,\n ...(failure.params === undefined ? {} : { detailParams: failure.params }),\n line: mount.detail,\n })\n }\n\n /**\n * The session-scope context the bridge registers through: the minted scope's\n * context carries the session's scope tag, so a registration made through it\n * lands in exactly this session's layer.\n */\n private bridgeContextOf(scope: Pick<Scope, 'ctx' | 'dispose'>): BridgeContextLike {\n if (this.options.bridgeContext !== undefined) return this.options.bridgeContext(scope)\n return {\n get: (name) => (scope.ctx as unknown as { get(service: string): unknown }).get(name),\n }\n }\n\n /** The registry surface the bridge reads; defaults to the plugin's own. */\n private bridgeRegistry(): BridgeRegistryLike {\n if (this.options.registry !== undefined) return this.options.registry\n const ctx = this.ctx as unknown as {\n tools: {\n get(name: string, scope?: object): ReturnType<BridgeRegistryLike['get']>\n schemas(scope?: object): ReturnType<BridgeRegistryLike['schemas']>\n }\n }\n // Bound through the receiver: an extracted `ctx.tools.get` reference would\n // lose the registry's `this`.\n return {\n get: (name, scope) => ctx.tools.get(name, scope),\n schemas: (scope) => ctx.tools.schemas(scope),\n }\n }\n\n /**\n * Install the forwarding bridge on one session: thin definitions in the\n * session's own layer over the project's live tools.\n *\n * Idempotent while the session keeps its project. The `tools/change`\n * subscription is what keeps the bridge level with a server that publishes\n * its tools long after the pass that registered the mount returned — the\n * session's layer is brought up to date before the next turn reads it.\n * A failure is contained: the session keeps its hold on the project's servers\n * and gets no tools from them until the next pass retries the sync.\n * @param state - the session taking the bridge.\n * @param project - the project whose tools are forwarded.\n */\n private installBridge(state: AgentState, project: ProjectState): void {\n if (state.bridge !== undefined || state.scope === undefined) return\n const context = this.bridgeContextOf(state.scope)\n const registry = this.bridgeRegistry()\n const servers = (): ReadonlySet<string> => this.runtimeNamesOf(state)\n const batch = new ForwardBatch({\n names: () => {\n const project = state.project\n // No project, nothing to probe. An empty key here would read the\n // *global* view instead — every tool any scope registered — and each\n // pass would forward names this session's project never published.\n if (project === undefined) return undefined\n try {\n const names = projectToolNames(\n project.key,\n (scope) => this.bridgeSchemas(scope),\n servers(),\n )\n // A route that cannot take declarations after its first request cannot\n // carry a deferred tool either: the marker would be stripped and the\n // schema sent. So the forwarder list itself becomes the presentation —\n // only what the session offers is registered, and the discovery tool is\n // how the model gets another one for the next step.\n if (state.toolUpdate === false) {\n const offered = this.offeredNamesOf(state)\n return names.filter((name) => offered.has(name))\n }\n return names\n } catch (error) {\n // A probe that failed says nothing about the project's set: the batch\n // it could not describe is the batch that stays live.\n this.ctx.logger.warn(\n `project-mcp: reading the tools to forward to session ${state.agent.id} failed: ${errorText(error)}`,\n )\n return undefined\n }\n },\n deferred: () => this.deferredNamesOf(state),\n register: (names, deferred) => {\n const project = state.project\n if (project === undefined) return () => undefined\n return forwardProjectTools({\n ctx: context,\n project: project.key,\n names,\n deferred: (name) => deferred.has(name),\n registry,\n })\n },\n onError: (error) => this.reportBridgeFailure(state, error),\n })\n const bridge: BridgeForwarders = {\n batch,\n detach: () => undefined,\n }\n // The listener lives on the session scope and is dropped with it, so a\n // released session never keeps syncing against a project it left. It only\n // *notes* the change: the registry emits this once per entry registered and\n // once per entry disposed, and a pass per event is what held the event loop.\n const detach = state.scope.ctx.on('tools/change', () => this.noteBridge(state))\n bridge.detach = typeof detach === 'function' ? (detach as () => void) : () => undefined\n state.bridge = bridge\n this.syncBridge(state)\n }\n\n /**\n * Bring one session's forwarders level with the project's live tools.\n *\n * The pass itself — including the re-entry its own registrations force on it\n * through `tools/change` — belongs to the session's {@link ForwardBatch}; this\n * is where a failure is contained and reported. A failed pass leaves the\n * session with no forwarder until the next pass retries (`namesIn` stays\n * unset), and never takes the session's hold on the project down.\n * @param state - the session whose bridge to sync.\n */\n private syncBridge(state: AgentState): void {\n const bridge = state.bridge\n if (bridge === undefined) return\n try {\n bridge.batch.sync()\n } catch (error) {\n this.reportBridgeFailure(state, error)\n }\n }\n\n /**\n * Note one registry change for one session's bridge, off the emitter's stack.\n *\n * The event this answers is emitted synchronously from inside the registry's\n * own insertion and removal — once per entry in, once per entry out — so one\n * MCP generation swap is a burst of thousands. Running the pass here would\n * make whoever registered a tool pay for every session watching the project,\n * and each pass projects the project's whole catalog. The batch folds the\n * burst into one queued pass instead, which is also why this is not\n * {@link syncBridge}: the read paths, the mount settle and the scope wiring\n * all bring the batch level synchronously, before anything reads the layer.\n * @param state - the session whose bridge noticed the change.\n */\n private noteBridge(state: AgentState): void {\n state.bridge?.batch.note()\n }\n\n /**\n * Write the one warning line a failed bridge pass is allowed.\n *\n * Shared by the synchronous pass and by the one a batch runs on its own: a\n * scheduled pass has no caller left to propagate its failure to, so the batch\n * hands it here through `onError` rather than swallowing it.\n * @param state - the session whose bridge failed.\n * @param error - what the pass threw.\n */\n private reportBridgeFailure(state: AgentState, error: unknown): void {\n this.ctx.logger.warn(\n `project-mcp: forwarding the tools of ${state.project?.projectRoot ?? 'the project'} into session ${state.agent.id} failed: ${errorText(error)}`,\n )\n }\n\n /** The project scope's visible schemas, as {@link projectToolNames} reads them. */\n private bridgeSchemas(scope: object): ReturnType<BridgeRegistryLike['schemas']> {\n return this.bridgeRegistry().schemas(scope)\n }\n\n /** Drop one session's bridge: its forwarders and its subscription. Idempotent. */\n private dropBridge(state: AgentState): void {\n const bridge = state.bridge\n if (bridge === undefined) return\n state.bridge = undefined\n try {\n bridge.batch.drop()\n } catch (error) {\n this.ctx.logger.warn(\n `project-mcp: dropping the forwarded tools of session ${state.agent.id} failed: ${errorText(error)}`,\n )\n }\n try {\n bridge.detach()\n } catch {\n // The scope disposal that follows drops the same subscription; a throw\n // here must not keep the session's hold from being released.\n }\n }\n\n /**\n * The project's shared scope, minted with its first mount. One scope per\n * project is what makes mcp-client's `serverName` reservation per project\n * rather than per session, and it is disposed when the project's last holder\n * lets go, so the instance lifetime matches a per-session mount's.\n * @param project - the project to mount into.\n * @returns the scope, reused when the project already has one.\n */\n private ensureProjectScope(project: ProjectState): Pick<Scope, 'ctx' | 'dispose'> {\n const existing = project.scope\n if (existing !== undefined) return existing\n const scope = this.mintScope(project.key)\n project.scope = scope\n return scope\n }\n\n /**\n * Wait for one fiber operation, bounded by `connectTimeoutMs`. A server that\n * never answers must not hold a pass (or a project's teardown) open forever;\n * the fiber stays alive and later passes keep watching it.\n */\n private async waitFor<T>(label: string, wait: Promise<T>): Promise<WaitOutcome<T>> {\n const limit = this.config.connectTimeoutMs\n const settled = wait.then(\n (value): WaitOutcome<T> => ({ kind: 'settled', value }),\n (error): WaitOutcome<T> => ({ kind: 'failed', error }),\n )\n if (limit <= 0) return await settled\n const outcome = await Promise.race([\n settled,\n delay(limit).then((): WaitOutcome<T> => ({ kind: 'timeout' })),\n ])\n if (outcome.kind === 'timeout') {\n this.ctx.logger.debug?.(\n `project-mcp: ${label} did not settle within ${formatSeconds(limit)}; the pass continues without it`,\n )\n }\n return outcome\n }\n\n /**\n * Whether every mount has settled, so a rescan can return without work. A\n * stalled mount keeps the pass alive on purpose: only a fresh status scan can\n * notice that the client's background retry finally connected.\n */\n private settled(state: AgentState): boolean {\n for (const mount of this.mountsOf(state).values()) {\n if (mount.stalled) return false\n if (mount.status !== 'active' && mount.status !== 'error') return false\n }\n return true\n }\n\n /**\n * Mint one scope through the injected factory, or through the module itself.\n * The parent link of a session key is established by {@link holdProject} before\n * this runs and deliberately not passed as `createScope`'s own `parent`\n * option: binding twice on one key throws, and the retained binding is what\n * makes a release and a project change re-linkable.\n * @param key - session key or project key the scope's registrations own.\n * @returns the minted scope.\n */\n private mintScope(key: AgentLike | ProjectScopeKey): Pick<Scope, 'ctx' | 'dispose'> {\n if (this.options.createScope !== undefined) return this.options.createScope(this.ctx, key)\n return createScope(this.ctx, key)\n }\n\n /**\n * Mint the session scope on first use and install the session wiring on it:\n * the project-MCP guidance section and, when activation is on, the wiring\n * that lets a project's MCP tools be *found* (`mcp_search_tools`) and put\n * back into an assembly a presentation plugin filtered.\n *\n * Both are installed once per scope and both read the project's live state, so\n * a rescan that changes the mounted set changes what they say without\n * re-registering anything. `detach` disposes the scope and releases the wiring\n * explicitly, and the next attach installs a fresh one over the surviving\n * session state.\n *\n * A failed mint is contained: the session keeps its hold on the shared mounts\n * (they are registered on the project scope, which is unaffected) and only\n * loses its own wiring, instead of failing the pass.\n */\n private ensureSessionScope(agent: AgentLike, state: AgentState): void {\n if (state.scope !== undefined) return\n let scope: Pick<Scope, 'ctx' | 'dispose'>\n try {\n scope = this.mintScope(state.agent)\n } catch (error) {\n this.ctx.logger.warn(\n `project-mcp: minting the scope of session ${agent.id} failed: ${errorText(error)}`,\n )\n return\n }\n state.scope = scope\n // The guidance section is independent of activation: with activation off\n // every tool is listed and the section only names the mount, so it stays a\n // true statement either way.\n if (this.config.guidanceEnabled ?? DEFAULT_GUIDANCE_ENABLED) {\n try {\n state.guidanceDispose = installGuidance({\n ctx: scope.ctx as unknown as GuidanceContextLike,\n text: () => this.guidanceText(agent, state),\n onError: (error) => {\n this.ctx.logger.warn(\n `project-mcp: guidance section failed for session ${agent.id}: ${errorText(error)}`,\n )\n },\n })\n } catch (error) {\n this.ctx.logger.warn(\n `project-mcp: guidance wiring failed for session ${agent.id}: ${errorText(error)}`,\n )\n }\n }\n if (!(this.config.activationEnabled ?? DEFAULT_ACTIVATION_ENABLED)) return\n try {\n state.activationDispose = installActivation({\n ctx: scope.ctx as unknown as ActivationContextLike,\n state: () => this.seedActivation(state),\n setState: (next) => {\n state.activation = next\n },\n available: () => this.activationCandidates(state),\n visible: () => this.visibleSchemas(state),\n foreign: () => this.foreignNamesOf(state),\n // The policy is read at every assembly rather than captured here, so a\n // mode or pin stored from the panel applies from the next model step on\n // without re-minting the scope the listener lives in.\n policy: () => this.policyFor(state.projectRoot),\n // The presentation lives in this session's own forwarders (they carry\n // `deferLoading`), so every move of the offered set re-applies it there.\n // `note` and not `sync`: the pass belongs off the caller's stack, and a\n // burst of activation settles in one queued pass.\n onOfferedChanged: () => state.bridge?.batch.note(),\n // The step the session is on, read when a search activates names: the\n // wiring keeps no counter of its own, because an activation outlives\n // the scope the wiring lives in and its stamp has to outlive it too.\n step: () => state.step,\n onActivated: (names, step) => {\n for (const name of names) state.steps.set(name, step)\n },\n onCompaction: () => {\n // A step record belongs to the activation it was made for, so the ones\n // a compaction just dropped go with them — while a tool the session\n // really used keeps the step its offer happened on.\n this.pruneStepRecords(state)\n },\n autoState: state.auto ?? createAutoOfferState(),\n setAutoState: (next) => {\n state.auto = next\n },\n ...(this.config.activationAutoLimit === undefined\n ? {}\n : { autoLimit: this.config.activationAutoLimit }),\n ...(this.config.activationAutoStickySteps === undefined\n ? {}\n : { autoStickySteps: this.config.activationAutoStickySteps }),\n ...(this.config.activationToolBudgetChars === undefined\n ? {}\n : { toolBudgetChars: this.config.activationToolBudgetChars }),\n onError: (error) => {\n this.ctx.logger.warn(\n `project-mcp: activation failed for session ${agent.id}: ${errorText(error)}`,\n )\n },\n })\n } catch (error) {\n this.ctx.logger.warn(\n `project-mcp: activation wiring failed for session ${agent.id}: ${errorText(error)}`,\n )\n }\n }\n\n /**\n * The session's activation state, seeded from its project's counters on first\n * use. Later scopes of the same session keep it; only a project change or a\n * teardown drops it.\n */\n private seedActivation(state: AgentState): ActivationState {\n const existing = state.activation\n if (existing !== undefined) return existing\n const projectRoot = state.projectRoot\n const usage = projectRoot === undefined ? undefined : this.options.usage?.forProject(projectRoot)\n const seeded = createActivationState(\n seedFromUsage(usage, {\n count: this.config.activationSeeded ?? DEFAULT_ACTIVATION_SEEDED,\n minCalls: this.config.activationMinCalls ?? DEFAULT_ACTIVATION_MIN_CALLS,\n }),\n )\n state.activation = seeded\n return seeded\n }\n\n /**\n * The schemas this plugin may offer this session: exactly the tools whose\n * public name belongs to a server it mounted for this agent's project. A\n * profile-level or other-project tool is never a candidate, and the prefix is\n * never parsed blindly — the runtime's own mount records decide.\n */\n private activationCandidates(state: AgentState): ToolSchemaLike[] {\n const servers = this.runtimeNamesOf(state)\n if (servers.size === 0) return []\n return this.mountedSchemas(state)\n .filter((schema) => matchServer(schema.name, servers) !== undefined)\n }\n\n /**\n * The schemas the session's own mount home publishes, read through the home's\n * scope key rather than the session's.\n *\n * The two are the same catalog by construction: a session that joined the\n * project's chain resolves the project's layer, and a session that could not\n * gets exactly those tools forwarded into its own layer. Reading the home's\n * view is what keeps this probe independent of the forwarding timing — a\n * server is up as soon as its tools are registered on the project scope, and\n * a bridge sync that has not run yet must not read as \"not up\".\n * @param state - the session whose home is probed.\n * @returns the visible schemas of its home, or none while it holds nothing.\n */\n private mountedSchemas(state: AgentState): ToolSchemaLike[] {\n const home = this.homeOf(state)\n if (home === undefined) return []\n // A bridge is kept level by the mount, activation and `tools/change`\n // signals; this is the same sync on the read path, so a session's own layer\n // can never lag behind the catalog this probe returns. Unchanged names\n // short-circuit inside, so the cost is one name comparison.\n this.syncBridge(state)\n return this.schemasOf(home, state.agent.id)\n }\n\n /**\n * The visible catalog of one mount home, read through the home's scope key.\n *\n * The single read both callers share: the activation probe asks for the whole\n * catalog, and the on-demand detail route asks it for one definition — reading\n * through the same key is what makes a deferred name answer exactly like an\n * offered one, because the home's catalog carries the whole mounted surface\n * and the deferral decision only lives in the request.\n *\n * @param home - the mount home whose registrations are read.\n * @param agentId - the session the read is attributed to, for the warning.\n * @returns the home's schemas, or none when the read fails.\n */\n private schemasOf(home: MountHome, agentId: string): ToolSchemaLike[] {\n try {\n return this.ctx.tools.schemas(home.key)\n } catch (error) {\n this.ctx.logger.warn(\n `project-mcp: reading the tool catalog of session ${agentId} failed: ${errorText(error)}`,\n )\n return []\n }\n }\n\n /**\n * Every MCP schema the session's own scope chain resolves beyond this\n * plugin's project mounts: the profile plane and any F-19 forwarders. Read\n * through the session's key rather than the home's, so the deferral budget\n * and the discovery tool measure the whole surface the request actually\n * carries. Only `mcp__`-prefixed names enter, and the discovery tool is left\n * out by value — not by prefix — so the activation wiring can offer it on its\n * own. The per-server usage counters stay on the project plane: this probe\n * reads the catalog, never the counters.\n *\n * @param state - the session whose visible surface is probed.\n * @returns the visible MCP schemas, or none when the read fails.\n */\n private visibleSchemas(state: AgentState): ToolSchemaLike[] {\n try {\n return this.ctx.tools.schemas(state.agent).filter(\n (schema) => schema.name.startsWith('mcp__') && schema.name !== SEARCH_TOOL_NAME,\n )\n } catch (error) {\n this.ctx.logger.warn(\n `project-mcp: reading the visible MCP surface of session ${state.agent.id} failed: ${errorText(error)}`,\n )\n return []\n }\n }\n\n /**\n * The MCP tool names this session must never be offered: everything another\n * project mounted in this process publishes. The union is read through each\n * other project's own scope key — not the session's — so a name the host\n * defect leaked into the session's chain is caught here by provenance rather\n * than by prefix. Conservative, so a name the session may legitimately see is\n * never marked foreign: the set subtracts the session's own project's runtime\n * names and every profile-level server name (a profile entry is none of this\n * plugin's business even when another project declares the same name).\n * @param state - the session whose request is being assembled.\n * @returns the foreign tool names, or none when the read fails.\n */\n private foreignNamesOf(state: AgentState): ReadonlySet<string> {\n const own = this.runtimeNamesOf(state)\n const profile = this.profileServerNames()\n const legitimate = new Set<string>([...own, ...profile])\n const foreign = new Set<string>()\n for (const project of this.projects.values()) {\n if (project.projectRoot === state.projectRoot) continue\n let schemas: ToolSchemaLike[]\n try {\n schemas = this.ctx.tools.schemas(project.key)\n } catch (error) {\n this.ctx.logger.warn(\n `project-mcp: reading another project's catalog for session ${state.agent.id} failed: ${errorText(error)}`,\n )\n continue\n }\n for (const schema of schemas) {\n if (!schema.name.startsWith('mcp__')) continue\n if (matchServer(schema.name, legitimate) !== undefined) continue\n foreign.add(schema.name)\n }\n }\n return foreign\n }\n\n /**\n * The live text of the session's guidance section.\n *\n * It reads the mount records and the registry at every assembly, so a rescan\n * that mounted or dropped a server — and a search that activated a tool — are\n * reflected without re-registering the section. Total: any failure returns the\n * empty string, because a section that throws would fail the model request\n * that asked for the assembly.\n */\n private guidanceText(agent: AgentLike, state: AgentState): string {\n try {\n const projectRoot = state.projectRoot\n if (projectRoot === undefined || this.mountsOf(state).size === 0) return ''\n const activationEnabled = this.config.activationEnabled ?? DEFAULT_ACTIVATION_ENABLED\n // With activation on, the presented set is the session's counter baseline\n // plus its activations; with it off, the registry lists every tool.\n const presented = activationEnabled ? presentedNames(this.seedActivation(state)) : undefined\n // Matched by the name each mount registers under, never by its declared\n // one: a shadowed declaration carries a local alias, and a registry lookup\n // by the contested name would drop its tools from the count.\n const mounted = new Set([...this.mountsOf(state).values()].map((mount) => mount.runtimeName))\n const toolsByServer = new Map<string, string[]>()\n const offered: string[] = []\n const deferred: string[] = []\n for (const schema of this.mountedSchemas(state)) {\n const server = matchServer(schema.name, mounted)\n if (server === undefined) continue\n const name = schema.name.slice(`mcp__${server}__`.length)\n const tools = toolsByServer.get(server)\n if (tools === undefined) toolsByServer.set(server, [name])\n else tools.push(name)\n if (presented === undefined || presented.has(schema.name)) offered.push(name)\n else deferred.push(name)\n }\n const servers: GuidanceServer[] = [...this.mountsOf(state).values()].map((mount) => ({\n name: mount.name,\n status: mount.status,\n ...(mount.transport === undefined ? {} : { transport: mount.transport }),\n tools: toolsByServer.get(mount.runtimeName) ?? [],\n }))\n // The seeded baseline's insertion order is the usage rank order\n // (most-called first); keep it and strip the server prefix, so the\n // guidance names the session's hot tools like every other short name.\n const mostUsed: string[] = []\n if (activationEnabled) {\n for (const fullName of this.seedActivation(state).baseline) {\n const server = matchServer(fullName, mounted)\n if (server !== undefined) mostUsed.push(fullName.slice(`mcp__${server}__`.length))\n }\n }\n return buildGuidance({\n project: projectLabel(projectRoot, homedir()),\n servers,\n offered,\n deferred,\n mostUsed,\n activationEnabled,\n // Where the route cannot declare a tool after the first request, the\n // names line below must send the model through the search instead of\n // promising a call that would answer \"unknown tool\".\n directCalls: state.toolUpdate !== false,\n })\n } catch (error) {\n this.ctx.logger.warn(\n `project-mcp: building guidance for session ${agent.id} failed: ${errorText(error)}`,\n )\n return ''\n }\n }\n\n /**\n * Record a call against the session's activation state: it refreshes the\n * freshness of a session-activated tool, and it is the evidence a later\n * compaction keeps that activation by. It rides the same `tools/result`\n * subscription the counters use, so no second observer exists.\n * @param agentId - calling agent, when the call was agent-scoped.\n * @param toolName - public registry name of the call.\n */\n noteToolUse(agentId: string | undefined, toolName: string): void {\n if (agentId === undefined) return\n const state = this.states.get(agentId)\n if (state?.activation === undefined) return\n state.activation = noteUse(state.activation, toolName, Date.now())\n }\n\n /** Drop the session-activated tools that outlived `toolIdleMs` without a call. */\n private pruneActivation(state: AgentState): void {\n const current = state.activation\n if (current === undefined) return\n state.activation = pruneIdle(current, Date.now(), this.config.toolIdleMs ?? DEFAULT_TOOL_IDLE_MS)\n // A step record belongs to the activation it was made for, so a name that\n // fell out of the window takes its record with it; one that returns is\n // stamped again with the step it returns on.\n if (state.activation !== current) this.pruneStepRecords(state)\n }\n\n /**\n * Drop the step records whose activation the session no longer holds.\n *\n * Called wherever activations end — the idle sweep and a compaction — so a\n * record never outlives the offer it was made for, and a name the session\n * still offers keeps the step its offer happened on.\n * @param state - the session whose records are reconciled.\n */\n private pruneStepRecords(state: AgentState): void {\n const active = state.activation?.active\n for (const name of [...state.steps.keys()]) {\n if (active === undefined || !active.has(name)) state.steps.delete(name)\n }\n }\n\n private async unmount(home: MountHome, name: string, reason: CodedText): Promise<void> {\n const mount = home.mounts.get(name)\n if (mount === undefined) return\n home.mounts.delete(name)\n this.logUnmount(home, mount, reason)\n await this.disposeFiber(mount)\n }\n\n /**\n * The line that closes a mount's life, the pair of the `mounting` line.\n *\n * The reason is the part a reader cannot infer from the log's order: an edit,\n * an idle release, an operator retry and a session teardown all unmount, and\n * only some of them are followed by a mount of the same server. The run time\n * tells a server that never came up from one that served and was replaced.\n * @param home - the home the instance lived in.\n * @param mount - the instance going away.\n * @param reason - why it is going away: the operator's sentence and its wire\n * code (F-48), nested two-level into the `unmounting` event as `reasonCode`.\n */\n private logUnmount(home: MountHome, mount: MountedInstance, reason: CodedText): void {\n const now = Date.now()\n const ran = formatDuration(now - mount.startedAt)\n // `unmounting` after a failure is the tail of that failure, so the tab keeps\n // it red; every other release is a warning. The instance serves every session\n // of its project, so its release is a project event that names no session.\n this.logLifecycle({\n at: now,\n level: mount.failed ? 'error' : 'warn',\n logLevel: 'info',\n projectRoot: mount.projectRoot,\n server: mount.name,\n message: `unmounting — ${reason.text} (it ran for ${ran})`,\n code: 'unmounting',\n params: { reasonCode: reason.code, ran },\n ...(mount.detail === undefined ? {} : { detail: mount.detail }),\n ...(mount.detailCode === undefined ? {} : { detailCode: mount.detailCode }),\n ...(mount.detailParams === undefined ? {} : { detailParams: mount.detailParams }),\n line: `unmounting ${mount.name} in ${home.projectRoot} — ${reason.text} (it ran for ${ran})`,\n })\n }\n\n /**\n * Bring every foreign holder of one home level with its live tools.\n *\n * The mount and unmount sites call this because they are the moments the\n * project's tool set actually changes: a session's own pass can run before the\n * server it shares has published anything (its own mount is only registered\n * after the hold), and this is what fills its forwarders in behind it. The\n * `tools/change` subscription and the read-path sync cover the same event on\n * a real registry; a third trigger costs nothing, because an unchanged name\n * set short-circuits.\n * @param home - the home whose tools changed.\n */\n private syncBridgesOf(home: MountHome): void {\n for (const state of this.states.values()) {\n if (state.bridge !== undefined && state.project === home) this.syncBridge(state)\n }\n }\n\n private async disposeFiber(mount: MountedInstance): Promise<void> {\n const fiber = mount.fiber\n mount.fiber = undefined\n if (fiber === undefined) return\n const outcome = await this.waitFor(\n `disposal of ${mount.name}`,\n Promise.resolve().then(() => fiber.dispose()),\n )\n if (outcome.kind === 'failed') {\n this.ctx.logger.warn(`project-mcp: disposing ${mount.name} failed: ${errorText(outcome.error)}`)\n }\n }\n\n /**\n * Refresh `active`/`connecting` from the tools actually visible to the agent,\n * and turn a mount that never produced a tool into a detailed `error` row.\n * The watchdog is strictly read-only: it never disposes a slow server, and a\n * mount that connects later returns to `active` on its own.\n */\n private refreshStatuses(agent: AgentLike, state: AgentState): void {\n const timeout = this.config.connectTimeoutMs\n const now = Date.now()\n for (const mount of this.mountsOf(state).values()) {\n // Activation failed outright: the fiber is dead, so there is nothing to\n // poll and nothing to revive without a new mount (`projectMcp.retry()`).\n if (mount.failed) continue\n if (this.hasTools(state, mount.runtimeName)) {\n if (mount.status !== 'active') {\n const elapsed = formatDuration(now - mount.startedAt)\n // Success is an event of its own level: the tab draws it green, not as\n // one more info line, and the line names the session that sees it.\n this.logLifecycle({\n at: now,\n level: 'up',\n logLevel: 'info',\n projectRoot: mount.projectRoot,\n sessionId: agent.id,\n server: mount.name,\n message: `is up — tools visible to session ${agent.id} after ${elapsed}`,\n code: 'mount.up',\n params: { sessionId: agent.id, elapsed },\n line: `${mount.name} is up in ${state.projectRoot ?? 'the project'} — its tools are visible to session ${agent.id} after ${elapsed}`,\n })\n }\n mount.status = 'active'\n mount.detail = undefined\n mount.detailCode = undefined\n mount.detailParams = undefined\n mount.stalled = false\n continue\n }\n const elapsed = now - mount.startedAt\n if (timeout > 0 && elapsed >= timeout) {\n const firstReport = !mount.stalled\n mount.status = 'error'\n mount.stalled = true\n const stall = stallDetail(mount, elapsed)\n mount.detail = stall.text\n mount.detailCode = stall.code\n mount.detailParams = stall.params\n if (firstReport) {\n // Reported once per stall (the watchdog re-reads it every pass), with\n // the three facts the row shows and no retry advice.\n this.logLifecycle({\n at: now,\n level: 'warn',\n logLevel: 'warn',\n projectRoot: mount.projectRoot,\n sessionId: agent.id,\n server: mount.name,\n message: `no tool appeared in ${formatDuration(elapsed)}`,\n code: 'mount.stalled',\n params: { elapsed: formatDuration(elapsed) },\n detail: stall.text,\n detailCode: stall.code,\n ...(stall.params === undefined ? {} : { detailParams: stall.params }),\n line: stall.text,\n })\n }\n continue\n }\n mount.status = 'connecting'\n mount.stalled = false\n mount.detail = undefined\n mount.detailCode = undefined\n mount.detailParams = undefined\n }\n }\n\n /**\n * The session's rows with their live mount state applied.\n *\n * Read-time, not stored: a mount that appears, connects or fails between two\n * passes changes what a panel must show, while the row belongs to the pass\n * that last re-derived it. Decorating here is what lets the status channel\n * report a mount the moment the pass creates it, rather than when that pass\n * finally returns.\n * @param state - the session whose rows to read.\n * @returns one row per declaration, in document order.\n */\n private liveRows(state: AgentState): ServerRow[] {\n const mounts = this.mountsOf(state)\n return state.rows.map((row) => decorate(row, mounts.get(row.name)))\n }\n\n /** Mount failures of this pass, published as first-class snapshot issues. */\n private mountDiagnostics(state: AgentState, projectRoot: string): SnapshotIssue[] {\n const diagnostics: SnapshotIssue[] = []\n for (const mount of this.mountsOf(state).values()) {\n if (mount.status !== 'error' || mount.detail === undefined) continue\n diagnostics.push({\n source: mount.source ?? projectRoot,\n server: mount.name,\n level: 'error',\n message: mount.detail,\n // The detail's wire companions ride along, so the issue translates the\n // same way the event's detail does (F-48).\n ...(mount.detailCode === undefined ? {} : { code: mount.detailCode }),\n ...(mount.detailParams === undefined ? {} : { params: mount.detailParams }),\n })\n }\n return diagnostics\n }\n\n private hasTools(state: AgentState, serverName: string): boolean {\n const prefix = `mcp__${serverName}__`\n return this.mountedSchemas(state).some((schema) => schema.name.startsWith(prefix))\n }\n\n /**\n * Global documents of this deployment, lowest priority first. Read before a\n * project's own documents, so a project declaration always wins.\n */\n private globalFiles(): string[] {\n return globalConfigPaths(this.config.globalFiles)\n }\n\n /**\n * Every document one project is configured to read, in priority order — the\n * order they are read in, which is what the panel's `priority n/total` counts.\n */\n private readFiles(projectRoot: string): ConfiguredFile[] {\n return [\n ...this.globalFiles().map((path): ConfiguredFile => ({ path, scope: 'global' })),\n ...localConfigPaths(projectRoot, this.config.localFiles).map(\n (path): ConfiguredFile => ({ path, scope: 'project' }),\n ),\n ]\n }\n\n private readProject(projectRoot: string): {\n entries: ParsedEntry[]\n issues: ParseIssue[]\n documents: Map<string, DocumentInfo>\n /**\n * Every document that declared each `serverName`, in declaration order —\n * lowest priority first, exactly the order {@link mergeEntries} applies, so\n * the winner of a duplicated name is the last path recorded here.\n */\n sources: Map<string, string[]>\n } {\n const paths = [...this.globalFiles(), ...localConfigPaths(projectRoot, this.config.localFiles)]\n const resolveContext = this.resolveContext(projectRoot)\n const groups: ParsedEntry[][] = []\n const issues: ParseIssue[] = []\n const documents = new Map<string, DocumentInfo>()\n const sources = new Map<string, string[]>()\n for (const path of paths) {\n const document = this.readDocument(path, resolveContext)\n if (document === undefined) continue\n groups.push(document.entries)\n issues.push(...document.issues)\n documents.set(path, this.documentInfo(path, projectRoot, document, resolveContext))\n for (const entry of document.entries) {\n const declared = sources.get(entry.name)\n if (declared === undefined) sources.set(entry.name, [path])\n else if (!declared.includes(path)) declared.push(path)\n }\n }\n const { entries, overridden } = mergeEntries(groups)\n for (const name of new Set(overridden)) {\n issues.push({\n source: projectRoot,\n server: name,\n level: 'warning',\n message: `serverName \"${name}\" was declared in more than one document; the highest-priority definition wins`,\n // The code the client's file grouping compares — never the prose,\n // which the client may have translated.\n code: 'parse.server.multiDocument',\n params: { name },\n })\n }\n return { entries, issues, documents, sources }\n }\n\n /**\n * Everything the editor needs about one declaring document: its revision and\n * write tier, plus the entry body of each server that parsed.\n */\n private documentInfo(\n path: string,\n projectRoot: string,\n document: CachedDocument,\n resolveContext: ResolveContext,\n ): DocumentInfo {\n const entries = new Map<string, EntrySnapshot>()\n const declared = document.raw\n if (declared !== undefined) {\n const byName = new Map<string, unknown>()\n for (const [key, value] of Object.entries(declared)) {\n const name = SERVER_NAME_PATTERN.test(key) ? key : slugifyServerName(key)\n if (name !== '') byName.set(name, value)\n }\n for (const entry of document.entries) {\n if (entry.config === undefined) continue\n const raw = byName.get(entry.name)\n entries.set(entry.name, buildEntrySnapshot(raw, entry.config.transport, credentialKeys(raw, resolveContext)))\n }\n }\n const scope = writeScopeFor(path, projectRoot, {\n projectDocuments: localConfigPaths(projectRoot, this.config.localFiles),\n globalDocuments: this.globalFiles(),\n allowGlobalWrite: this.config.allowGlobalWrite === true,\n })\n return { revision: documentRevision(document.text), entries, ...scope }\n }\n\n private readDocument(path: string, resolveContext: ResolveContext): CachedDocument | undefined {\n let stats\n try {\n stats = statSync(path)\n } catch {\n this.documents.delete(path)\n return undefined\n }\n const cached = this.documents.get(path)\n if (\n cached !== undefined &&\n cached.mtimeMs === stats.mtimeMs &&\n cached.size === stats.size &&\n cached.stamp === (resolveContext.stamp ?? '')\n ) {\n return cached\n }\n let text: string\n try {\n text = readFileSync(path, 'utf8')\n } catch {\n return undefined\n }\n const parsed = parseDocument(text, path, resolveContext)\n let raw: Record<string, unknown> | undefined\n try {\n raw = extractServerMap(JSON.parse(text) as unknown) ?? undefined\n } catch {\n // Invalid JSON: `parseDocument` already reported it per entry.\n raw = undefined\n }\n const document: CachedDocument = {\n mtimeMs: stats.mtimeMs,\n size: stats.size,\n text,\n stamp: resolveContext.stamp ?? '',\n raw,\n entries: parsed.entries,\n issues: parsed.issues,\n }\n this.documents.set(path, document)\n return document\n }\n\n private resolveContext(projectRoot: string): ResolveContext {\n const dotenv = this.readProjectEnv(projectRoot)\n const secrets = this.readSecrets()\n return {\n env: process.env,\n dotenv: dotenv.values,\n inputs: this.config.inputs,\n secrets: secrets.values,\n stamp: `${dotenv.stamp}\\u0001${secrets.stamp}`,\n projectRoot,\n toolCallTimeoutMs: this.config.toolCallTimeoutMs,\n failOnStartupError: this.config.failOnStartupError,\n }\n }\n\n /**\n * The project's own dotenv values, plus the identity of the files they came\n * from. Documents are merged lowest priority first, so `<project>/.dsh/.env`\n * overrides the plain `<project>/.env`; each file is re-read only when its\n * mtime/size changes, and a file that is gone leaves both the map and the\n * stamp (so deleting `.env` un-resolves its references on the next pass).\n */\n private readProjectEnv(projectRoot: string): { values: Record<string, string>; stamp: string } {\n const values: Record<string, string> = {}\n if (this.config.envFiles === false) return { values, stamp: '' }\n const parts: string[] = []\n for (const path of projectEnvPaths(projectRoot)) {\n let stats\n try {\n stats = statSync(path)\n } catch {\n this.envFiles.delete(path)\n continue\n }\n const cached = this.envFiles.get(path)\n const entry =\n cached !== undefined && cached.mtimeMs === stats.mtimeMs && cached.size === stats.size\n ? cached\n : { mtimeMs: stats.mtimeMs, size: stats.size, values: readEnvFile(path) }\n this.envFiles.set(path, entry)\n Object.assign(values, entry.values)\n parts.push(`${path}:${entry.mtimeMs}:${entry.size}`)\n }\n return { values, stamp: parts.join('|') }\n }\n\n /**\n * Credentials, re-read only when the document changes. Every pass of every\n * session resolves `${input:NAME}` references, so an uncached read here cost\n * one synchronous stat plus YAML parse per session per pass. The stamp is the\n * same identity the document cache compares.\n */\n private readSecrets(): { values: Record<string, string>; stamp: string } {\n const path = this.config.credentialsFile\n let stats\n try {\n stats = statSync(path)\n } catch {\n this.secrets = undefined\n return { values: {}, stamp: '' }\n }\n const stamp = `${stats.mtimeMs}:${stats.size}`\n const cached = this.secrets\n if (cached !== undefined && cached.mtimeMs === stats.mtimeMs && cached.size === stats.size) {\n return { values: cached.values, stamp }\n }\n const values = readSecrets(path)\n this.secrets = { mtimeMs: stats.mtimeMs, size: stats.size, values }\n return { values, stamp }\n }\n\n private profileServerNames(): Set<string> {\n const names = new Set<string>()\n let entries: LoaderEntryLike[] = []\n try {\n const loader = (this.ctx as unknown as { get(name: string): unknown }).get('loader') as\n | LoaderLike\n | undefined\n entries = loader?.entries?.() ?? []\n } catch {\n return names\n }\n for (const entry of entries) {\n const options = entry.options ?? {}\n if (options.disabled === true) continue\n if (!MCP_CLIENT_ENTRY_NAMES.has(String(options.name))) continue\n const name = options.config?.serverName\n if (typeof name !== 'string') continue\n if (entry.fiber?.state === FIBER_ACTIVE) names.add(name)\n }\n return names\n }\n\n /**\n * The other loaded plugin that owns the assembled tool list, if the profile\n * has one.\n *\n * Read from the same `loader.entries()` this plugin already consults for the\n * reserved `serverName`s, for the same reason: the profile is where a second\n * owner is mounted, and a running entry is the only kind that shapes a\n * request. An entry named like a known presentation plugin but not active is\n * mounted-and-stopped, which shapes nothing, so it is reported no more than an\n * absent one is.\n *\n * @returns the owner, or `undefined` when this plugin assembles alone.\n */\n private presentationOwner(): PresentationOwner | undefined {\n let entries: LoaderEntryLike[] = []\n try {\n const loader = (this.ctx as unknown as { get(name: string): unknown }).get('loader') as\n | LoaderLike\n | undefined\n entries = loader?.entries?.() ?? []\n } catch {\n return undefined\n }\n for (const entry of entries) {\n const options = entry.options ?? {}\n if (options.disabled === true) continue\n if (!PRESENTATION_OWNER_ENTRY_NAMES.has(String(options.name))) continue\n if (entry.fiber?.state !== FIBER_ACTIVE) continue\n // The module specifier is what the profile wrote down, so it is the most\n // useful label; the entry id disambiguates two mounts of one module and\n // stands in when a hand-written profile names the plugin by path.\n const name =\n typeof options.name === 'string' && options.name !== ''\n ? options.name\n : typeof options.id === 'string'\n ? options.id\n : ''\n return { name, note: PRESENTATION_OWNER_NOTE, noteCode: 'present.ownerNote' }\n }\n return undefined\n }\n\n /**\n * Keep one watcher set per project with live agents. Only the project's own\n * document directories are watched recursively: an unrelated file storm\n * (install caches, build output, git metadata) never reaches this plugin, so\n * it costs no events and no passes. A flat watch on the project root notices\n * a config directory appearing or disappearing, and the rescan timer is the\n * safety net for anything else.\n */\n private syncWatchers(): void {\n const roots = new Set<string>()\n for (const state of this.states.values()) {\n if (state.projectRoot !== undefined) roots.add(state.projectRoot)\n }\n for (const [root, watchers] of [...this.watchers]) {\n if (roots.has(root)) continue\n this.closeWatchers(root, watchers)\n }\n if (!this.config.watch) return\n for (const root of roots) {\n const existing = this.watchers.get(root)\n if (existing !== undefined) {\n const desired = this.watchTargets(root)\n if (sameTargets(this.watchedDirs.get(root) ?? [], desired)) continue\n this.closeWatchers(root, existing)\n }\n const targets = this.watchTargets(root)\n const watchers = this.watchProject(root, targets)\n if (watchers.length === 0) continue\n this.watchers.set(root, watchers)\n this.watchedDirs.set(root, targets)\n this.watchedRoots.add(root)\n }\n }\n\n private closeWatchers(root: string, watchers: FSWatcher[]): void {\n for (const watcher of watchers) watcher.close()\n this.watchers.delete(root)\n this.watchedDirs.delete(root)\n this.watchedRoots.delete(root)\n }\n\n /** Directories (and document files) worth watching for one root. */\n private watchTargets(root: string): WatchTarget[] {\n const targets: WatchTarget[] = []\n for (const directory of configDirectories(root, this.config.localFiles)) {\n if (directory !== root) targets.push({ path: directory, directory: true })\n }\n // A global document is watched as a file: watching its whole home directory\n // would put the watcher on every unrelated write under `$HOME`.\n for (const file of this.globalFiles()) targets.push({ path: file, directory: false })\n return targets\n }\n\n private watchProject(root: string, targets: readonly WatchTarget[]): FSWatcher[] {\n const onChange = (): void => this.schedule('watch')\n const watchers: FSWatcher[] = []\n const add = (path: string, recursive: boolean): void => {\n try {\n const watcher = watch(path, { recursive, persistent: false }, onChange)\n watcher.on('error', () => undefined)\n watchers.push(watcher)\n } catch {\n // The target can disappear between the existence check and the watch.\n }\n }\n // Flat: catches a config directory appearing or disappearing.\n add(root, false)\n for (const target of targets) {\n if (!target.directory) {\n add(target.path, false)\n continue\n }\n if (this.recursiveWatch !== false) {\n try {\n const watcher = watch(target.path, { recursive: true, persistent: false }, onChange)\n watcher.on('error', () => undefined)\n watchers.push(watcher)\n this.recursiveWatch = true\n continue\n } catch (error) {\n this.recursiveWatch = false\n this.ctx.logger.debug?.(\n `project-mcp: recursive watch unavailable for ${target.path} (${errorText(error)}); using flat watches`,\n )\n }\n }\n add(target.path, false)\n }\n return watchers\n }\n}\n\n/**\n * The real `serverName` conflicts of one reconciled pass, in a stable order.\n *\n * Two declarations fight over a name and only one of them mounts, so a panel\n * that shows the surviving row alone would hide the loss:\n *\n * - `profile` — a profile-level `mcp-client` instance already owns the name. The\n * project's entry does not mount under it while the profile's copy is the one\n * shown (the default); it mounts under a name this project chose otherwise —\n * the local alias, or the contested name itself, where it is the nearer\n * declaration and shadows the profile instance's tools in this project's\n * sessions. It is a conflict only where the profile is allowed to win\n * ({@link RuntimeConfig.profileWins}); the row carries `status: 'conflict'`\n * for exactly the names this project does not mount.\n * - `duplicate` — two documents of one project declare the same name and\n * {@link mergeEntries} keeps the highest-priority declaration, so the other\n * one is silently ignored.\n *\n * Only names defined for this project are reported: a source recorded for a name\n * the merge dropped (a document that reappeared between passes) is a document\n * detail, not a conflict this row set can explain.\n *\n * @param entries - merged entries, one per resolved name.\n * @param sources - declaring documents per name, lowest priority first.\n * @param reserved - profile-reserved names that shadow the project's entry.\n * @param aliases - the local name each shadowed declaration would take, when\n * this project has one to give ({@link resolveConflictNames}); a project with\n * none can still answer `native`, which needs no prefix.\n * @param policy - the project's policy: what the user already chose about each\n * contested name.\n * @returns one report per name, sorted by name; empty when nothing conflicts.\n */\nfunction conflictsFor(\n entries: readonly ParsedEntry[],\n sources: ReadonlyMap<string, string[]>,\n reserved: ReadonlySet<string>,\n aliases: ReadonlyMap<string, string>,\n policy: ToolPolicy,\n): ServerConflict[] {\n const conflicts: ServerConflict[] = []\n for (const entry of entries) {\n const name = entry.name\n // The winner is listed first in both kinds: the profile instance that owns\n // the name, or the document the merge kept, which is the last one to\n // declare it.\n const declared = [...(sources.get(name) ?? [])]\n const winner = declared[declared.length - 1] ?? entry.source\n const others = declared.slice(0, -1).reverse()\n if (reserved.has(name)) {\n const alias = aliases.get(name)\n const choice = aliasesOf(policy)[name] ?? 'profile'\n // The choice is published even where this project has no alias to offer:\n // `native` needs no prefix, so an alias-less project still has two answers\n // and a panel that hid the choice would offer it none.\n conflicts.push({\n server: name,\n kind: 'profile',\n sources: [winner, ...others],\n ...(alias === undefined ? {} : { alias }),\n choice,\n // The prose is byte-identical to what the site always emitted; the\n // code and its flat params ride beside it for the client to translate\n // (F-48).\n ...(alias === undefined\n ? { code: 'conflict.profile', params: { name } }\n : { code: 'conflict.profileAlias', params: { name, alias } }),\n message:\n alias === undefined\n ? `\"${name}\" is owned by a profile-level mcp-client instance, so the project entry does not mount under it; remove the profile entry to use the project one everywhere, or let this project's copy take the name in this project's sessions alone.`\n : `\"${name}\" is owned by a profile-level mcp-client instance; this project's copy mounts as \"${alias}\" when chosen beside it, or under the contested name when chosen to shadow it in this project's sessions, and does not mount at all while the profile's copy is the one shown.`,\n })\n continue\n }\n if (others.length === 0) continue\n conflicts.push({\n server: name,\n kind: 'duplicate',\n sources: [winner, ...others],\n code: 'conflict.documents',\n // Numbers stringify at emission: params are flat strings end to end.\n params: { name, count: String(declared.length), winner },\n message: `\"${name}\" is declared in ${declared.length} documents; ${winner} wins and the other declaration is not mounted.`,\n })\n }\n // Code-unit order, the same rule the rest of the plugin sorts tool names by.\n return conflicts.sort((left, right) =>\n left.server < right.server ? -1 : left.server > right.server ? 1 : 0,\n )\n}\n\nfunction baseRow(entry: ParsedEntry, projectRoot: string, document: DocumentInfo | undefined): ServerRow {\n const snapshot = document?.entries.get(entry.name)\n return {\n name: entry.name,\n status: 'error',\n projectRoot,\n source: entry.source,\n ...(entry.config === undefined ? {} : { transport: entry.config.transport }),\n ...(document === undefined\n ? {}\n : {\n ...(snapshot === undefined ? {} : { entry: snapshot }),\n writeScope: document.scope,\n ...(document.reason === undefined ? {} : { writeBlockedReason: document.reason }),\n // The wire companions ride beside the prose: the client translates\n // the code and falls back to the byte-identical reason.\n ...(document.blockedCode === undefined ? {} : { blockedCode: document.blockedCode }),\n ...(document.blockedParams === undefined ? {} : { blockedParams: document.blockedParams }),\n documentRevision: document.revision,\n }),\n }\n}\n\n/** `env`/`headers` keys of one declared entry whose value comes from credentials. */\nfunction credentialKeys(declared: unknown, resolveContext: ResolveContext): CredentialKeys {\n const record = isRecord(declared) ? declared : {}\n return { env: credentialKeySet(record.env, resolveContext), headers: credentialKeySet(record.headers, resolveContext) }\n}\n\nfunction credentialKeySet(section: unknown, resolveContext: ResolveContext): ReadonlySet<string> {\n const keys = new Set<string>()\n if (!isRecord(section)) return keys\n for (const [key, value] of Object.entries(section)) {\n if (typeof value === 'string' && referencesCredentials(value, resolveContext)) keys.add(key)\n }\n return keys\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\n/** Row of a declared server that is not mounted, with the reason in `detail`. */\nfunction idleRow(row: ServerRow, reason: CodedText): ServerRow {\n // Strip a previous detail's companions too, or a recycled error row would\n // keep a stale code under the new prose.\n const { detail: _stale, detailCode: _staleCode, detailParams: _staleParams, ...rest } = row\n return {\n ...rest,\n status: 'idle',\n detail: reason.text,\n detailCode: reason.code,\n ...(reason.params === undefined ? {} : { detailParams: reason.params }),\n }\n}\n\nfunction formatSeconds(ms: number): string {\n return `${(ms / 1000).toFixed(1)}s`\n}\n\n/**\n * Duration as an operator reads it: milliseconds under a second, seconds under\n * a minute, then minutes and seconds. A watchdog that fires at 40 ms must not\n * print `0.0s`, and a mount that has been waiting for four and a half minutes\n * should not print `266.7s`.\n */\nfunction formatDuration(ms: number): string {\n if (ms < 1000) return `${Math.round(ms)}ms`\n if (ms < 60_000) return `${(ms / 1000).toFixed(1)}s`\n const minutes = Math.floor(ms / 60_000)\n const seconds = Math.round((ms - minutes * 60_000) / 1000)\n return seconds === 60 ? `${minutes + 1}m` : `${minutes}m ${seconds}s`\n}\n\n/** Unref'd timer, so a bounded wait never keeps a process alive on its own. */\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => {\n const timer = setTimeout(resolve, ms)\n timer.unref?.()\n })\n}\n\n/**\n * Endpoint label for an error message. Arguments and query strings are the two\n * places a declared entry can carry a secret (`--api-key=…`, `?token=…`), so\n * neither ever reaches a row, a log line or the snapshot.\n */\nfunction describeEndpoint(config: NonNullable<ParsedEntry['config']>): string {\n if (config.transport === 'streamable-http') return `streamable-http ${visibleUrl(config.url)}`\n return `stdio ${config.command}`\n}\n\n/**\n * Detail of a mount whose activation failed, including the underlying error and\n * the exact declaration to look at.\n *\n * Multi-line on purpose: the row's detail is the only place an operator sees\n * why a server is not there, and a run-on sentence that starts with the error\n * and ends with the file path reads as prose instead of the three facts it is.\n */\nfunction failureDetail(mount: MountedInstance, error: unknown): CodedText {\n const params = {\n name: mount.name,\n error: errorText(error),\n endpoint: mount.endpoint,\n // The `{source}` fallback stays English under zh/ru: params are flat strings,\n // so a translatable fragment would need the wire extension Ruling 4 names.\n // Accepted partial — F-48 ledger Ruling 5 (same class as parse.ref.failedInKey).\n source: mount.source ?? 'the project document',\n }\n return {\n code: 'mount.failedDetail',\n text: [\n `${params.name}: mount failed — ${params.error}`,\n `endpoint: ${params.endpoint}`,\n `declared in: ${params.source}`,\n ].join('\\n'),\n params,\n }\n}\n\n/**\n * Detail of a mount that has produced no tool inside `connectTimeoutMs`. The\n * server is left running: a slow start (an `npx` cold fetch, a container pull)\n * is not an error, only a condition the operator needs to see.\n *\n * Facts only — the name and the wait, the endpoint, the declaring document. The\n * row already carries the status, the transport chip and a `Retry` button, and\n * a stdio server's own reason is on its stderr, in the DSH log; anything more\n * here is text an operator has to read past to find the three lines that matter.\n */\nfunction stallDetail(mount: MountedInstance, elapsedMs: number): CodedText {\n const params = {\n name: mount.name,\n elapsed: formatDuration(elapsedMs),\n endpoint: mount.endpoint,\n // See failureDetail: the `{source}` fallback is an accepted English fragment\n // under zh/ru (F-48 ledger Ruling 5).\n source: mount.source ?? 'the project document',\n }\n return {\n code: 'mount.stalledDetail',\n text: [\n `${params.name}: no tool appeared in ${params.elapsed}`,\n `endpoint: ${params.endpoint}`,\n `declared in: ${params.source}`,\n ].join('\\n'),\n params,\n }\n}\n\n/** Row + live mount state; the mount is authoritative for `status` and `detail`. */\nfunction decorate(row: ServerRow, mount: MountedInstance | undefined): ServerRow {\n if (mount === undefined) return row\n // Drop any detail a previous pass wrote, so a mount that recovered stops\n // reporting a stale stall — companions included, or a recycled row would\n // keep a code under prose it does not belong to.\n const { detail: _stale, detailCode: _staleCode, detailParams: _staleParams, ...rest } = row\n return {\n ...rest,\n status: mount.status,\n ...(mount.detail === undefined ? {} : { detail: mount.detail }),\n ...(mount.detailCode === undefined ? {} : { detailCode: mount.detailCode }),\n ...(mount.detailParams === undefined ? {} : { detailParams: mount.detailParams }),\n ...(mount.transport === undefined ? {} : { transport: mount.transport }),\n }\n}\n\n/**\n * Which of two rows describing the same server a project-level merge keeps. The\n * most actionable state wins, so a session that mounted the server — or failed\n * to — is never hidden behind a session that has not started a turn yet.\n */\nconst STATUS_PRIORITY: Record<ServerStatus, number> = {\n error: 5,\n active: 4,\n connecting: 3,\n conflict: 2,\n idle: 1,\n disabled: 0,\n}\n\n/**\n * Merge one session's rows into a project's merged list. The first session to\n * declare a server fixes its position (document order); the status with the\n * highest {@link STATUS_PRIORITY} seen so far supplies the row itself.\n */\nfunction mergeRows(target: ServerRow[], rows: readonly ServerRow[]): void {\n for (const row of rows) {\n const index = target.findIndex((existing) => existing.name === row.name)\n if (index === -1) {\n target.push(row)\n continue\n }\n const current = target[index]\n if (current !== undefined && STATUS_PRIORITY[row.status] > STATUS_PRIORITY[current.status]) {\n target[index] = row\n }\n }\n}\n\n/**\n * Identity of one reconciliation input set: the declarations, the profile\n * reservations, and the published state of the project's shared mounts. Equal\n * digests mean this session has nothing to reconcile.\n *\n * The shared mounts belong in it because a project's servers are one instance\n * for all of its sessions: another session's pass can mount, settle, stall or\n * drop one of them without touching any document, and this session's rows are a\n * rendering of exactly that instance.\n * @param entries - parsed declarations of the session's project.\n * @param reserved - `serverName`s a profile-level instance already owns.\n * @param mounts - the session's current shared mounts, live.\n * @param chosen - shadowed names this pass mounts, and under which name: a local\n * alias, or `undefined` for the contested name itself.\n * @returns a stable identity string.\n */\nfunction digestOf(\n entries: ParsedEntry[],\n reserved: ReadonlySet<string>,\n mounts: ReadonlyMap<string, MountedInstance>,\n chosen: ReadonlyMap<string, string | undefined>,\n): string {\n const parts = entries.map(\n (entry) =>\n `${entry.name}\\u0000${entry.enabled ? '1' : '0'}\\u0000${entry.error ?? ''}\\u0000${\n entry.config === undefined ? '' : fingerprint(entry.config)\n }`,\n )\n parts.push(`reserved:${[...reserved].sort().join(',')}`)\n // The local names this pass chose. They belong in the identity because a\n // choice the user just made moves a declaration between \"conflict report\" and\n // \"mount\", with no document and no mount touched yet — without them, the pass\n // that follows the click would find its inputs unchanged and do nothing.\n for (const [name, mountedAs] of [...chosen].sort(([left], [right]) => (left < right ? -1 : 1))) {\n // `native` is its own part rather than a `local` with an empty name: a choice\n // that mounts under the declared name has to move this identity exactly as a\n // choice that mounts under a local one does, or the pass after the click finds\n // its inputs unchanged and mounts nothing.\n parts.push(mountedAs === undefined ? `native:${name}` : `local:${name}\\u0000${mountedAs}`)\n }\n for (const [name, mount] of mounts) {\n parts.push(\n `mount:${name}\\u0000${mount.status}\\u0000${mount.detail ?? ''}\\u0000${mount.stalled ? '1' : '0'}\\u0000${mount.runtimeName}`,\n )\n }\n return parts.join('\\u0001')\n}\n\nfunction fingerprint(config: unknown): string {\n return JSON.stringify(config)\n}\n\n/**\n * The name one declaration registers under this pass: its local alias, or the\n * name it declared.\n *\n * @param entry - parsed declaration.\n * @param alias - local name the pass chose, when it chose one.\n * @returns the `serverName` to hand `@deepseek-ai/dsh-mcp-client`.\n */\nfunction runtimeNameOf(entry: ParsedEntry, alias: string | undefined): string {\n return alias ?? entry.name\n}\n\n/**\n * One declaration's config as it is mounted: the same body, under the name this\n * registration actually takes.\n *\n * A fresh object on purpose — the parsed entry is shared with every other\n * session and with the editor, and rewriting its `serverName` in place would\n * make the alias look like the declared name everywhere else.\n *\n * @param config - the parsed mcp-client config.\n * @param runtimeName - the `serverName` to reserve.\n * @returns the config to mount.\n */\nfunction runtimeConfigOf(\n config: NonNullable<ParsedEntry['config']>,\n runtimeName: string,\n): NonNullable<ParsedEntry['config']> {\n if (config.serverName === runtimeName) return config\n return { ...config, serverName: runtimeName }\n}\n\n/**\n * The one line a shadowed declaration carries.\n *\n * Two readings, and the row has to say which one it is: the profile's copy is the\n * one shown and this project's entry is a conflict, or the entry has a local name\n * to be mounted under and the choice is the question. A mounted row carries no\n * detail at all ({@link decorate}), so a chosen answer is explained by the\n * conflict report, which a mounted name still publishes.\n *\n * @param name - the contested `serverName`.\n * @param alias - the local name this project could give it, when it has one.\n * @returns the row's detail line, with its wire code and params (F-48).\n */\nfunction conflictDetail(name: string, alias: string | undefined): CodedText {\n const base = `serverName \"${name}\" is already provided by a profile-level mcp-client instance`\n return alias === undefined\n ? {\n text: `${base} — remove that entry from the profile to use the project one everywhere, or choose this project's copy to let it take the name in this project's sessions`,\n code: 'conflict.profileDetail',\n params: { name },\n }\n : {\n text: `${base} — choose this project's copy to mount it as \"${alias}\", or under the contested name to shadow the profile instance here`,\n code: 'conflict.profileAliasDetail',\n params: { name, alias },\n }\n}\n\nasync function activation(fiber: MountFiber): Promise<void> {\n if (typeof fiber.await === 'function') {\n await fiber.await()\n return\n }\n await Promise.resolve(fiber as unknown)\n}\n\nfunction errorText(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\n/**\n * The fields one tool definition accepts, read from its top-level\n * `parameters.properties` in schema order.\n *\n * A declared object or array is drawn as its own `type` and never expanded:\n * the record answers \"what does this tool take\", and a nested graph is what the\n * model-facing schema already carries. A property published without a `type` —\n * the JSON Schema case of `oneOf` or `$ref` — reads as `any`, the same word the\n * row vocabulary uses for \"the schema names none\". A property's `default` is\n * deliberately not part of the record: it is the host's own default for a call,\n * never a value the tool publishes.\n *\n * @param parameters - the definition's JSON Schema object arguments.\n * @returns one field per declared property; empty when the schema declares none.\n */\nfunction toolFieldsOf(parameters: Record<string, unknown>): ToolField[] {\n const properties = parameters.properties\n if (!isRecord(properties)) return []\n const required = new Set(stringArray(parameters.required))\n return Object.entries(properties).map(([name, declared]) => {\n const field = isRecord(declared) ? declared : {}\n const type = field.type\n const description = field.description\n return {\n name,\n type: typeof type === 'string' && type !== '' ? type : 'any',\n required: required.has(name),\n ...(typeof description === 'string' && description !== '' ? { description } : {}),\n }\n })\n}\n\n/** The strings of one array value; empty for anything that is not one. */\nfunction stringArray(value: unknown): string[] {\n return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : []\n}\n\n/**\n * One path the watcher stack covers and what kind it is.\n *\n * The kind comes from the config, not from the name: a document is watched as a\n * file — watching its whole directory would put the watcher on unrelated writes\n * — while a directory that holds a project document is watched (recursively when\n * the platform allows) so a document appearing there is seen.\n */\ninterface WatchTarget {\n /** Absolute path. */\n readonly path: string\n /** `true` for a directory, `false` for a document file. */\n readonly directory: boolean\n}\n\n/** Same targets, in the same order — what decides a watcher rebuild. */\nfunction sameTargets(left: readonly WatchTarget[], right: readonly WatchTarget[]): boolean {\n return (\n left.length === right.length &&\n left.every((value, index) => value.path === right[index]?.path && value.directory === right[index]?.directory)\n )\n}\n","/**\n * Contract shared by the host half and the browser half of the panel.\n *\n * Import-free on purpose: the client bundle must not pull host code in, and the\n * right sidebar exists only in the browser half, so the two halves meet at these\n * routes over HTTP.\n *\n * @module dsh-project-mcp/shared\n */\n\nimport type { ConflictChoice, EntrySnapshot, ToolMode } from './types.ts'\n\n/** Route prefix the host serves and the sidebar panel fetches. */\nexport const ROUTE_PREFIX = '/project-mcp'\n\n/** Sidebar tab id; also the `SidebarTab.type` the panel opens as. */\nexport const TAB_ID = 'dsh-project-mcp:servers'\n\n/** Plugin name, shared by both halves. */\nexport const PACKAGE_NAME = 'dsh-project-mcp'\n\n/** Actions the host serves under {@link ROUTE_PREFIX}, and the panel fetches. */\nexport const ROUTE_ACTIONS = {\n /** `GET`: the current snapshot. */\n snapshot: 'snapshot',\n /** `POST`: ask for a rescan; answers as soon as the request is accepted. */\n sync: 'sync',\n /** `POST`: drop this project's failed mounts and re-mount them; answers once they are dropped. */\n retry: 'retry',\n /** `GET`: the status channel — one pushed frame per change, held open. */\n events: 'events',\n /** `GET`: one page of a project's log ring, oldest first, for \"show older\". */\n logs: 'logs',\n /**\n * `GET`: one tool's detail — its description, its accepted fields, its\n * measured size and the reason it is not offered — read once per opened row\n * so that neither the snapshot nor a change frame carries it.\n */\n tool: 'tool',\n /** `POST`: release this session's mounts. */\n release: 'release',\n /** `POST`: write one edited entry back to its declaring document. */\n save: 'save',\n /** `POST`: pin or unpin one tool of one project. */\n pin: 'pin',\n /** `POST`: set one project's tool mode. */\n policy: 'policy',\n /** `POST`: choose which declaration of a contested `serverName` shows. */\n conflict: 'conflict',\n} as const\n\n/**\n * One operator request: the body of `POST sync` and `POST retry`.\n *\n * `projectRoot` scopes the action, so a surface that shows one project never\n * starts or restarts a server for another. `full` is the answer shape: a\n * single-project surface leaves it out and gets that project's slice back, while\n * a surface that lists every project — the settings page — asks for the whole\n * snapshot, since narrowing would empty the list it renders.\n */\nexport interface OperatorRequest {\n /** Project the action applies to; omitted covers every project. */\n readonly projectRoot?: string\n /** Answer with the whole snapshot rather than `projectRoot`'s slice. */\n readonly full?: boolean\n}\n\n/** Pin or unpin one tool of one project. */\nexport interface PinRequest {\n /** Project root the tool belongs to. */\n readonly projectRoot: string\n /** Public registry name, eg `mcp__tglider__workspace`. */\n readonly tool: string\n /** `true` pins it, `false` unpins it. */\n readonly pinned: boolean\n}\n\n/** Set one project's tool mode. Pins travel in their own request. */\nexport interface PolicyRequest {\n /** Project root the mode applies to. */\n readonly projectRoot: string\n /** The mode to store. */\n readonly mode: ToolMode\n}\n\n/**\n * Choose which declaration of one contested `serverName` a project shows.\n *\n * The name stays the profile's either way; the answer decides whether the\n * project's own entry mounts beside it under a local namespace. The name is\n * carried as declared — the sanitized `mcpServers` key — because that is what\n * the conflict report names, and the local name is the plugin's to compute.\n */\nexport interface ConflictRequest {\n /** Project root the name belongs to. */\n readonly projectRoot: string\n /** Contested `serverName`, as the project declared it. */\n readonly server: string\n /** The declaration to show. */\n readonly choice: ConflictChoice\n}\n\n/**\n * One entry a save writes.\n *\n * The panel submits the {@link EntrySnapshot} it was given, with the fields the\n * user changed. A masked `env`/`headers` key submitted without a `value` keeps\n * whatever the document declares for it; a key the submission omits is removed.\n */\nexport interface SaveRequest {\n /** Project root the edited row belongs to. */\n readonly projectRoot: string\n /** `serverName` being edited. */\n readonly server: string\n /** Absolute path of the document the entry came from. */\n readonly document: string\n /** `documentRevision` the edit was built from; a mismatch refuses the write. */\n readonly revision: string\n /** `true` acknowledges a write to the global tier; required only there. */\n readonly consent?: boolean\n /** The entry body to write. */\n readonly entry: EntrySnapshot\n}\n\n/** Error codes a save answers with, each with its own sentence in the panel. */\nexport type SaveErrorCode =\n /** The entry is not one this plugin would mount; nothing was written. */\n | 'invalid'\n /** The document may not be written: profile, `<DSH_HOME>`, or no consent. */\n | 'blocked'\n /** The document changed since the snapshot was taken; nothing was written. */\n | 'conflict'\n /** The document or the server is no longer there. */\n | 'not-found'\n /** The write itself failed; the document is left as it was. */\n | 'failed'","/**\n * Host HTTP surface for the sidebar panel.\n *\n * The browser half of a DSH composition is a different process from this one, so\n * the panel cannot call the `projectMcp` service in process: it fetches these\n * routes, which is how every browser-facing service in DSH reaches its host.\n * Every response is `{ ok: true, value }` or `{ ok: false, error }`.\n *\n * @module dsh-project-mcp/ui\n */\n\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport type { ProjectMcpService } from './index.ts'\nimport { page } from './logs.ts'\nimport { isConflictChoice, isToolMode } from './policy.ts'\nimport type { PolicyOutcome } from './runtime.ts'\nimport type {\n ConflictRequest,\n OperatorRequest,\n PinRequest,\n PolicyRequest,\n SaveErrorCode,\n SaveRequest,\n} from './shared.ts'\nimport { ROUTE_PREFIX } from './shared.ts'\nimport type { EntrySnapshot, McpSnapshot, SnapshotChange } from './types.ts'\n\n/** The subset of the DSH web server this plugin registers on. */\nexport interface WebServerLike {\n /** Register one route and return its disposer, in whatever shape the server uses. */\n register(route: { kind: 'prefix'; path: string; handler: RouteHandler }): unknown\n}\n\n/** Node HTTP handler signature the web server expects. */\nexport type RouteHandler = (req: IncomingMessage, res: ServerResponse) => Promise<void>\n\n/** Largest request body accepted for a session id. */\nconst MAX_BODY_BYTES = 4_096\n\n/** Largest request body accepted for a save: one entry body plus its extras. */\nconst MAX_SAVE_BYTES = 64 * 1024\n\n/**\n * How often a quiet stream is poked.\n *\n * The channel can be silent for minutes — nothing happens in a project, so\n * nothing is announced — and an idle connection is what proxies and browsers\n * reap. A comment frame is not an event: the panel does not see it, the socket\n * stays warm. `unref`'d, so a headless host is never kept alive for it.\n */\nconst HEARTBEAT_MS = 15_000\n\n/**\n * The status channel: one open `GET events` response per panel, and a frame\n * whenever the picture changes.\n *\n * Server-Sent Events rather than polling: DSH's own web server hands a route the\n * raw response (\"owns the full response lifecycle, may hold the response open,\n * e.g. SSE\") and exempts `text/event-stream` from its gzip filter, and the\n * browser's `EventSource` reconnects on its own. The subscription is only held\n * while somebody is listening, and the heartbeat only runs with a stream open.\n */\nexport interface EventStream {\n /** Serve one `GET events`: the response stays open until the client leaves. */\n serve(req: IncomingMessage, res: ServerResponse): void\n /** Close every open stream and stop listening; the route's disposer calls it. */\n dispose(): void\n}\n\n/**\n * Build the status channel of one route registration.\n * @param service - the runtime's published service.\n * @returns the channel's `serve`/`dispose` pair.\n */\nexport function createEventStream(service: ProjectMcpService): EventStream {\n const streams = new Set<ServerResponse>()\n let heartbeat: ReturnType<typeof setInterval> | undefined\n let unsubscribe: (() => void) | undefined\n let latest: SnapshotChange | undefined\n\n /**\n * Write one frame, dropping a stream that has already gone: a dead socket\n * raises on `write`, and an exception here would reach the pass that\n * announced the change rather than the panel it was meant for.\n */\n const write = (res: ServerResponse, frame: string): void => {\n try {\n res.write(frame)\n } catch {\n streams.delete(res)\n }\n }\n\n const frame = (event: 'hello' | 'change', change: SnapshotChange): string =>\n `event: ${event}\\ndata: ${JSON.stringify(change)}\\n\\n`\n\n const stop = (): void => {\n if (heartbeat !== undefined) clearInterval(heartbeat)\n heartbeat = undefined\n unsubscribe?.()\n unsubscribe = undefined\n }\n\n /**\n * Start listening, if this is the first stream. The subscription answers with\n * the picture as it is now, which is also what a stream opened later replays:\n * every frame carries the whole snapshot, so the newest one is always current.\n */\n const start = (): void => {\n if (unsubscribe !== undefined) return\n unsubscribe = service.subscribe((change) => {\n latest = change\n for (const stream of [...streams]) write(stream, frame('change', change))\n })\n heartbeat = setInterval(() => {\n for (const stream of [...streams]) write(stream, ': ping\\n\\n')\n }, HEARTBEAT_MS)\n heartbeat.unref?.()\n }\n\n return {\n serve(req, res): void {\n res.writeHead(200, {\n 'content-type': 'text/event-stream; charset=utf-8',\n 'cache-control': 'no-cache, no-transform',\n connection: 'keep-alive',\n })\n // A comment first — DSH's own HMR stream does the same — so the browser\n // sees a live channel before anything happens, plus how fast to come back.\n res.write(': connected\\nretry: 2000\\n\\n')\n // Subscribe before joining the fan-out: the subscription answers with the\n // picture as it is, which is this stream's `hello` — a `change` frame for a\n // change that predates the panel would say the same thing twice.\n start()\n streams.add(res)\n if (latest !== undefined) write(res, frame('hello', latest))\n const leave = (): void => {\n streams.delete(res)\n if (streams.size === 0) stop()\n }\n req.on('close', leave)\n res.on('error', leave)\n },\n dispose(): void {\n stop()\n for (const stream of [...streams]) {\n streams.delete(stream)\n try {\n stream.end()\n } catch {\n // The socket is already gone; nothing to end.\n }\n }\n },\n }\n}\n\n/**\n * HTTP status each coded refusal answers with. The policy routes reuse the same\n * vocabulary as a save: `invalid`/`not-found` are the panel's 400s, `failed` a\n * 500.\n */\nconst SAVE_STATUS: Record<SaveErrorCode, number> = {\n invalid: 400,\n blocked: 400,\n 'not-found': 400,\n conflict: 409,\n failed: 500,\n}\n\n/**\n * HTTP status a `GET tool` refusal answers with: the same vocabulary, one\n * different reading.\n *\n * A save or a policy change names something the panel is looking at *and\n * edits*, so a name this host does not know is a malformed request there —\n * `400`. A tool read is a *fetch* of a row the panel already drew, so an\n * unknown project, session or name means the picture moved under it, which is\n * exactly what `404` says: `GET logs` answers the same question the same way.\n */\nconst TOOL_STATUS: Record<SaveErrorCode, number> = {\n ...SAVE_STATUS,\n 'not-found': 404,\n}\n\n/**\n * Read one numeric query parameter.\n *\n * The panel decides the window, so the host refuses rather than guesses: a\n * parameter the URL does not carry is absent, and one it carries as anything but\n * a finite number — `abc`, an empty value — is `'invalid'`, which the route\n * answers with `bad-request`.\n * @param raw - the raw value, `null` when the query string omits it.\n * @returns the number, `undefined` when absent, `'invalid'` when unusable.\n */\nfunction numberParam(raw: string | null): number | undefined | 'invalid' {\n if (raw === null) return undefined\n const value = Number(raw)\n return raw.trim() === '' || !Number.isFinite(value) ? 'invalid' : value\n}\n\n/**\n * Build the route handler for {@link ROUTE_PREFIX}.\n *\n * Both operator actions — `Sync` and `Retry` — answer as soon as they are\n * accepted, never once the servers they touch have settled: the pass they queue\n * runs in the background, and the panel reads the outcome from the status\n * channel. A response held open for a mount that is still connecting is exactly\n * the hang this route no longer produces.\n *\n * @param service - the runtime's published service.\n * @param events - the status channel to serve; built from the service when omitted.\n * @returns a handler for `GET snapshot|events|logs`, `POST sync|retry|release|save`.\n */\nexport function createRouteHandler(\n service: ProjectMcpService,\n events: EventStream = createEventStream(service),\n): RouteHandler {\n const send = (res: ServerResponse, status: number, body: unknown): void => {\n res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' })\n res.end(JSON.stringify(body))\n }\n const reply = async (\n res: ServerResponse,\n action: () => Promise<void>,\n request: OperatorRequest = {},\n ): Promise<void> => {\n try {\n await action()\n send(res, 200, { ok: true, value: operatorAnswer(service, request) })\n } catch (error) {\n send(res, 500, {\n ok: false,\n error: { code: 'failed', message: error instanceof Error ? error.message : String(error) },\n })\n }\n }\n\n /**\n * Answer a pin or mode change with the same envelope a save uses: the fresh\n * snapshot, or the refusal code's status. The service method is synchronous —\n * the policy is not part of any document, so no rescan follows — but a store\n * that still fails answers `500` rather than breaking the route.\n */\n const replyPolicy = (res: ServerResponse, change: () => PolicyOutcome): void => {\n try {\n const outcome = change()\n if (outcome.ok) {\n send(res, 200, { ok: true, value: outcome.snapshot })\n return\n }\n send(res, SAVE_STATUS[outcome.code], {\n ok: false,\n error: {\n code: outcome.code,\n message: outcome.message,\n // The F-48 companions ride the envelope only when the outcome has\n // them: an uncoded refusal's body is byte-identical to before.\n ...(outcome.messageCode === undefined\n ? {}\n : { messageCode: outcome.messageCode, messageParams: outcome.messageParams }),\n },\n })\n } catch (error) {\n send(res, 500, {\n ok: false,\n error: { code: 'failed', message: error instanceof Error ? error.message : String(error) },\n })\n }\n }\n return async (req, res) => {\n const url = new URL(req.url ?? '/', 'http://localhost')\n const action = url.pathname.slice(ROUTE_PREFIX.length).replace(/^\\/+|\\/+$/g, '')\n const method = req.method ?? 'GET'\n if (method === 'GET' && action === 'snapshot') {\n send(res, 200, { ok: true, value: service.snapshot() })\n return\n }\n if (method === 'POST' && action === 'sync') {\n const request = operatorRequestOf(await readJson(req))\n // The pass is background work from here on, so the answer is the picture\n // as it is now — the status channel carries the rest.\n service.syncSoon(request.projectRoot)\n send(res, 200, { ok: true, value: operatorAnswer(service, request) })\n return\n }\n if (method === 'GET' && action === 'events') {\n events.serve(req, res)\n return\n }\n // The tab is drawn from the snapshot, which carries the newest page of the\n // ring; this route is \"show older\". It reads the ring directly — the buffer\n // has one owner (`src/logs.ts`) and no runtime state to ask for — and it\n // answers even when the named project is unknown to the runtime: the ring\n // is keyed by the root, and an empty page is an answer, not a refusal.\n if (method === 'GET' && action === 'logs') {\n const projectRoot = url.searchParams.get('projectRoot')\n const before = numberParam(url.searchParams.get('before'))\n const limit = numberParam(url.searchParams.get('limit'))\n if (projectRoot === null || projectRoot === '' || before === 'invalid' || limit === 'invalid') {\n send(res, 400, {\n ok: false,\n error: {\n code: 'bad-request',\n message: 'GET logs needs a projectRoot, and before/limit as finite numbers',\n },\n })\n return\n }\n send(res, 200, {\n ok: true,\n value: page({\n projectRoot,\n ...(before === undefined ? {} : { before }),\n ...(limit === undefined ? {} : { limit }),\n }),\n })\n return\n }\n // One tool's detail, for a row the panel opened. On demand rather than in\n // the snapshot — descriptions and schemas are the expensive part, and every\n // change frame and poll carries the whole snapshot — so nothing grows on the\n // wire and the answer is fetched once per opened row. The same precedent as\n // `logs`: the route checks that it was given three names at all and refuses\n // a request missing one, while \"this host does not know that project,\n // session or tool\" is the service's `404` rather than the route's `400`.\n if (method === 'GET' && action === 'tool') {\n const projectRoot = url.searchParams.get('projectRoot')\n const sessionId = url.searchParams.get('sessionId')\n const name = url.searchParams.get('name')\n if (projectRoot === null || projectRoot === '') {\n send(res, 400, {\n ok: false,\n error: { code: 'bad-request', message: 'GET tool needs a projectRoot' },\n })\n return\n }\n if (sessionId === null || sessionId === '') {\n send(res, 400, {\n ok: false,\n error: { code: 'bad-request', message: 'GET tool needs a sessionId' },\n })\n return\n }\n if (name === null || name === '') {\n send(res, 400, {\n ok: false,\n error: { code: 'bad-request', message: 'GET tool needs a name' },\n })\n return\n }\n const outcome = service.toolFacts(projectRoot, sessionId, name)\n if (!outcome.ok) {\n send(res, TOOL_STATUS[outcome.code], {\n ok: false,\n error: { code: outcome.code, message: outcome.message },\n })\n return\n }\n send(res, 200, { ok: true, value: outcome.value })\n return\n }\n if (method === 'POST' && action === 'retry') {\n const request = operatorRequestOf(await readJson(req))\n await reply(res, () => service.retry(request.projectRoot), request)\n return\n }\n if (method === 'POST' && action === 'release') {\n const body = await readJson(req)\n const sessionId = typeof body.sessionId === 'string' ? body.sessionId : undefined\n await reply(res, () => service.release(sessionId))\n return\n }\n if (method === 'POST' && action === 'save') {\n const request = saveRequestOf(await readJson(req, MAX_SAVE_BYTES))\n if (request === undefined) {\n send(res, 400, {\n ok: false,\n error: { code: 'invalid', message: 'the save body is not a well-formed entry request' },\n })\n return\n }\n try {\n const outcome = await service.save(request)\n if (outcome.ok) {\n send(res, 200, { ok: true, value: outcome.snapshot })\n return\n }\n send(res, SAVE_STATUS[outcome.code], {\n ok: false,\n error: {\n code: outcome.code,\n message: outcome.message,\n // The F-48 companions ride the envelope only when the outcome has\n // them: an uncoded refusal's body is byte-identical to before.\n ...(outcome.messageCode === undefined\n ? {}\n : { messageCode: outcome.messageCode, messageParams: outcome.messageParams }),\n },\n })\n } catch (error) {\n send(res, 500, {\n ok: false,\n error: { code: 'failed', message: error instanceof Error ? error.message : String(error) },\n })\n }\n return\n }\n // A pin and a mode are durable plugin state, not document edits: neither\n // route rescans, and both answer with the snapshot rebuilt on the spot.\n if (method === 'POST' && action === 'pin') {\n const request = pinRequestOf(await readJson(req))\n if (request === undefined) {\n send(res, 400, {\n ok: false,\n error: { code: 'invalid', message: 'the pin body is not a well-formed pin request' },\n })\n return\n }\n replyPolicy(res, () => service.setPin(request))\n return\n }\n if (method === 'POST' && action === 'policy') {\n const request = policyRequestOf(await readJson(req))\n if (request === undefined) {\n send(res, 400, {\n ok: false,\n error: { code: 'invalid', message: 'the policy body is not a well-formed mode request' },\n })\n return\n }\n replyPolicy(res, () => service.setPolicy(request))\n return\n }\n if (method === 'POST' && action === 'conflict') {\n const request = conflictRequestOf(await readJson(req))\n if (request === undefined) {\n send(res, 400, {\n ok: false,\n error: {\n code: 'invalid',\n message: 'the conflict body is not a well-formed conflict request',\n },\n })\n return\n }\n replyPolicy(res, () => service.setConflictChoice(request))\n return\n }\n send(res, 404, {\n ok: false,\n error: { code: 'not-found', message: `unknown route ${method} ${url.pathname}` },\n })\n }\n}\n\n/**\n * The operator request a `sync` or `retry` body carries. A body that is not an\n * operator request at all — a surface that predates the field, a `{}`, a\n * malformed value — reads as the global call it used to be.\n * @param body - the parsed request body.\n * @returns the project the action applies to, and the answer shape asked for.\n */\nexport function operatorRequestOf(body: Record<string, unknown>): OperatorRequest {\n const projectRoot = body.projectRoot\n return {\n ...(typeof projectRoot === 'string' && projectRoot !== '' ? { projectRoot } : {}),\n ...(body.full === true ? { full: true } : {}),\n }\n}\n\n/**\n * The snapshot an operator route answers with.\n *\n * A single-project surface (the sidebar tab, a row's own `Retry`) gets that\n * project's slice: it shows one project, and answering with every project made a click in one of them look like it had touched all of them. A\n * surface that lists every project asks for `full`, because a narrowed answer\n * would empty the list it renders.\n * @param service - the runtime's published service.\n * @param request - the operator request the caller sent.\n * @returns the snapshot, narrowed when the caller asked for one project.\n */\nexport function operatorAnswer(service: ProjectMcpService, request: OperatorRequest): McpSnapshot {\n const snapshot = service.snapshot()\n if (request.full === true || request.projectRoot === undefined) return snapshot\n return projectSlice(snapshot, request.projectRoot)\n}\n\n/**\n * One project's slice of a snapshot: its own project record and the root the\n * panel prints as watched, with the other projects dropped.\n * @param snapshot - the whole snapshot.\n * @param projectRoot - the project to keep.\n * @returns the narrowed snapshot.\n */\nexport function projectSlice(snapshot: McpSnapshot, projectRoot: string): McpSnapshot {\n return {\n ...snapshot,\n projects: snapshot.projects.filter((project) => project.projectRoot === projectRoot),\n watchedFiles: snapshot.watchedFiles.filter((file) => file === projectRoot),\n }\n}\n\n/**\n * Register the panel routes on the DSH web server.\n * @param webServer - the injected web server service.\n * @param service - the runtime's published service.\n * @returns the disposer: it closes the open status streams, then the routes.\n */\nexport function registerRoutes(webServer: WebServerLike, service: ProjectMcpService): () => void {\n const events = createEventStream(service)\n const registration = webServer.register({\n kind: 'prefix',\n path: ROUTE_PREFIX,\n handler: createRouteHandler(service, events),\n })\n return () => {\n events.dispose()\n disposeRegistration(registration)\n }\n}\n\n/**\n * Run one registration's disposer, whichever shape the web server hands back:\n * Cordis only ever calls a disposer *function* for an effect, and the server may\n * return a `{ dispose() }` object instead.\n * @param registration - the value `registerRoutes` returned.\n */\nexport function disposeRegistration(registration: unknown): void {\n if (typeof registration === 'function') {\n ;(registration as () => void)()\n return\n }\n if (typeof registration !== 'object' || registration === null) return\n const dispose = (registration as { dispose?: unknown }).dispose\n if (typeof dispose === 'function') (dispose as () => void).call(registration)\n}\n\n/**\n * Read a bounded JSON body; anything unparseable, oversized or non-object stays\n * an empty object.\n * @param req - the incoming request.\n * @param limit - largest body accepted, in bytes.\n * @returns the parsed object body, or `{}` when there is none.\n */\nasync function readJson(req: IncomingMessage, limit: number = MAX_BODY_BYTES): Promise<Record<string, unknown>> {\n const chunks: Buffer[] = []\n let size = 0\n for await (const chunk of req) {\n const buffer = chunk as Buffer\n size += buffer.length\n if (size > limit) return {}\n chunks.push(buffer)\n }\n try {\n const parsed: unknown = JSON.parse(Buffer.concat(chunks).toString('utf8'))\n return typeof parsed === 'object' && parsed !== null ? (parsed as Record<string, unknown>) : {}\n } catch {\n return {}\n }\n}\n\n/**\n * Shape one `POST save` body into a {@link SaveRequest}.\n *\n * Only the envelope is checked here: whether the entry itself parses, and\n * whether the document may be written, is the runtime's decision and comes back\n * as a coded refusal.\n * @param body - parsed request body.\n * @returns the request, or `undefined` when a required field is missing.\n */\nfunction saveRequestOf(body: Record<string, unknown>): SaveRequest | undefined {\n const { projectRoot, server, document, revision, entry } = body\n if (typeof projectRoot !== 'string' || projectRoot === '') return undefined\n if (typeof server !== 'string' || server === '') return undefined\n if (typeof document !== 'string' || document === '') return undefined\n if (typeof revision !== 'string' || revision === '') return undefined\n if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) return undefined\n return {\n projectRoot,\n server,\n document,\n revision,\n ...(body.consent === true ? { consent: true } : {}),\n entry: entry as EntrySnapshot,\n }\n}\n\n/**\n * Shape one `POST pin` body into a {@link PinRequest}.\n *\n * Only the envelope is checked here: whether the project has a live session is\n * the runtime's decision and comes back as a coded refusal.\n * @param body - parsed request body.\n * @returns the request, or `undefined` when a required field is missing.\n */\nfunction pinRequestOf(body: Record<string, unknown>): PinRequest | undefined {\n const { projectRoot, tool, pinned } = body\n if (typeof projectRoot !== 'string' || projectRoot === '') return undefined\n if (typeof tool !== 'string' || tool === '') return undefined\n if (typeof pinned !== 'boolean') return undefined\n return { projectRoot, tool, pinned }\n}\n\n/**\n * Shape one `POST policy` body into a {@link PolicyRequest}.\n *\n * The mode is validated here as well as in the runtime, so a switch carrying a\n * mode this build does not know is a `400` and never reaches the store.\n * @param body - parsed request body.\n * @returns the request, or `undefined` when a required field is missing.\n */\nfunction policyRequestOf(body: Record<string, unknown>): PolicyRequest | undefined {\n const { projectRoot, mode } = body\n if (typeof projectRoot !== 'string' || projectRoot === '') return undefined\n if (!isToolMode(mode)) return undefined\n return { projectRoot, mode }\n}\n\n/**\n * Shape one `POST conflict` body into a {@link ConflictRequest}.\n *\n * The answer is checked here as well as in the runtime, so a request carrying a\n * choice this build does not know is a `400` and never reaches the store. The\n * name itself is not checked against anything: a project that does not conflict\n * over it yet may still be given an answer, which is what makes the choice\n * survive a declaration that comes and goes.\n * @param body - parsed request body.\n * @returns the request, or `undefined` when a required field is missing.\n */\nfunction conflictRequestOf(body: Record<string, unknown>): ConflictRequest | undefined {\n const { projectRoot, server, choice } = body\n if (typeof projectRoot !== 'string' || projectRoot === '') return undefined\n if (typeof server !== 'string' || server === '') return undefined\n if (!isConflictChoice(choice)) return undefined\n return { projectRoot, server, choice }\n}\n","/**\n * `dsh-project-mcp` — per-project MCP servers for DeepSeek Harness.\n *\n * The host half reads a project's own MCP documents and mounts the declared\n * servers on the Cordis context of every session (`agent`) whose working\n * directory resolves to that project. Servers therefore exist exactly where\n * they are declared, and two projects may declare the same `serverName`\n * without colliding with each other or with profile-level entries.\n *\n * Sources, in increasing priority (later documents override by `serverName`):\n * 1. the global documents this deployment lists in `globalFiles` — none by default\n * 2. the project-relative documents it lists in `localFiles` —\n * `<project>/.dsh/mcp.json` out of the box\n *\n * @module dsh-project-mcp\n */\n\nimport type { Context } from '@deepseek-ai/cordis'\nimport z from '@deepseek-ai/schemastery'\nimport {\n DEFAULT_ACTIVATION_ENABLED,\n DEFAULT_ACTIVATION_MIN_CALLS,\n DEFAULT_ACTIVATION_SEEDED,\n DEFAULT_AUTO_ACTIVATION_LIMIT,\n DEFAULT_AUTO_ACTIVATION_STICKY_STEPS,\n DEFAULT_TOOL_BUDGET_CHARS,\n DEFAULT_TOOL_IDLE_MS,\n} from './activation.ts'\nimport {\n DEFAULT_FILE_MARKERS,\n DEFAULT_GLOBAL_FILES,\n DEFAULT_LOCAL_FILES,\n DEFAULT_PROJECT_MARKERS,\n defaultCredentialsPath,\n} from './discovery.ts'\nimport { DEFAULT_GUIDANCE_ENABLED } from './guidance.ts'\nimport { isValidLocalPrefix } from './naming.ts'\nimport { PolicyStore } from './policy.ts'\nimport { ProjectMcpRuntime } from './runtime.ts'\nimport type {\n AgentLike,\n AgentScopeLike,\n PolicyOutcome,\n RuntimeConfig,\n RuntimeOptions,\n SaveOutcome,\n ToolFactsOutcome,\n} from './runtime.ts'\nimport type { ConflictRequest, PinRequest, PolicyRequest, SaveRequest } from './shared.ts'\nimport { UsageStore, observeToolResults } from './usage.ts'\nimport type { ToolResultEventLike, ToolResultLike } from './usage.ts'\nimport { disposeRegistration, registerRoutes } from './ui.ts'\nimport type { WebServerLike } from './ui.ts'\nimport type { McpSnapshot, SnapshotChange } from './types.ts'\n\nexport { ProjectMcpRuntime, mountTrigger } from './runtime.ts'\nexport type {\n AgentLike,\n AgentMounts,\n AgentScopeLike,\n MountDecision,\n MountTrigger,\n PolicyOutcome,\n PolicySource,\n RuntimeConfig,\n RuntimeOptions,\n SaveOutcome,\n ToolFactsOutcome,\n UsageSource,\n} from './runtime.ts'\nexport {\n POLICY_FILE_NAME,\n POLICY_VERSION,\n PolicyStore,\n TOOL_MODES,\n isToolMode,\n parsePolicyDocument,\n policyFor,\n withMode,\n withPin,\n} from './policy.ts'\nexport type {\n PolicyDocument,\n PolicyLogger,\n PolicyState,\n PolicyStoreOptions,\n} from './policy.ts'\nexport { findProjectRoot, configDirectories, expandConfigPath, globalConfigPaths, localConfigPaths } from './discovery.ts'\nexport { parseDocument, mergeEntries, parseCredentials } from './parse.ts'\nexport {\n DEFAULT_ACTIVATION_ENABLED,\n DEFAULT_ACTIVATION_MIN_CALLS,\n DEFAULT_ACTIVATION_SEEDED,\n DEFAULT_SEARCH_LIMIT,\n DEFAULT_TOOL_IDLE_MS,\n MAX_SEARCH_LIMIT,\n MAX_SEARCH_TOKENS,\n SEARCH_TOOL_NAME,\n activate,\n createActivationState,\n createSearchTool,\n installActivation,\n noteUse,\n onCompaction,\n presentedNames,\n pruneIdle,\n seedFromUsage,\n withActiveTools,\n} from './activation.ts'\nexport type {\n ActivationContextLike,\n ActivationState,\n ActivationWiringOptions,\n AssembleListener,\n AssemblyLike,\n ListenerLike,\n SearchToolOptions,\n SeedOptions,\n SessionEventLike,\n TextBlockLike,\n ToolDefinitionLike,\n ToolSchemaLike,\n} from './activation.ts'\nexport {\n DEFAULT_GUIDANCE_ENABLED,\n GUIDANCE_SECTION_NAME,\n MAX_GUIDANCE_CHARS,\n MAX_GUIDANCE_PURPOSE,\n MAX_GUIDANCE_SERVERS,\n MAX_GUIDANCE_HIDDEN_NAMES,\n buildGuidance,\n installGuidance,\n projectLabel,\n} from './guidance.ts'\nexport type {\n GuidanceContextLike,\n GuidanceInput,\n GuidancePromptLike,\n GuidancePromptScopeLike,\n GuidanceSectionLike,\n GuidanceServer,\n GuidanceWiringOptions,\n} from './guidance.ts'\nexport {\n USAGE_FILE_NAME,\n USAGE_VERSION,\n UsageStore,\n matchServer,\n observeToolResults,\n parseUsageDocument,\n recordUsage,\n usageEventFor,\n} from './usage.ts'\nexport { createRouteHandler, disposeRegistration, registerRoutes } from './ui.ts'\nexport { ROUTE_PREFIX, TAB_ID } from './shared.ts'\nexport type { RouteHandler, WebServerLike } from './ui.ts'\nexport type {\n McpSnapshot,\n ProjectSnapshot,\n ServerRow,\n ServerStatus,\n ServerUsage,\n SessionSnapshot,\n SnapshotChange,\n SnapshotIssue,\n} from './types.ts'\nexport type {\n ToolResultEventLike,\n ToolResultLike,\n ToolResultObserverOptions,\n UsageCall,\n UsageDocument,\n UsageEvent,\n UsageLogger,\n UsageState,\n UsageStoreOptions,\n} from './usage.ts'\n\n/**\n * Plugin config: everything two deployments may want to set differently.\n *\n * Live editing: on DSH ≥ 0.1.7 the keys of {@link VOLATILE_CONFIG_KEYS} arrive\n * not as plain values but as volatile refs (`{ get(): T }`, see\n * {@link VolatileLike}) that the host re-points on every profile edit and\n * re-reads on `loader/volatile-update`. Every read of those keys goes through\n * {@link liveValue}, which accepts both shapes, so a plain object — yaml\n * config on an older host, and every test fixture — keeps working unchanged.\n */\nexport interface Config {\n /** Master switch; `false` mounts nothing and reads nothing. */\n enabled?: boolean\n /**\n * Project-relative MCP documents to read, lowest priority first — a later\n * document overrides an earlier entry of the same `serverName`. A spec is\n * relative to the project root, or absolute, or `~/…` / `$DSH_HOME/…`.\n * Default: `['.dsh/mcp.json']`.\n */\n localFiles?: string[]\n /**\n * Global MCP documents read before a project's own, lowest priority first.\n * A relative spec resolves against `$HOME`; `~`, `$DSH_HOME` and absolute\n * paths work as in {@link localFiles}. Empty — the default — reads none, so\n * a project never inherits a server it did not declare.\n *\n * A boolean is accepted as a **migration guard only**, for a config written\n * when this key was the switch \"also read `~/.dsh/mcp.json` and\n * `~/.kimi-code/mcp.json`\": `true` reads `~/.dsh/mcp.json`, `false` reads\n * nothing. Set a list instead.\n */\n globalFiles?: string[] | boolean\n /** Read `<project>/.env` and `<project>/.dsh/.env` for `${...}` values. */\n envFiles?: boolean\n /** Values for `${input:NAME}` references, consulted before env and credentials. */\n inputs?: Record<string, string>\n /** Directory names that terminate the upward project-root walk. */\n projectMarkers?: string[]\n /** File suffixes that also terminate the upward project-root walk. */\n fileMarkers?: string[]\n /** Timeout for every generated mcp-client config. */\n toolCallTimeoutMs?: number\n /** Whether a failed initial MCP connection should fail the mount. */\n failOnStartupError?: boolean\n /** Report a mount that produced no tool within this window as an error row; `0` disables. */\n connectTimeoutMs?: number\n /** Mount a session's project on its first turn instead of at session creation. */\n lazy?: boolean\n /** Release a session's mounts after this much inactivity; `0` disables. */\n idleTimeoutMs?: number\n /** How long the first step of a turn may wait for a pending mount; `0` never waits. */\n activationWaitMs?: number\n /** Profile-level `serverName` reservations win; the project row becomes `conflict`. */\n profileWins?: boolean\n /**\n * Local namespace a project entry mounts under when the profile already owns\n * its `serverName` and the user chose to see this project's copy as well,\n * at most five characters (`[A-Za-z0-9_-]`, {@link isValidLocalPrefix}).\n * Empty — the default — derives one from the project's own folder, so a\n * conflict has an answer without a setting. Only the local answer reads it:\n * the choice that mounts the entry under its declared name needs no prefix.\n */\n localPrefix?: string\n /** Watch project config documents for edits and re-sync. */\n watch?: boolean\n /** Debounce applied to watcher and lifecycle events (ms). */\n debounceMs?: number\n /** Safety-net rescan interval (ms). */\n rescanIntervalMs?: number\n /** Credentials document consulted for `${input:NAME}` values. */\n credentialsFile?: string\n /**\n * Offer the session's MCP tools through `mcp_search_tools` + activation, and\n * put the active ones back into each assembled request. `false` restores the\n * plain registry presentation: every mounted tool is always listed.\n */\n activationEnabled?: boolean\n /** Tools the durable counters may seed into the always-offered baseline; `0` seeds none. */\n activationSeeded?: number\n /** Calls one tool needs in the counters before it is seeded into the baseline. */\n activationMinCalls?: number\n /** Drop a session-activated tool after this long without a call; `0` disables. */\n toolIdleMs?: number\n /**\n * Publish one short project-MCP guidance section in the session's system\n * prompt, ahead of the per-server `mcp:<server>` instruction blocks, so the\n * model knows the rest of the project's tools can be requested. `false`\n * registers no section at all.\n */\n guidanceEnabled?: boolean\n /**\n * Cap on the names the context-driven tier offers at once; `0` disables the\n * tier. Optional so a config object that predates this feature keeps the\n * shipped default.\n */\n activationAutoLimit?: number\n /** Extra advances one context-driven offer survives after leaving the ranking. */\n activationAutoStickySteps?: number\n /**\n * Serialized size of a session's MCP surface, in characters, above which its\n * tools are offered on demand instead of being listed; `0` defers every\n * surface, however small.\n */\n activationToolBudgetChars?: number\n /**\n * Permit the panel to write the documents of the `globalFiles` list. `false`\n * keeps them read-only; a write also needs an explicit per-write consent, so\n * both gates must be open. Default `false`.\n */\n allowGlobalWrite?: boolean\n}\n\nconst DEFAULTS = {\n enabled: true,\n localFiles: [...DEFAULT_LOCAL_FILES],\n globalFiles: [...DEFAULT_GLOBAL_FILES],\n envFiles: true,\n toolCallTimeoutMs: 60_000,\n failOnStartupError: false,\n connectTimeoutMs: 60_000,\n lazy: true,\n idleTimeoutMs: 300_000,\n activationWaitMs: 2_000,\n profileWins: true,\n localPrefix: '',\n watch: true,\n debounceMs: 300,\n rescanIntervalMs: 10_000,\n activationEnabled: DEFAULT_ACTIVATION_ENABLED,\n activationSeeded: DEFAULT_ACTIVATION_SEEDED,\n activationMinCalls: DEFAULT_ACTIVATION_MIN_CALLS,\n toolIdleMs: DEFAULT_TOOL_IDLE_MS,\n guidanceEnabled: DEFAULT_GUIDANCE_ENABLED,\n activationAutoLimit: DEFAULT_AUTO_ACTIVATION_LIMIT,\n activationAutoStickySteps: DEFAULT_AUTO_ACTIVATION_STICKY_STEPS,\n activationToolBudgetChars: DEFAULT_TOOL_BUDGET_CHARS,\n allowGlobalWrite: false,\n} as const\n\nconst nonEmptyString = z.string().min(1)\n\n/**\n * The volatile-ref shape a DSH ≥ 0.1.7 host hands a volatile config field: a\n * stable reference whose `get()` reads the current, live-edited value.\n * Declared locally so no cordis version is needed to name it; an older host\n * passes the plain value instead, which {@link liveValue} also accepts.\n */\ninterface VolatileLike<T> {\n get(): T\n}\n\n// The loader's event typing ships with `@deepseek-ai/cordis-plugin-loader`,\n// which this plugin does not depend on; declaring the one event it listens to\n// keeps the dependency surface unchanged. The signature matches the loader's\n// own augmentation, so both merge cleanly where the loader's types are loaded.\ndeclare module '@deepseek-ai/cordis' {\n interface Events {\n /**\n * Volatile config values were committed into the running fiber without a\n * remount; dispatched to the owning fiber only.\n * @param paths - changed config paths as key arrays.\n */\n 'loader/volatile-update'(paths: readonly (readonly string[])[]): void\n }\n}\n\n/**\n * Mark a config field volatile — live-editable from Plugins → dsh-project-mcp\n * on DSH ≥ 0.1.7 — when the installed schemastery knows the flag. An older\n * schemastery at runtime gets the schema back unchanged, and the field stays\n * yaml-only there.\n */\nfunction volatileField<S>(schema: S): S {\n const mark = (schema as unknown as { volatile?: unknown }).volatile\n if (typeof mark !== 'function') return schema\n return (mark as (this: unknown) => S).call(schema)\n}\n\n/**\n * Read one config field that may be a live-edited volatile ref.\n * @param field - plain value, or a {@link VolatileLike} ref wrapping it.\n * @returns the current value, whichever shape arrived.\n */\nexport function liveValue<T>(field: T | VolatileLike<T> | undefined): T | undefined {\n if (\n typeof field === 'object' &&\n field !== null &&\n typeof (field as VolatileLike<T>).get === 'function'\n ) {\n return (field as VolatileLike<T>).get()\n }\n return field as T | undefined\n}\n\n/**\n * The {@link Config} keys a DSH ≥ 0.1.7 host may live-edit without restarting\n * the entry: all of them are read at use time, so merging them into the\n * running config is safe. Every other key is structural or boot-time\n * (documents, markers, credentials, the watch switch) and stays yaml-only.\n */\nexport const VOLATILE_CONFIG_KEYS: readonly (keyof RuntimeConfig)[] = [\n 'activationEnabled',\n 'activationSeeded',\n 'activationMinCalls',\n 'toolIdleMs',\n 'guidanceEnabled',\n 'activationAutoLimit',\n 'activationAutoStickySteps',\n 'activationToolBudgetChars',\n 'allowGlobalWrite',\n 'envFiles',\n 'lazy',\n 'localPrefix',\n 'profileWins',\n 'connectTimeoutMs',\n 'toolCallTimeoutMs',\n 'idleTimeoutMs',\n 'debounceMs',\n 'activationWaitMs',\n]\n\n/** Validated Loader schema for {@link Config}. */\nexport const Config: z<Config> = z.object({\n enabled: z.boolean().default(DEFAULTS.enabled),\n localFiles: z.array(nonEmptyString).default([...DEFAULT_LOCAL_FILES]),\n // The union is a migration guard, not a second setting: a document still\n // carrying the boolean this key used to be validates instead of failing the\n // entry, and `configuredFiles` reads its intent.\n globalFiles: z.union([z.array(nonEmptyString), z.boolean()]).default([...DEFAULT_GLOBAL_FILES]),\n envFiles: volatileField(z.boolean().default(DEFAULTS.envFiles)),\n inputs: z.dict(String).default({}),\n projectMarkers: z.array(nonEmptyString).default([...DEFAULT_PROJECT_MARKERS]),\n fileMarkers: z.array(nonEmptyString).default([...DEFAULT_FILE_MARKERS]),\n toolCallTimeoutMs: volatileField(z.number().step(1).min(1).default(DEFAULTS.toolCallTimeoutMs)),\n failOnStartupError: z.boolean().default(DEFAULTS.failOnStartupError),\n connectTimeoutMs: volatileField(z.number().step(1).min(0).default(DEFAULTS.connectTimeoutMs)),\n lazy: volatileField(z.boolean().default(DEFAULTS.lazy)),\n idleTimeoutMs: volatileField(z.number().step(1).min(0).default(DEFAULTS.idleTimeoutMs)),\n activationWaitMs: volatileField(\n z.number().step(1).min(0).max(30_000).default(DEFAULTS.activationWaitMs),\n ),\n profileWins: volatileField(z.boolean().default(DEFAULTS.profileWins)),\n localPrefix: volatileField(z.string().default(DEFAULTS.localPrefix)),\n watch: z.boolean().default(DEFAULTS.watch),\n debounceMs: volatileField(z.number().step(1).min(0).max(60_000).default(DEFAULTS.debounceMs)),\n rescanIntervalMs: z.number().step(1).min(1_000).default(DEFAULTS.rescanIntervalMs),\n credentialsFile: z.string().default(''),\n activationEnabled: volatileField(z.boolean().default(DEFAULTS.activationEnabled)),\n activationSeeded: volatileField(z.number().step(1).min(0).default(DEFAULTS.activationSeeded)),\n activationMinCalls: volatileField(\n z.number().step(1).min(0).default(DEFAULTS.activationMinCalls),\n ),\n toolIdleMs: volatileField(z.number().step(1).min(0).default(DEFAULTS.toolIdleMs)),\n guidanceEnabled: volatileField(z.boolean().default(DEFAULTS.guidanceEnabled)),\n activationAutoLimit: volatileField(\n z.number().step(1).min(0).default(DEFAULTS.activationAutoLimit),\n ),\n activationAutoStickySteps: volatileField(\n z.number().step(1).min(0).default(DEFAULTS.activationAutoStickySteps),\n ),\n activationToolBudgetChars: volatileField(\n z.number().step(1).min(0).default(DEFAULTS.activationToolBudgetChars),\n ),\n allowGlobalWrite: volatileField(z.boolean().default(DEFAULTS.allowGlobalWrite)),\n})\n\n/** Cordis plugin name used by loader diagnostics. */\nexport const name = 'project-mcp'\n\n/** Services required before project MCP servers can be mounted. */\nexport const inject = ['tools']\n\n/** Service name under which the runtime publishes its snapshot. */\nexport const SERVICE_NAME = 'projectMcp'\n\n/** Read-only handle published as the `projectMcp` service. */\nexport interface ProjectMcpService {\n /** Current rows per project with live sessions, merged and split per session. */\n snapshot(): McpSnapshot\n /**\n * Run one reconciliation pass immediately and await it, as the operator call:\n * it may start a session's declared servers without that session having\n * started a turn. Every other pass — a turn, an event, the rescan tick —\n * mounts only the sessions whose own working directory asked for their\n * project.\n * @param projectRoot - restricts the pass to one project's sessions.\n */\n syncNow(projectRoot?: string): Promise<void>\n /**\n * Ask for the same pass and answer at once, without waiting for it: the\n * panel's `Sync`. Scripted reconciliation awaits {@link ProjectMcpService.syncNow}.\n * @param projectRoot - restricts the pass to one project's sessions.\n */\n syncSoon(projectRoot?: string): void\n /**\n * Drop the failed mounts and re-mount them (after fixing their cause). Answers\n * as soon as they are dropped; the pass that mounts them again runs in the\n * background, because waiting for it is what made the panel's `Retry` look\n * hung while a server was still connecting.\n * @param projectRoot - restricts the drop and the pass to one project.\n */\n retry(projectRoot?: string): Promise<void>\n /**\n * Watch the picture instead of asking for it: the listener is told the current\n * state at once, then once per change that changes something. Backs the\n * panel's status channel, so an open panel polls nothing.\n * @param listener - told the revision and the whole snapshot it belongs to.\n * @returns a disposer that stops watching.\n */\n subscribe(listener: (change: SnapshotChange) => void): () => void\n /** Give one session's servers back now, or every mounted session's when no id is given. */\n release(agentId?: string): Promise<void>\n /**\n * Read one tool's detail for a row a panel opened: its model-facing\n * description, the fields its schema accepts, and the reason this session's\n * request does not carry it. Answered on demand instead of riding the\n * snapshot, because descriptions and schemas are the expensive part and this\n * is read once per opened row.\n * @param projectRoot - project root the panel read the row from.\n * @param sessionId - live agent id the row belongs to.\n * @param name - public registry name, as the panel drew it.\n * @returns the tool's facts, or the coded refusal the route maps to a status.\n */\n toolFacts(projectRoot: string, sessionId: string, name: string): ToolFactsOutcome\n /**\n * Write one edited entry back to the document that declares it.\n * @param request - entry body, declaring document and the revision it was read at.\n * @returns the fresh snapshot, or the coded refusal the route maps to a status.\n */\n save(request: SaveRequest): Promise<SaveOutcome>\n /**\n * Pin or unpin one tool of one project. Durable, and never a rescan: the policy\n * is not part of any declaring document.\n * @param request - project root, public tool name and the wanted pin state.\n * @returns the fresh snapshot, or the coded refusal the route maps to a status.\n */\n setPin(request: PinRequest): PolicyOutcome\n /**\n * Store one project's tool mode (`disclosure` | `direct` | `off`).\n * @param request - project root and the mode to store.\n * @returns the fresh snapshot, or the coded refusal the route maps to a status.\n */\n setPolicy(request: PolicyRequest): PolicyOutcome\n /**\n * Choose which declaration of one contested `serverName` this project shows.\n * Durable, and followed by a reconcile: the choice is what moves the entry\n * between a conflict report and a mount under its local name.\n * @param request - project root, contested name and the declaration to show.\n * @returns the fresh snapshot, or the coded refusal the route maps to a status.\n */\n setConflictChoice(request: ConflictRequest): PolicyOutcome\n}\n\n/**\n * Mount project-declared MCP servers per session scope.\n * @param ctx - host context of the plugin entry.\n * @param config - validated plugin configuration.\n */\nexport async function apply(ctx: Context, config: Config): Promise<void> {\n if (config.enabled === false) {\n ctx.logger.info('project-mcp: disabled by configuration')\n return\n }\n const usage = new UsageStore({ logger: ctx.logger })\n // The per-project tool policy is durable state of the same kind as the\n // counters, so it is loaded once here and published by the same runtime.\n const policy = new PolicyStore({ logger: ctx.logger })\n const runtime = new ProjectMcpRuntime(ctx, resolveConfig(config), { usage, policy })\n // A volatile-capable host (DSH ≥ 0.1.7) re-points the volatile refs inside\n // `config` on every profile edit and announces it here instead of restarting\n // the entry; an older host never emits the event, so this subscribes\n // unconditionally. `resolveConfig` re-reads the refs through `liveValue`,\n // and the runtime merges only the volatile keys.\n ctx.on('loader/volatile-update', () => {\n runtime.applyLiveConfig(resolveConfig(config))\n })\n const service: ProjectMcpService = {\n snapshot: () => runtime.snapshot(),\n syncNow: (projectRoot) => runtime.syncNow(projectRoot),\n syncSoon: (projectRoot) => runtime.syncSoon(projectRoot),\n retry: (projectRoot) => runtime.retry(projectRoot),\n release: (agentId) => runtime.release(agentId),\n toolFacts: (projectRoot, sessionId, name) => runtime.toolFactsOf(projectRoot, sessionId, name),\n save: (request) => runtime.saveEntry(request),\n setPin: (request) => runtime.setPin(request),\n setPolicy: (request) => runtime.setPolicy(request),\n setConflictChoice: (request) => runtime.setConflictChoice(request),\n subscribe: (listener) => runtime.subscribe(listener),\n }\n // `agents` exists in every interactive composition but is resolved lazily so\n // the plugin still loads when a deployment mounts it without the agent plane.\n ctx.inject(['agents'], (scope) => {\n runtime.attach(scope as unknown as AgentScopeLike)\n scope.provide(SERVICE_NAME, service)\n })\n // The sidebar panel runs in the browser half, which can reach neither this\n // service nor the host context that owns it: publish the same surface over HTTP\n // when the composition has a web server.\n ctx.inject(['webServer'], (scope) => {\n const webServer = (scope as unknown as { webServer?: WebServerLike }).webServer\n if (webServer === undefined) return\n scope.effect(() => {\n const registration = registerRoutes(webServer, service)\n return () => disposeRegistration(registration)\n }, 'project-mcp: panel routes')\n })\n ctx.effect(\n () => () => {\n void runtime.disposeAll()\n },\n 'project-mcp: runtime',\n )\n // Counters ride the registry's own result event: one listener for every\n // agent, attributed through the runtime's agent -> project mapping, so only\n // servers this plugin mounted can be counted. Activation freshness rides the\n // same event — a real call is what keeps an activated tool offered — so no\n // second `tools/result` subscription exists.\n ctx.effect(() => {\n const dispose = observeToolResults({\n on: (event, handler) =>\n ctx.on(event, (exec: ToolResultEventLike, result: ToolResultLike) => {\n runtime.noteToolUse(exec.agent?.id, exec.name)\n return handler(exec, result)\n }),\n mountsFor: (agentId) => runtime.mountsFor(agentId),\n store: usage,\n })\n return () => {\n dispose()\n usage.dispose()\n }\n }, 'project-mcp: usage counters')\n // The policy store owns the same debounced write the counters do, so it is\n // flushed and stopped with the fiber that created it.\n ctx.effect(\n () => () => {\n policy.dispose()\n },\n 'project-mcp: tool policy',\n )\n}\n\n/**\n * The local prefix one config asks for.\n *\n * A value the `serverName` alphabet cannot carry, or one longer than the five\n * characters the panel promises, is refused rather than trimmed: a silently\n * different namespace would rename a project's tools behind the user's back.\n * The empty string — the default and the answer to a refused value — asks for\n * the prefix derived from the project's own folder.\n *\n * @param value - raw `localPrefix` from the config.\n * @returns a valid prefix, or `''` for the derived one.\n */\nfunction localPrefixOf(value: string | undefined): string {\n if (value === undefined || value === '') return ''\n if (value === value.trim() && isValidLocalPrefix(value)) return value\n return ''\n}\n\n/**\n * One configured document list, from either shape the config can carry.\n *\n * A list is used as written. A boolean is the migration guard of the key that\n * used to be the switch \"also read the global documents\": `true` meant the\n * documents in `legacyTrue` (what that switch turned on), `false` meant none.\n * An absent value falls back to the default list.\n *\n * @param value - raw `localFiles` or `globalFiles`.\n * @param fallback - list used when the config says nothing.\n * @param legacyTrue - documents a legacy `true` stands for.\n * @returns specs, lowest priority first, with blanks dropped.\n */\nfunction configuredFiles(\n value: readonly string[] | boolean | undefined,\n fallback: readonly string[],\n legacyTrue: readonly string[],\n): string[] {\n if (value === undefined) return [...fallback]\n if (Array.isArray(value)) return value.filter((spec) => spec !== '')\n return value ? [...legacyTrue] : []\n}\n\n/** Resolve the plugin config into the runtime's fully-defaulted shape. */\nexport function resolveConfig(config: Config): RuntimeConfig {\n return {\n localFiles: configuredFiles(config.localFiles, DEFAULTS.localFiles, DEFAULT_LOCAL_FILES),\n // The only key whose boolean is legacy: it used to switch the DSH home\n // document on, so that is what `true` keeps meaning here.\n globalFiles: configuredFiles(config.globalFiles, DEFAULTS.globalFiles, ['$DSH_HOME/mcp.json']),\n envFiles: liveValue(config.envFiles) ?? DEFAULTS.envFiles,\n inputs: config.inputs ?? {},\n projectMarkers: [...(config.projectMarkers ?? DEFAULT_PROJECT_MARKERS)],\n fileMarkers: [...(config.fileMarkers ?? DEFAULT_FILE_MARKERS)],\n toolCallTimeoutMs: liveValue(config.toolCallTimeoutMs) ?? DEFAULTS.toolCallTimeoutMs,\n failOnStartupError: config.failOnStartupError ?? DEFAULTS.failOnStartupError,\n connectTimeoutMs: liveValue(config.connectTimeoutMs) ?? DEFAULTS.connectTimeoutMs,\n lazy: liveValue(config.lazy) ?? DEFAULTS.lazy,\n idleTimeoutMs: liveValue(config.idleTimeoutMs) ?? DEFAULTS.idleTimeoutMs,\n activationWaitMs: liveValue(config.activationWaitMs) ?? DEFAULTS.activationWaitMs,\n profileWins: liveValue(config.profileWins) ?? DEFAULTS.profileWins,\n localPrefix: localPrefixOf(liveValue(config.localPrefix)),\n watch: config.watch ?? DEFAULTS.watch,\n debounceMs: liveValue(config.debounceMs) ?? DEFAULTS.debounceMs,\n rescanIntervalMs: config.rescanIntervalMs ?? DEFAULTS.rescanIntervalMs,\n credentialsFile:\n config.credentialsFile !== undefined && config.credentialsFile !== ''\n ? config.credentialsFile\n : defaultCredentialsPath(),\n activationEnabled: liveValue(config.activationEnabled) ?? DEFAULTS.activationEnabled,\n activationSeeded: liveValue(config.activationSeeded) ?? DEFAULTS.activationSeeded,\n activationMinCalls: liveValue(config.activationMinCalls) ?? DEFAULTS.activationMinCalls,\n toolIdleMs: liveValue(config.toolIdleMs) ?? DEFAULTS.toolIdleMs,\n guidanceEnabled: liveValue(config.guidanceEnabled) ?? DEFAULTS.guidanceEnabled,\n activationAutoLimit: liveValue(config.activationAutoLimit) ?? DEFAULTS.activationAutoLimit,\n activationAutoStickySteps:\n liveValue(config.activationAutoStickySteps) ?? DEFAULTS.activationAutoStickySteps,\n activationToolBudgetChars:\n liveValue(config.activationToolBudgetChars) ?? DEFAULTS.activationToolBudgetChars,\n allowGlobalWrite: liveValue(config.allowGlobalWrite) ?? DEFAULTS.allowGlobalWrite,\n }\n}\n"],"mappings":";;;;;;;;;AAsgBA,MAAa,sBAAkC;CAAE,MAAM;CAAc,MAAM,CAAC;CAAG,SAAS,CAAC;AAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC5d3F,MAAa,6BAA6B;;;;;;AAO1C,MAAa,4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