dsh-project-mcp 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +983 -0
- package/cordis.patch.yml +7 -0
- package/locale/en.json +6 -0
- package/locale/ru.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +106 -0
- package/src/activation.ts +1632 -0
- package/src/bridge.ts +486 -0
- package/src/client/design-fixtures.ts +399 -0
- package/src/client/design.ts +410 -0
- package/src/client/index.ts +255 -0
- package/src/client/locales/host.ts +570 -0
- package/src/client/locales/ui.ts +914 -0
- package/src/client/plugin-config.ts +721 -0
- package/src/client/policy.ts +277 -0
- package/src/client/settings-tools.ts +1136 -0
- package/src/client/settings.ts +3603 -0
- package/src/client/tab-locale.ts +94 -0
- package/src/client/toasts.ts +553 -0
- package/src/client/usage-view.ts +190 -0
- package/src/client/view.ts +4120 -0
- package/src/discovery.ts +211 -0
- package/src/guidance.ts +415 -0
- package/src/index.ts +685 -0
- package/src/logs.ts +184 -0
- package/src/naming.ts +134 -0
- package/src/notifications.ts +254 -0
- package/src/parse.ts +637 -0
- package/src/policy.ts +425 -0
- package/src/runtime.ts +4222 -0
- package/src/shared.ts +130 -0
- package/src/types.ts +662 -0
- package/src/ui.ts +579 -0
- package/src/usage.ts +442 -0
- package/src/write.ts +447 -0
package/src/runtime.ts
ADDED
|
@@ -0,0 +1,4222 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Project-scoped MCP mounting runtime.
|
|
3
|
+
*
|
|
4
|
+
* Isolation model: every live agent (session) resolves its own working
|
|
5
|
+
* directory to a project root, and the servers declared by that project are
|
|
6
|
+
* mounted **once for the project** inside a Cordis scope minted for it
|
|
7
|
+
* (`createScope(hostCtx, projectKey)`), exactly the pattern the in-box
|
|
8
|
+
* browser-use runtime uses for MCP servers. Each session additionally gets its
|
|
9
|
+
* own scope, parented to its project's (`bindScopeParent(agent, projectKey)`):
|
|
10
|
+
* a session sees its project's layer through the scope chain, which is how one
|
|
11
|
+
* child process serves every session of that project — subagents included —
|
|
12
|
+
* while a session of another project never resolves it. Because mcp-client
|
|
13
|
+
* reserves a `serverName` per registration scope, two projects may declare the
|
|
14
|
+
* same name without a conflict, and the plugin's own teardown disposes every
|
|
15
|
+
* scope it minted: the project scope when its last holder releases it, so a
|
|
16
|
+
* shared instance goes away on exactly the trigger a per-session one did.
|
|
17
|
+
*
|
|
18
|
+
* @module dsh-project-mcp/runtime
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { readFileSync, statSync, watch } from 'node:fs'
|
|
22
|
+
import type { FSWatcher } from 'node:fs'
|
|
23
|
+
import { homedir } from 'node:os'
|
|
24
|
+
import * as mcpClient from '@deepseek-ai/dsh-mcp-client'
|
|
25
|
+
import { bindScopeParent, createScope, scopeOf } from '@deepseek-ai/dsh-scope'
|
|
26
|
+
import type { Scope, ScopeParentBinding } from '@deepseek-ai/dsh-scope'
|
|
27
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
28
|
+
import { ForwardBatch, forwardProjectTools, projectToolNames } from './bridge.ts'
|
|
29
|
+
import type { BridgeContextLike, BridgeRegistryLike } from './bridge.ts'
|
|
30
|
+
import {
|
|
31
|
+
DEFAULT_ACTIVATION_ENABLED,
|
|
32
|
+
DEFAULT_ACTIVATION_MIN_CALLS,
|
|
33
|
+
DEFAULT_ACTIVATION_SEEDED,
|
|
34
|
+
DEFAULT_TOOL_IDLE_MS,
|
|
35
|
+
SEARCH_TOOL_NAME,
|
|
36
|
+
createActivationState,
|
|
37
|
+
createAutoOfferState,
|
|
38
|
+
installActivation,
|
|
39
|
+
noteUse,
|
|
40
|
+
presentedNames,
|
|
41
|
+
pruneIdle,
|
|
42
|
+
seedFromUsage,
|
|
43
|
+
toolsFor,
|
|
44
|
+
} from './activation.ts'
|
|
45
|
+
import type {
|
|
46
|
+
ActivationContextLike,
|
|
47
|
+
ActivationState,
|
|
48
|
+
AutoOfferState,
|
|
49
|
+
ToolSchemaLike,
|
|
50
|
+
} from './activation.ts'
|
|
51
|
+
import {
|
|
52
|
+
configDirectories,
|
|
53
|
+
findProjectRoot,
|
|
54
|
+
globalConfigPaths,
|
|
55
|
+
localConfigPaths,
|
|
56
|
+
projectEnvPaths,
|
|
57
|
+
readEnvFile,
|
|
58
|
+
readSecrets,
|
|
59
|
+
} from './discovery.ts'
|
|
60
|
+
import {
|
|
61
|
+
DEFAULT_GUIDANCE_ENABLED,
|
|
62
|
+
buildGuidance,
|
|
63
|
+
installGuidance,
|
|
64
|
+
projectLabel,
|
|
65
|
+
} from './guidance.ts'
|
|
66
|
+
import type { GuidanceContextLike, GuidanceServer } from './guidance.ts'
|
|
67
|
+
// The volatile key list lives at the entry (`src/index.ts`) because the schema
|
|
68
|
+
// declares it; the import cycles back here, but it is read only inside
|
|
69
|
+
// `applyLiveConfig`, long after both modules finished evaluating.
|
|
70
|
+
import { VOLATILE_CONFIG_KEYS } from './index.ts'
|
|
71
|
+
import { LOG_PAGE_SIZE, countForSession, countOf, latest } from './logs.ts'
|
|
72
|
+
import { emitEvent, logConsumer, subscribeEvent } from './notifications.ts'
|
|
73
|
+
import type { PluginEvent } from './notifications.ts'
|
|
74
|
+
import {
|
|
75
|
+
SERVER_NAME_PATTERN,
|
|
76
|
+
extractServerMap,
|
|
77
|
+
mergeEntries,
|
|
78
|
+
parseDocument,
|
|
79
|
+
referencesCredentials,
|
|
80
|
+
slugifyServerName,
|
|
81
|
+
} from './parse.ts'
|
|
82
|
+
import type { ParsedEntry, ParseIssue, ResolveContext } from './parse.ts'
|
|
83
|
+
import { isValidLocalPrefix, resolveConflictNames } from './naming.ts'
|
|
84
|
+
import { aliasesOf, isConflictChoice, isToolMode } from './policy.ts'
|
|
85
|
+
import type { ConflictRequest, PinRequest, PolicyRequest, SaveErrorCode, SaveRequest } from './shared.ts'
|
|
86
|
+
import { DEFAULT_TOOL_POLICY } from './types.ts'
|
|
87
|
+
import type {
|
|
88
|
+
ConfiguredFile,
|
|
89
|
+
ConflictChoice,
|
|
90
|
+
EntrySnapshot,
|
|
91
|
+
McpSnapshot,
|
|
92
|
+
ProjectSnapshot,
|
|
93
|
+
PresentationOwner,
|
|
94
|
+
ServerConflict,
|
|
95
|
+
ServerRow,
|
|
96
|
+
ServerStatus,
|
|
97
|
+
ServerUsage,
|
|
98
|
+
SessionSnapshot,
|
|
99
|
+
SessionTools,
|
|
100
|
+
SnapshotChange,
|
|
101
|
+
SnapshotIssue,
|
|
102
|
+
ToolMode,
|
|
103
|
+
ToolPolicy,
|
|
104
|
+
WriteScope,
|
|
105
|
+
} from './types.ts'
|
|
106
|
+
import { matchServer } from './usage.ts'
|
|
107
|
+
import {
|
|
108
|
+
applyEntry,
|
|
109
|
+
buildEntrySnapshot,
|
|
110
|
+
documentRevision,
|
|
111
|
+
entryToDeclaration,
|
|
112
|
+
visibleUrl,
|
|
113
|
+
WriteDocError,
|
|
114
|
+
writeDocument,
|
|
115
|
+
writeScopeFor,
|
|
116
|
+
} from './write.ts'
|
|
117
|
+
import type { CredentialKeys, WriteScopeInfo } from './write.ts'
|
|
118
|
+
|
|
119
|
+
/** Live agent handle: only the fields this plugin consumes. */
|
|
120
|
+
export interface AgentLike {
|
|
121
|
+
/** Session id, unique per agent. */
|
|
122
|
+
readonly id: string
|
|
123
|
+
/** Session header carrying the working directory. */
|
|
124
|
+
readonly session: { readonly header?: { readonly cwd?: string } }
|
|
125
|
+
/**
|
|
126
|
+
* Host-reported lifecycle status, when the composition publishes one. Read
|
|
127
|
+
* live where a release decision needs the truth rather than the last event
|
|
128
|
+
* this plugin happened to see.
|
|
129
|
+
*/
|
|
130
|
+
readonly status?: 'idle' | 'running'
|
|
131
|
+
/** The agent's own Cordis context. */
|
|
132
|
+
readonly ctx: Context
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** The subset of `ctx.agents` used here. */
|
|
136
|
+
export interface AgentsLike {
|
|
137
|
+
/** All live agents. */
|
|
138
|
+
list(): AgentLike[]
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** One agent-plane event, as far as this plugin consumes it. */
|
|
142
|
+
export interface AgentEventLike {
|
|
143
|
+
/** The subject agent. */
|
|
144
|
+
agent: AgentLike
|
|
145
|
+
/** `agent/status` only: whether a turn is currently running. */
|
|
146
|
+
status?: 'idle' | 'running'
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** The subset of the hosting scope used here. */
|
|
150
|
+
export interface AgentScopeLike {
|
|
151
|
+
/** Agent registry (injected). */
|
|
152
|
+
readonly agents: AgentsLike
|
|
153
|
+
/**
|
|
154
|
+
* Subscribe to an agent lifecycle or turn event. `agent/pre-step` is a
|
|
155
|
+
* waterfall hook, so its handler receives a continuation and must return it.
|
|
156
|
+
*/
|
|
157
|
+
on(name: string, handler: (event: AgentEventLike, next: () => Promise<unknown>) => unknown): unknown
|
|
158
|
+
/** Register a fiber-scoped cleanup. */
|
|
159
|
+
effect(fn: () => unknown, label?: string): unknown
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Resolved plugin configuration. */
|
|
163
|
+
export interface RuntimeConfig {
|
|
164
|
+
/**
|
|
165
|
+
* Project-relative MCP documents to read, lowest priority first. A spec is
|
|
166
|
+
* relative to the project root, or absolute / `~/…` / `$DSH_HOME/…`.
|
|
167
|
+
*/
|
|
168
|
+
localFiles: string[]
|
|
169
|
+
/**
|
|
170
|
+
* Global MCP documents read before a project's own, lowest priority first;
|
|
171
|
+
* `[]` reads none.
|
|
172
|
+
*/
|
|
173
|
+
globalFiles: string[]
|
|
174
|
+
/**
|
|
175
|
+
* Read the project's own dotenv documents (`<project>/.env` and
|
|
176
|
+
* `<project>/.dsh/.env`) for `${...}` values.
|
|
177
|
+
*/
|
|
178
|
+
envFiles?: boolean
|
|
179
|
+
inputs: Record<string, string>
|
|
180
|
+
projectMarkers: string[]
|
|
181
|
+
fileMarkers: string[]
|
|
182
|
+
toolCallTimeoutMs: number
|
|
183
|
+
failOnStartupError: boolean
|
|
184
|
+
/** Window after which a mount that produced no tool is reported as an error; `0` disables. */
|
|
185
|
+
connectTimeoutMs: number
|
|
186
|
+
/** Mount a session's project on its first turn instead of at session creation. */
|
|
187
|
+
lazy: boolean
|
|
188
|
+
/** Release a session's mounts after this much inactivity; `0` disables. */
|
|
189
|
+
idleTimeoutMs: number
|
|
190
|
+
/** How long the first step of a turn may wait for a pending mount; `0` never waits. */
|
|
191
|
+
activationWaitMs: number
|
|
192
|
+
profileWins: boolean
|
|
193
|
+
/**
|
|
194
|
+
* Local namespace a project entry takes when a profile-level instance already
|
|
195
|
+
* owns its `serverName` and the user chose to see the project's copy too.
|
|
196
|
+
* Empty asks for one derived from the project's own folder
|
|
197
|
+
* (`src/naming.ts`, {@link isValidLocalPrefix}); never longer than five
|
|
198
|
+
* characters, because it is a name a person has to read in front of every
|
|
199
|
+
* tool of that server.
|
|
200
|
+
*/
|
|
201
|
+
localPrefix: string
|
|
202
|
+
watch: boolean
|
|
203
|
+
debounceMs: number
|
|
204
|
+
rescanIntervalMs: number
|
|
205
|
+
credentialsFile: string
|
|
206
|
+
/**
|
|
207
|
+
* Offer the session's MCP tools through `mcp_search_tools` + activation, and
|
|
208
|
+
* put the active ones back into each assembled request. Optional so a config
|
|
209
|
+
* object that predates this feature keeps the shipped default.
|
|
210
|
+
*/
|
|
211
|
+
activationEnabled?: boolean
|
|
212
|
+
/** Total tools the durable counters may seed into the baseline; `0` seeds none. */
|
|
213
|
+
activationSeeded?: number
|
|
214
|
+
/** Calls one tool needs in the counters before it is seeded into the baseline. */
|
|
215
|
+
activationMinCalls?: number
|
|
216
|
+
/** Drop a session-activated tool after this long without a call; `0` disables. */
|
|
217
|
+
toolIdleMs?: number
|
|
218
|
+
/**
|
|
219
|
+
* Publish one short project-MCP guidance section in the session's system
|
|
220
|
+
* prompt, just ahead of the per-server `mcp:<server>` instruction blocks.
|
|
221
|
+
* `false` registers no section at all. Optional so a config object that
|
|
222
|
+
* predates this feature keeps the shipped default.
|
|
223
|
+
*/
|
|
224
|
+
guidanceEnabled?: boolean
|
|
225
|
+
/**
|
|
226
|
+
* Cap on the names the context-driven tier offers at once; `0` disables the
|
|
227
|
+
* tier. Optional so a config object that predates this feature keeps the
|
|
228
|
+
* shipped default.
|
|
229
|
+
*/
|
|
230
|
+
activationAutoLimit?: number
|
|
231
|
+
/** Extra advances one context-driven offer survives after leaving the ranking. */
|
|
232
|
+
activationAutoStickySteps?: number
|
|
233
|
+
/**
|
|
234
|
+
* Serialized size of a session's MCP surface, in characters, above which its
|
|
235
|
+
* tools are offered on demand instead of being listed; `0` defers every
|
|
236
|
+
* surface, however small.
|
|
237
|
+
*/
|
|
238
|
+
activationToolBudgetChars?: number
|
|
239
|
+
/**
|
|
240
|
+
* Permit writes to the documents of the `globalFiles` list. Off by default:
|
|
241
|
+
* a global write needs both this switch and an explicit per-write `consent`,
|
|
242
|
+
* so a panel mistake cannot rewrite every project's servers. Optional so a
|
|
243
|
+
* config object that predates this feature keeps it disabled.
|
|
244
|
+
*/
|
|
245
|
+
allowGlobalWrite?: boolean
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* Outcome of {@link ProjectMcpRuntime.saveEntry}: the fresh snapshot after a
|
|
250
|
+
* write, or the code the route maps to a status.
|
|
251
|
+
*/
|
|
252
|
+
export type SaveOutcome =
|
|
253
|
+
| { readonly ok: true; readonly snapshot: McpSnapshot }
|
|
254
|
+
| {
|
|
255
|
+
readonly ok: false
|
|
256
|
+
readonly code: SaveErrorCode
|
|
257
|
+
readonly message: string
|
|
258
|
+
/**
|
|
259
|
+
* Stable wire code of `message` (`projectMcp.host` namespace), for
|
|
260
|
+
* client-side translation (F-48); the prose `message` keeps its
|
|
261
|
+
* byte-identical English and stays the fallback.
|
|
262
|
+
*/
|
|
263
|
+
readonly messageCode?: string
|
|
264
|
+
/** Flat params of {@link messageCode}, stringified at emission. */
|
|
265
|
+
readonly messageParams?: Record<string, string>
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* Outcome of {@link ProjectMcpRuntime.setPin} and
|
|
270
|
+
* {@link ProjectMcpRuntime.setPolicy}: the fresh snapshot after the store was
|
|
271
|
+
* changed, or the code the route maps to a status. Both refusals are `400`s:
|
|
272
|
+
* `not-found` for a project this host has no live session in, `invalid` for a
|
|
273
|
+
* mode no assembly knows, `failed` when the host was built without a policy
|
|
274
|
+
* store.
|
|
275
|
+
*/
|
|
276
|
+
export type PolicyOutcome =
|
|
277
|
+
| { readonly ok: true; readonly snapshot: McpSnapshot }
|
|
278
|
+
| {
|
|
279
|
+
readonly ok: false
|
|
280
|
+
readonly code: SaveErrorCode
|
|
281
|
+
readonly message: string
|
|
282
|
+
/** Wire code of `message`, the same contract as {@link SaveOutcome}'s. */
|
|
283
|
+
readonly messageCode?: string
|
|
284
|
+
/** Flat params of {@link messageCode}, stringified at emission. */
|
|
285
|
+
readonly messageParams?: Record<string, string>
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* Identity of the Cordis scope one project's servers are mounted in. Every
|
|
290
|
+
* session of that project is parented to it, so the registrations inside are
|
|
291
|
+
* visible to those sessions and to nobody else.
|
|
292
|
+
*/
|
|
293
|
+
export interface ProjectScopeKey {
|
|
294
|
+
/** Project root whose sessions share this scope. */
|
|
295
|
+
readonly projectRoot: string
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* Whether one scope key names a project's shared registrations rather than a
|
|
300
|
+
* session. A host that models scopes (a test double, a diagnostic) can tell the
|
|
301
|
+
* two apart without the object identity the runtime keeps to itself.
|
|
302
|
+
* @param key - key handed to {@link RuntimeOptions.createScope}.
|
|
303
|
+
* @returns `true` when the key is a {@link ProjectScopeKey}.
|
|
304
|
+
*/
|
|
305
|
+
export function isProjectScopeKey(key: unknown): key is ProjectScopeKey {
|
|
306
|
+
return isRecord(key) && typeof (key as { projectRoot?: unknown }).projectRoot === 'string'
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** Injection points that tests override; production uses the real defaults. */
|
|
310
|
+
export interface RuntimeOptions {
|
|
311
|
+
/** Plugin object mounted per server; defaults to `@deepseek-ai/dsh-mcp-client`. */
|
|
312
|
+
plugin?: unknown
|
|
313
|
+
/**
|
|
314
|
+
* Scope factory; defaults to `createScope` from `@deepseek-ai/dsh-scope`.
|
|
315
|
+
* Called once per session and once per project that mounts something. The
|
|
316
|
+
* parent link of a session scope is established by the runtime itself, before
|
|
317
|
+
* this is called — the factory only mints the scope. A session key is the
|
|
318
|
+
* agent's own scope key; a project key is a {@link ProjectScopeKey}.
|
|
319
|
+
*/
|
|
320
|
+
createScope?: (ctx: Context, key: AgentLike | ProjectScopeKey) => Pick<Scope, 'ctx' | 'dispose'>
|
|
321
|
+
/**
|
|
322
|
+
* Registry surface the forwarding bridge reads: one scoped lookup. It is read
|
|
323
|
+
* off the plugin's own context by default, which is the same `ctx.tools` the
|
|
324
|
+
* registration path uses; tests override it with their double's registry.
|
|
325
|
+
*/
|
|
326
|
+
registry?: BridgeRegistryLike
|
|
327
|
+
/**
|
|
328
|
+
* Bridge context factory; defaults to reading the scope tag
|
|
329
|
+
* ({@link scopeOf}) from the minted scope's context and wiring the registry
|
|
330
|
+
* getter to it. A test whose scope double is a plain object overrides this,
|
|
331
|
+
* because its contexts carry no `dsh-scope` tag to read.
|
|
332
|
+
*/
|
|
333
|
+
bridgeContext?: (scope: Pick<Scope, 'ctx' | 'dispose'>) => BridgeContextLike
|
|
334
|
+
/** Durable counters `snapshot()` publishes alongside the rows; absent means none. */
|
|
335
|
+
usage?: UsageSource
|
|
336
|
+
/**
|
|
337
|
+
* Durable per-project policy the snapshot publishes and the assembly reads;
|
|
338
|
+
* absent means every project keeps {@link DEFAULT_TOOL_POLICY}.
|
|
339
|
+
*/
|
|
340
|
+
policy?: PolicySource
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** Read-only view of the durable counters, consulted by {@link ProjectMcpRuntime.snapshot}. */
|
|
344
|
+
export interface UsageSource {
|
|
345
|
+
/** Counters recorded for one project root, or `undefined` when it has none. */
|
|
346
|
+
forProject(projectRoot: string): Record<string, ServerUsage> | undefined
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/**
|
|
350
|
+
* The durable policy as the runtime consumes it: read on every snapshot and
|
|
351
|
+
* every assembly, written by the two panel service methods. Structural on
|
|
352
|
+
* purpose, so a test can pass a plain object and the plugin does not depend on
|
|
353
|
+
* the store class.
|
|
354
|
+
*/
|
|
355
|
+
export interface PolicySource {
|
|
356
|
+
/** Policy of one project root; the shipped default when none is stored. */
|
|
357
|
+
forProject(projectRoot: string): ToolPolicy
|
|
358
|
+
/** Store one project's mode and return the policy now in force. */
|
|
359
|
+
setMode(projectRoot: string, mode: ToolMode): ToolPolicy
|
|
360
|
+
/** Pin or unpin one tool of one project and return the policy now in force. */
|
|
361
|
+
setPin(projectRoot: string, tool: string, pinned: boolean): ToolPolicy
|
|
362
|
+
/**
|
|
363
|
+
* Store which declaration of one contested `serverName` the project shows and
|
|
364
|
+
* return the policy now in force.
|
|
365
|
+
*/
|
|
366
|
+
setConflictChoice(
|
|
367
|
+
projectRoot: string,
|
|
368
|
+
server: string,
|
|
369
|
+
choice: ConflictChoice,
|
|
370
|
+
): ToolPolicy
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/**
|
|
374
|
+
* What this plugin currently mounts for one live agent: the project root the
|
|
375
|
+
* agent resolved to and the server names it mounted there.
|
|
376
|
+
*/
|
|
377
|
+
export interface AgentMounts {
|
|
378
|
+
/** Project root the agent's working directory resolved to. */
|
|
379
|
+
projectRoot: string
|
|
380
|
+
/** Names of the servers this plugin mounted for that agent right now. */
|
|
381
|
+
servers: ReadonlySet<string>
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/** Minimal fiber surface used for mount bookkeeping. */
|
|
385
|
+
interface MountFiber {
|
|
386
|
+
dispose(): unknown
|
|
387
|
+
await?(): Promise<unknown>
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/** Result of a bounded wait on a fiber operation. */
|
|
391
|
+
type WaitOutcome<T> =
|
|
392
|
+
| { kind: 'settled'; value: T }
|
|
393
|
+
| { kind: 'failed'; error: unknown }
|
|
394
|
+
| { kind: 'timeout' }
|
|
395
|
+
|
|
396
|
+
/** Cordis fiber states (mirrors `@deepseek-ai/cordis`). */
|
|
397
|
+
const FIBER_ACTIVE = 2
|
|
398
|
+
|
|
399
|
+
/** Plugin names that identify a profile-level mcp-client registration. */
|
|
400
|
+
const MCP_CLIENT_ENTRY_NAMES = new Set(['@deepseek-ai/dsh-mcp-client', 'dsh-mcp-client'])
|
|
401
|
+
|
|
402
|
+
/**
|
|
403
|
+
* Entry names that identify a second owner of the assembled tool list.
|
|
404
|
+
*
|
|
405
|
+
* Matched the way {@link MCP_CLIENT_ENTRY_NAMES} is: by the module specifier the
|
|
406
|
+
* loader entry imports. A loader entry's `options.name` names a module, not a
|
|
407
|
+
* capability, so a check that did not name the known owners could not tell a
|
|
408
|
+
* presentation plugin from a logging one. The scoped spelling is included
|
|
409
|
+
* because that is how a published plugin is mounted in a profile.
|
|
410
|
+
*/
|
|
411
|
+
const PRESENTATION_OWNER_ENTRY_NAMES = new Set([
|
|
412
|
+
'@deepseek-ai/dsh-progressive-tools',
|
|
413
|
+
'dsh-progressive-tools',
|
|
414
|
+
])
|
|
415
|
+
|
|
416
|
+
/**
|
|
417
|
+
* Why this plugin and another presentation owner cannot shape one request.
|
|
418
|
+
*
|
|
419
|
+
* One explanation for every owner, not one per artifact: the reason is about
|
|
420
|
+
* the plumbing (`assembly.tools` waterfall, outer listener wins) and not about
|
|
421
|
+
* what the other plugin is called. Short because a panel prints it in a single
|
|
422
|
+
* line under the tools list.
|
|
423
|
+
*/
|
|
424
|
+
const PRESENTATION_OWNER_NOTE =
|
|
425
|
+
'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.'
|
|
426
|
+
|
|
427
|
+
/**
|
|
428
|
+
* Host prose plus its wire code (F-48): the English sentence, byte-identical
|
|
429
|
+
* to what the site emitted before codes existed, and the `projectMcp.host`
|
|
430
|
+
* code the client translates by. The two travel as one value so a call site
|
|
431
|
+
* cannot reword the prose without touching the code, and so a reason passed
|
|
432
|
+
* down a call chain (`detach` → `releaseProject` → `unmount`) keeps its code.
|
|
433
|
+
*/
|
|
434
|
+
interface CodedText {
|
|
435
|
+
/** The English sentence, as it always read. */
|
|
436
|
+
readonly text: string
|
|
437
|
+
/** The dotted wire code, into the client's `projectMcp.host` namespace. */
|
|
438
|
+
readonly code: string
|
|
439
|
+
/** Flat params of the code, when it has any; numbers stringify here. */
|
|
440
|
+
readonly params?: Record<string, string>
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
/** `detail` of a declared server that `lazy` has not mounted yet. */
|
|
444
|
+
const LAZY_DETAIL: CodedText = {
|
|
445
|
+
code: 'idle.lazy',
|
|
446
|
+
text: 'not mounted yet — this session has not started a turn (lazy mounting is on)',
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/** Why one pass may start a project's servers for one session. */
|
|
450
|
+
export type MountTrigger = 'turn' | 'mounted' | 'eager' | 'operator'
|
|
451
|
+
|
|
452
|
+
/** What one session contributes to the mount decision of one pass. */
|
|
453
|
+
export interface MountDecision {
|
|
454
|
+
/** Whether `lazy` is on: without it a session mounts as soon as it exists. */
|
|
455
|
+
lazy: boolean
|
|
456
|
+
/** This session's own turn asked for its project (a pre-step or a `running` status). */
|
|
457
|
+
activationPending: boolean
|
|
458
|
+
/** This session already holds mounts, so a pass reconciles them live. */
|
|
459
|
+
mounted: boolean
|
|
460
|
+
/** An operator asked for exactly this session (`syncNow`, `retry`, an edit). */
|
|
461
|
+
operatorRequested: boolean
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
/**
|
|
465
|
+
* Sessions one pass may mount without their own turn asking: `'all'` for an
|
|
466
|
+
* operator call that reconciles every session, a set of session ids for a pass
|
|
467
|
+
* that belongs to one project, the project root itself for an operator call
|
|
468
|
+
* scoped to a project — matched while the pass runs, so it also covers a session
|
|
469
|
+
* whose working directory has not been read yet — and no requests at all for a
|
|
470
|
+
* pass driven by a turn, an event or the rescan tick.
|
|
471
|
+
*/
|
|
472
|
+
export type PassRequests = 'all' | ReadonlySet<string> | { readonly projectRoot: string }
|
|
473
|
+
|
|
474
|
+
/** The pass a turn, an event or the rescan tick runs: every session must ask. */
|
|
475
|
+
const NO_REQUESTS: PassRequests = new Set()
|
|
476
|
+
|
|
477
|
+
/**
|
|
478
|
+
* Decide whether one pass may start servers for one session, and why.
|
|
479
|
+
*
|
|
480
|
+
* The plugin's isolation rule lives here: a session starts the servers of the
|
|
481
|
+
* project its working directory resolves to only when *that* session asks to
|
|
482
|
+
* work there — its own turn, an operator request that names it, or a
|
|
483
|
+
* deployment that turned `lazy` off. A session that is merely live (restored,
|
|
484
|
+
* listed, idle, or another session's neighbour) never starts anything, and a
|
|
485
|
+
* session that already holds mounts is reconciled so edits reach them.
|
|
486
|
+
* @param decision - what one session contributes to one pass.
|
|
487
|
+
* @returns the trigger, or `undefined` when the session must stay idle.
|
|
488
|
+
*/
|
|
489
|
+
export function mountTrigger(decision: MountDecision): MountTrigger | undefined {
|
|
490
|
+
if (decision.operatorRequested) return 'operator'
|
|
491
|
+
if (decision.activationPending) return 'turn'
|
|
492
|
+
if (decision.mounted) return 'mounted'
|
|
493
|
+
if (!decision.lazy) return 'eager'
|
|
494
|
+
return undefined
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
/**
|
|
498
|
+
* Run the parsed config through mcp-client's own Schemastery schema, exactly as
|
|
499
|
+
* the in-box precedent does (`ctx.plugin(McpClient, McpClient.Config({...}))`):
|
|
500
|
+
* this fills `maxInstructionBytes`/`reconnect` defaults and fails loudly on a
|
|
501
|
+
* config the client would reject. A plugin without a callable `Config` keeps
|
|
502
|
+
* the raw value.
|
|
503
|
+
*/
|
|
504
|
+
function clientConfig(value: unknown): unknown {
|
|
505
|
+
const schema = (mcpClient as { Config?: (input: unknown) => unknown }).Config
|
|
506
|
+
return typeof schema === 'function' ? schema(value) : value
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
interface LoaderEntryLike {
|
|
510
|
+
options?: {
|
|
511
|
+
id?: unknown
|
|
512
|
+
name?: unknown
|
|
513
|
+
config?: { serverName?: unknown }
|
|
514
|
+
disabled?: unknown
|
|
515
|
+
}
|
|
516
|
+
fiber?: { state?: unknown }
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
interface LoaderLike {
|
|
520
|
+
entries?(): LoaderEntryLike[]
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
interface MountedInstance {
|
|
524
|
+
name: string
|
|
525
|
+
/**
|
|
526
|
+
* The `serverName` this mount actually registers under: the declared name, or
|
|
527
|
+
* the local alias when a profile instance owns the declared one. It is what
|
|
528
|
+
* the registry prefixes this server's tools with, so every lookup that goes by
|
|
529
|
+
* tool prefix — status, guidance, the activation baseline — reads this and
|
|
530
|
+
* never {@link name}.
|
|
531
|
+
*/
|
|
532
|
+
runtimeName: string
|
|
533
|
+
/** Project root whose declaration this instance was mounted from. */
|
|
534
|
+
projectRoot: string
|
|
535
|
+
fingerprint: string
|
|
536
|
+
fiber: MountFiber | undefined
|
|
537
|
+
status: ServerStatus
|
|
538
|
+
detail: string | undefined
|
|
539
|
+
/** Wire companions of {@link MountedInstance.detail} (F-48), set with it. */
|
|
540
|
+
detailCode: string | undefined
|
|
541
|
+
detailParams: Record<string, string> | undefined
|
|
542
|
+
source: string | undefined
|
|
543
|
+
transport: 'stdio' | 'streamable-http' | undefined
|
|
544
|
+
/** Endpoint label already stripped of arguments and query strings. */
|
|
545
|
+
endpoint: string
|
|
546
|
+
/** When this mount started, for the connect watchdog. */
|
|
547
|
+
startedAt: number
|
|
548
|
+
/** `true` once the watchdog has reported the mount as never connected. */
|
|
549
|
+
stalled: boolean
|
|
550
|
+
/** `true` when activation itself failed, so no retry can revive this fiber. */
|
|
551
|
+
failed: boolean
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
/**
|
|
555
|
+
* The forwarding bridge one session holds when its key could not be joined to
|
|
556
|
+
* its project's chain: the thin definitions registered in the session's own
|
|
557
|
+
* layer, and the subscription that keeps them level with the project's live
|
|
558
|
+
* tool set.
|
|
559
|
+
*/
|
|
560
|
+
interface BridgeForwarders {
|
|
561
|
+
/**
|
|
562
|
+
* The session's live registration batch. It owns the swap and the re-entrancy
|
|
563
|
+
* every registration forces on it (`tools/change` is emitted from inside the
|
|
564
|
+
* insertion, and the session is subscribed to it).
|
|
565
|
+
*/
|
|
566
|
+
readonly batch: ForwardBatch
|
|
567
|
+
/** Disposer of the project-scope `tools/change` subscription. */
|
|
568
|
+
detach: () => void
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
/**
|
|
572
|
+
* Where one session's MCP instances live — one home per project, forever.
|
|
573
|
+
*
|
|
574
|
+
* A session whose scope key could be parented to its project resolves the
|
|
575
|
+
* project's shared home directly: one scope and one process per declared
|
|
576
|
+
* server, shared by every session that works there. A session whose key the
|
|
577
|
+
* harness already parented to something else cannot join that chain —
|
|
578
|
+
* `dsh-scope` binds a key once, and the agent-preset roster binds every
|
|
579
|
+
* composed agent before it is published — so it holds the SAME project home and
|
|
580
|
+
* reads it through the forwarding bridge: a thin definition in its own layer
|
|
581
|
+
* whose call runs the project's own. That is what makes "one process per
|
|
582
|
+
* project" true in a preset composition too, instead of one instance per
|
|
583
|
+
* session. See `docs/design/contracts/bridge.md`.
|
|
584
|
+
*/
|
|
585
|
+
interface MountHome {
|
|
586
|
+
/** The project root whose declarations this home serves. */
|
|
587
|
+
projectRoot: string
|
|
588
|
+
/** Scope key the mcp-client instances are mounted under. */
|
|
589
|
+
key: AgentLike | ProjectScopeKey
|
|
590
|
+
/** The scope those instances live in; `undefined` before the first mount. */
|
|
591
|
+
scope: Pick<Scope, 'ctx' | 'dispose'> | undefined
|
|
592
|
+
/** One live instance per declared `serverName`. */
|
|
593
|
+
mounts: Map<string, MountedInstance>
|
|
594
|
+
/** `true` when every session of the project shares this home. */
|
|
595
|
+
shared: boolean
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
/**
|
|
599
|
+
* One project's shared mount state: the scope its sessions' servers are
|
|
600
|
+
* registered in, and the live mounts those sessions share. The scope is minted
|
|
601
|
+
* with the project's first mount and dropped with its last holder, so a project
|
|
602
|
+
* costs one scope and one process per declared server however many sessions
|
|
603
|
+
* work in it.
|
|
604
|
+
*/
|
|
605
|
+
interface ProjectState extends MountHome {
|
|
606
|
+
projectRoot: string
|
|
607
|
+
/** Scope key the project's registrations are tagged with. */
|
|
608
|
+
key: ProjectScopeKey
|
|
609
|
+
/** The project scope; `undefined` before the first mount and after teardown. */
|
|
610
|
+
scope: Pick<Scope, 'ctx' | 'dispose'> | undefined
|
|
611
|
+
/** One live instance per declared `serverName`, shared by every holder. */
|
|
612
|
+
mounts: Map<string, MountedInstance>
|
|
613
|
+
shared: true
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
/** No mounts: what a session that holds none sees. */
|
|
617
|
+
const NO_MOUNTS: ReadonlyMap<string, MountedInstance> = new Map()
|
|
618
|
+
|
|
619
|
+
/**
|
|
620
|
+
* Parent links minted for session scope keys, kept process-wide because the
|
|
621
|
+
* relation they feed (`bindScopeParent`) is process-wide too: a second runtime
|
|
622
|
+
* in one process reuses the handle the first bound instead of failing on a key
|
|
623
|
+
* that is already linked.
|
|
624
|
+
*/
|
|
625
|
+
const parentBindings = new WeakMap<object, ScopeParentBinding>()
|
|
626
|
+
|
|
627
|
+
/**
|
|
628
|
+
* Point one scope key at the scope key it may resolve layers from, and keep the
|
|
629
|
+
* binding that alone may re-link it later.
|
|
630
|
+
*
|
|
631
|
+
* This link is the mechanism that makes a project's shared servers visible to
|
|
632
|
+
* exactly its sessions: the tools registry and the prompt assembly resolve a
|
|
633
|
+
* session's catalog by walking `scopeChainOf(agentKey)`, so a project layer is
|
|
634
|
+
* reachable only from a key parented to it. Re-linking is what a project change
|
|
635
|
+
* and a release need, which is why the binding is retained rather than passed
|
|
636
|
+
* to {@link createScope} and forgotten: the dsh-scope contract for a re-link
|
|
637
|
+
* holds here — the runtime disposes the session scope and drops every
|
|
638
|
+
* registration produced under the old parent before pointing the key
|
|
639
|
+
* elsewhere.
|
|
640
|
+
*
|
|
641
|
+
* Reports who owns the resulting link: `true` when this runtime just created it
|
|
642
|
+
* or already owns the key's binding, `false` when another composition parented
|
|
643
|
+
* the key first — in which case the link is left untouched and the caller takes
|
|
644
|
+
* the forwarding bridge instead of silently moving a binding it does not own.
|
|
645
|
+
*
|
|
646
|
+
* @param key - scope key to link.
|
|
647
|
+
* @param parent - the key whose registrations the linked key may see.
|
|
648
|
+
* @returns whether this runtime now owns the link.
|
|
649
|
+
*/
|
|
650
|
+
function linkScopeParent(key: object, parent: object): boolean {
|
|
651
|
+
const bound = parentBindings.get(key)
|
|
652
|
+
if (bound !== undefined) {
|
|
653
|
+
bound.rebind(parent)
|
|
654
|
+
return true
|
|
655
|
+
}
|
|
656
|
+
try {
|
|
657
|
+
parentBindings.set(key, bindScopeParent(key, parent))
|
|
658
|
+
return true
|
|
659
|
+
} catch {
|
|
660
|
+
return false
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
interface AgentState {
|
|
665
|
+
agent: AgentLike
|
|
666
|
+
cwd: string | undefined
|
|
667
|
+
projectRoot: string | undefined
|
|
668
|
+
/**
|
|
669
|
+
* Digest of the last reconciled pass: the document set, the profile
|
|
670
|
+
* reservations, and the published state of the shared mounts. Identical means
|
|
671
|
+
* "nothing to do" — including when another session of the same project
|
|
672
|
+
* mounted, settled or dropped something this session would otherwise render
|
|
673
|
+
* from a stale row.
|
|
674
|
+
*/
|
|
675
|
+
digest: string | undefined
|
|
676
|
+
scope: Pick<Scope, 'ctx' | 'dispose'> | undefined
|
|
677
|
+
/**
|
|
678
|
+
* The project whose shared mounts this session currently holds; `undefined`
|
|
679
|
+
* while it holds none. Every holder resolves the one home, whether its own key
|
|
680
|
+
* joined the project's chain or the bridge carries the tools to it.
|
|
681
|
+
*/
|
|
682
|
+
project: ProjectState | undefined
|
|
683
|
+
/**
|
|
684
|
+
* The forwarding bridge this session holds when its key could not be parented
|
|
685
|
+
* to its project (the harness bound that key first, and `dsh-scope` binds a
|
|
686
|
+
* key once). `undefined` for a session whose own chain already resolves the
|
|
687
|
+
* project's layer, which needs no bridge.
|
|
688
|
+
*/
|
|
689
|
+
bridge: BridgeForwarders | undefined
|
|
690
|
+
/**
|
|
691
|
+
* Whether {@link linkScopeParent} linked this session's key, so a detach knows
|
|
692
|
+
* it owns the re-link and not another plugin that parented the same key.
|
|
693
|
+
*/
|
|
694
|
+
parentLinked: boolean
|
|
695
|
+
/**
|
|
696
|
+
* Layer-less scope key a released session is re-linked to. Without it a
|
|
697
|
+
* session that let a project's servers go would keep resolving them from the
|
|
698
|
+
* still-running shared layer — the one thing per-session mounting gave for
|
|
699
|
+
* free, because disposing the session scope removed its whole chain.
|
|
700
|
+
*/
|
|
701
|
+
detachedKey: object | undefined
|
|
702
|
+
rows: ServerRow[]
|
|
703
|
+
issues: SnapshotIssue[]
|
|
704
|
+
/**
|
|
705
|
+
* `serverName` conflicts of the last reconciled pass: a profile-level
|
|
706
|
+
* instance that already owns a name, or one name two project documents
|
|
707
|
+
* declare. Always the truth of that pass — an empty list is the answer "no
|
|
708
|
+
* conflicts", not an absent one.
|
|
709
|
+
*/
|
|
710
|
+
conflicts: ServerConflict[]
|
|
711
|
+
/** Last observed activity (turn start, step, turn end); `undefined` until then. */
|
|
712
|
+
lastActivityAt: number | undefined
|
|
713
|
+
/** `true` while a turn runs, so idle release never fires in the middle of one. */
|
|
714
|
+
busy: boolean
|
|
715
|
+
/**
|
|
716
|
+
* Set when a turn starts while nothing is mounted, so the next pass mounts
|
|
717
|
+
* the project even in `lazy` mode. Cleared by the pass that mounts it.
|
|
718
|
+
*/
|
|
719
|
+
activationPending: boolean
|
|
720
|
+
/**
|
|
721
|
+
* Session activation state (counter baseline + session-activated names).
|
|
722
|
+
* `undefined` until the session's first scope is minted and seeds it; kept
|
|
723
|
+
* across an idle release so the session keeps what it activated.
|
|
724
|
+
*/
|
|
725
|
+
activation: ActivationState | undefined
|
|
726
|
+
/**
|
|
727
|
+
* Number of the agent step this session is on, counted from `agent/pre-step`
|
|
728
|
+
* and starting at `1` for the first step the hook sees. `0` means no step has
|
|
729
|
+
* started yet, and then no offer carries a number.
|
|
730
|
+
*/
|
|
731
|
+
step: number
|
|
732
|
+
/**
|
|
733
|
+
* Step each session activation was recorded on, keyed by public name. Kept
|
|
734
|
+
* next to {@link AgentState.activation} because the two outlive an idle
|
|
735
|
+
* release together: the activation is what a row lists, and this is when it
|
|
736
|
+
* was offered. Pruned with the activation it belongs to.
|
|
737
|
+
*/
|
|
738
|
+
steps: Map<string, number>
|
|
739
|
+
/**
|
|
740
|
+
* Disposer of the activation wiring installed on the current scope. Kept so a
|
|
741
|
+
* scope teardown unregisters `mcp_search_tools` explicitly: the scope fiber
|
|
742
|
+
* owns that registration with the real registry, but a test host may publish a
|
|
743
|
+
* plain `tools` stub, and the tool must disappear either way.
|
|
744
|
+
*/
|
|
745
|
+
activationDispose: (() => void) | undefined
|
|
746
|
+
/**
|
|
747
|
+
* Disposer of the guidance-section wiring installed on the current scope. Kept
|
|
748
|
+
* for the same reason as {@link AgentState.activationDispose}: the scope fiber
|
|
749
|
+
* owns the registration with the real prompt registry, but a host that
|
|
750
|
+
* publishes a plain `systemPrompt` stub has only this path.
|
|
751
|
+
*/
|
|
752
|
+
guidanceDispose: (() => void) | undefined
|
|
753
|
+
/**
|
|
754
|
+
* Context-driven offer window (BM25 task ranking + sticky names). Kept next
|
|
755
|
+
* to `activation` so a re-minted scope of the same session resumes the offers
|
|
756
|
+
* it was showing instead of starting over — the same reason the activation
|
|
757
|
+
* state outlives an idle release.
|
|
758
|
+
*/
|
|
759
|
+
auto: AutoOfferState | undefined
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
interface CachedDocument {
|
|
763
|
+
mtimeMs: number
|
|
764
|
+
size: number
|
|
765
|
+
/** Exact bytes the parse was made from; the write path revises them. */
|
|
766
|
+
text: string
|
|
767
|
+
/**
|
|
768
|
+
* Identity of the value sources the parse expanded `${...}` against. A
|
|
769
|
+
* document whose own bytes did not move is still re-parsed when its sources
|
|
770
|
+
* did, so an edit to a project `.env` or to the credentials file reaches the
|
|
771
|
+
* mounts without `mcp.json` being touched at all.
|
|
772
|
+
*/
|
|
773
|
+
stamp: string
|
|
774
|
+
/** Raw `name -> entry` map the document declared, when it held one. */
|
|
775
|
+
raw: Record<string, unknown> | undefined
|
|
776
|
+
entries: ParsedEntry[]
|
|
777
|
+
issues: ParseIssue[]
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
/** Everything the editor needs from one declaring document, per server name. */
|
|
781
|
+
interface DocumentInfo extends WriteScopeInfo {
|
|
782
|
+
/** Content revision of the document at snapshot time. */
|
|
783
|
+
revision: string
|
|
784
|
+
/** Entry body per sanitized `serverName`, for the entries that parsed. */
|
|
785
|
+
entries: Map<string, EntrySnapshot>
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
/**
|
|
789
|
+
* Owns every project-scoped mount, the config watchers, and the rescan timer.
|
|
790
|
+
* One instance per plugin fiber; `attach()` binds it to the agent service.
|
|
791
|
+
*/
|
|
792
|
+
export class ProjectMcpRuntime {
|
|
793
|
+
private readonly states = new Map<string, AgentState>()
|
|
794
|
+
/** Projects with a live shared scope, keyed by project root. */
|
|
795
|
+
private readonly projects = new Map<string, ProjectState>()
|
|
796
|
+
private readonly documents = new Map<string, CachedDocument>()
|
|
797
|
+
/** Cached credentials document, re-read only when mtime/size change. */
|
|
798
|
+
private secrets: { mtimeMs: number; size: number; values: Record<string, string> } | undefined
|
|
799
|
+
/**
|
|
800
|
+
* Dotenv values per project document, re-read only when mtime/size change.
|
|
801
|
+
* Every pass of every session resolves `${...}` references, so an uncached
|
|
802
|
+
* read here would cost one stat plus parse per file per session per pass.
|
|
803
|
+
*/
|
|
804
|
+
private readonly envFiles = new Map<
|
|
805
|
+
string,
|
|
806
|
+
{ mtimeMs: number; size: number; values: Record<string, string> }
|
|
807
|
+
>()
|
|
808
|
+
private readonly watchers = new Map<string, FSWatcher[]>()
|
|
809
|
+
/** Config directories currently watched per project root. */
|
|
810
|
+
private readonly watchedDirs = new Map<string, WatchTarget[]>()
|
|
811
|
+
private readonly watchedRoots = new Set<string>()
|
|
812
|
+
private timer: ReturnType<typeof setInterval> | undefined
|
|
813
|
+
private debounce: ReturnType<typeof setTimeout> | undefined
|
|
814
|
+
private chain: Promise<void> = Promise.resolve()
|
|
815
|
+
/** The host's live-session registry, once `attach()` has bound one. */
|
|
816
|
+
private listAgents: (() => AgentLike[]) | undefined
|
|
817
|
+
/** `undefined` until a recursive watch has been attempted. */
|
|
818
|
+
private recursiveWatch: boolean | undefined = undefined
|
|
819
|
+
private ready = false
|
|
820
|
+
private disposed = false
|
|
821
|
+
/** Panels watching the picture through the status channel. */
|
|
822
|
+
private readonly listeners = new Set<(change: SnapshotChange) => void>()
|
|
823
|
+
/** Changes announced so far; the picture a stream opens on is revision `0`. */
|
|
824
|
+
private revision = 0
|
|
825
|
+
/** JSON of the last announced picture, so an unchanged pass announces nothing. */
|
|
826
|
+
private announced: string | undefined
|
|
827
|
+
/**
|
|
828
|
+
* Disposer of the DSH-log subscriber this runtime installs on the notification
|
|
829
|
+
* service in {@link ProjectMcpRuntime.attach}. One subscription per live
|
|
830
|
+
* runtime, dropped in {@link ProjectMcpRuntime.disposeAll}, so a re-mount
|
|
831
|
+
* cannot leave a second logger reading the same events.
|
|
832
|
+
*/
|
|
833
|
+
private detachLog: (() => void) | undefined
|
|
834
|
+
|
|
835
|
+
/**
|
|
836
|
+
* @param ctx - the plugin's own context (host/root scope).
|
|
837
|
+
* @param config - resolved plugin configuration.
|
|
838
|
+
* @param options - mount overrides (tests only).
|
|
839
|
+
*/
|
|
840
|
+
constructor(
|
|
841
|
+
private readonly ctx: Context,
|
|
842
|
+
private readonly config: RuntimeConfig,
|
|
843
|
+
private readonly options: RuntimeOptions = {},
|
|
844
|
+
) {}
|
|
845
|
+
|
|
846
|
+
/** Bind to the agent service: existing agents, lifecycle events, rescan timer. */
|
|
847
|
+
attach(scope: AgentScopeLike): void {
|
|
848
|
+
this.ready = true
|
|
849
|
+
// The DSH log is a consumer of the notification service, not a second write
|
|
850
|
+
// path: this runtime's own logger subscribes here, once, and is told every
|
|
851
|
+
// event the runtime publishes.
|
|
852
|
+
this.detachLog ??= subscribeEvent(logConsumer(this.ctx.logger))
|
|
853
|
+
this.listAgents = () => scope.agents.list()
|
|
854
|
+
scope.on('agent/created', ({ agent }) => {
|
|
855
|
+
if (this.disposed) return
|
|
856
|
+
this.states.set(agent.id, this.newState(agent))
|
|
857
|
+
// The scope is owned by this plugin, but the agent may also be disposed
|
|
858
|
+
// without a matching event reaching us first; this keeps teardown ordered.
|
|
859
|
+
agent.ctx.effect(
|
|
860
|
+
() => () => {
|
|
861
|
+
this.dropAgent(agent.id)
|
|
862
|
+
},
|
|
863
|
+
'project-mcp: session',
|
|
864
|
+
)
|
|
865
|
+
this.schedule('agent/created')
|
|
866
|
+
})
|
|
867
|
+
scope.on('agent/disposed', ({ agent }) => {
|
|
868
|
+
if (this.disposed) return
|
|
869
|
+
this.dropAgent(agent.id)
|
|
870
|
+
})
|
|
871
|
+
scope.on('agent/status', (event) => {
|
|
872
|
+
this.onStatus(event)
|
|
873
|
+
})
|
|
874
|
+
scope.on('agent/pre-step', (event, next) => this.onPreStep(event, next))
|
|
875
|
+
for (const agent of scope.agents.list()) this.states.set(agent.id, this.newState(agent))
|
|
876
|
+
scope.effect(
|
|
877
|
+
() => () => {
|
|
878
|
+
void this.disposeAll()
|
|
879
|
+
},
|
|
880
|
+
'project-mcp: lifecycle',
|
|
881
|
+
)
|
|
882
|
+
// The safety-net tick also drives idle release, so it runs whenever either
|
|
883
|
+
// of the two needs it.
|
|
884
|
+
if (this.config.watch || this.config.idleTimeoutMs > 0) {
|
|
885
|
+
this.timer = setInterval(() => this.schedule('rescan'), this.config.rescanIntervalMs)
|
|
886
|
+
// A rescan timer must not keep a headless DSH process alive on its own.
|
|
887
|
+
this.timer.unref?.()
|
|
888
|
+
}
|
|
889
|
+
this.schedule('attach')
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
/**
|
|
893
|
+
* Merge one live-edited config into the running one.
|
|
894
|
+
*
|
|
895
|
+
* A DSH ≥ 0.1.7 host serves the volatile config keys as a profile-backed
|
|
896
|
+
* form and re-resolves them on `loader/volatile-update` instead of
|
|
897
|
+
* restarting the entry. Only those keys are taken from `next` — every other
|
|
898
|
+
* key (documents, markers, credentials, the watch switch) stays whatever the
|
|
899
|
+
* entry booted with, because nothing here re-reads it safely at runtime.
|
|
900
|
+
* All volatile keys are consumed at use time, so the merge alone moves the
|
|
901
|
+
* behavior.
|
|
902
|
+
*
|
|
903
|
+
* The one exception is the safety-net tick: it is armed once in
|
|
904
|
+
* {@link ProjectMcpRuntime.attach}, yet its need — `watch || idleTimeoutMs
|
|
905
|
+
* > 0` — flips with a live edit of `idleTimeoutMs`, so it is re-armed or
|
|
906
|
+
* cleared here. Arming is reserved to an attached runtime: before
|
|
907
|
+
* `attach()` the merge alone is enough, because `attach()` arms from the
|
|
908
|
+
* merged values; after disposal nothing may come back.
|
|
909
|
+
*
|
|
910
|
+
* @param next - the freshly resolved config; only the volatile keys are read.
|
|
911
|
+
*/
|
|
912
|
+
applyLiveConfig(next: RuntimeConfig): void {
|
|
913
|
+
const target = this.config as Record<keyof RuntimeConfig, unknown>
|
|
914
|
+
for (const key of VOLATILE_CONFIG_KEYS) {
|
|
915
|
+
const value = next[key]
|
|
916
|
+
if (value !== undefined) target[key] = value
|
|
917
|
+
}
|
|
918
|
+
if (this.timer !== undefined && !this.config.watch && this.config.idleTimeoutMs === 0) {
|
|
919
|
+
clearInterval(this.timer)
|
|
920
|
+
this.timer = undefined
|
|
921
|
+
} else if (
|
|
922
|
+
this.timer === undefined &&
|
|
923
|
+
this.ready &&
|
|
924
|
+
!this.disposed &&
|
|
925
|
+
(this.config.watch || this.config.idleTimeoutMs > 0)
|
|
926
|
+
) {
|
|
927
|
+
this.timer = setInterval(() => this.schedule('rescan'), this.config.rescanIntervalMs)
|
|
928
|
+
// A rescan timer must not keep a headless DSH process alive on its own.
|
|
929
|
+
this.timer.unref?.()
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
/**
|
|
934
|
+
* Current snapshot: projects with live agents, their rows, and watched roots.
|
|
935
|
+
*
|
|
936
|
+
* Each project carries both a merge and the per-session split. The merge is
|
|
937
|
+
* deliberately not "first session wins": sessions of one project mount
|
|
938
|
+
* independently, so the same server can be mounted for one and idle for
|
|
939
|
+
* another, and the panel must not report a running server as idle (or hide a
|
|
940
|
+
* failing one) just because the idle session was registered first.
|
|
941
|
+
*
|
|
942
|
+
* A session that mounted tools also carries what it offers the model right
|
|
943
|
+
* now (see {@link sessionTools}); the row is derived per call, never stored,
|
|
944
|
+
* so a panel that polls after an activation sees it.
|
|
945
|
+
*/
|
|
946
|
+
snapshot(): McpSnapshot {
|
|
947
|
+
const byProject = new Map<string, ProjectSnapshot>()
|
|
948
|
+
for (const state of this.states.values()) {
|
|
949
|
+
if (state.projectRoot === undefined) continue
|
|
950
|
+
let project = byProject.get(state.projectRoot)
|
|
951
|
+
if (project === undefined) {
|
|
952
|
+
project = { projectRoot: state.projectRoot, sessionIds: [], rows: [], issues: [], sessions: [], conflicts: [] }
|
|
953
|
+
byProject.set(state.projectRoot, project)
|
|
954
|
+
}
|
|
955
|
+
project.sessionIds.push(state.agent.id)
|
|
956
|
+
project.sessions.push(this.sessionSnapshot(state, state.projectRoot))
|
|
957
|
+
mergeRows(project.rows, this.liveRows(state))
|
|
958
|
+
for (const issue of state.issues) {
|
|
959
|
+
if (!project.issues.some((existing) => existing.message === issue.message)) {
|
|
960
|
+
project.issues.push(issue)
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
// Conflicts merge exactly like issues do: every session of one root reads
|
|
964
|
+
// the same documents and the same profile, so one name gets one report and
|
|
965
|
+
// the first session to name it keeps it. The list is published even when
|
|
966
|
+
// empty — that is the panel's "no conflicts", not a field it guesses about.
|
|
967
|
+
if (state.conflicts.length > 0) {
|
|
968
|
+
const merged: ServerConflict[] = [...(project.conflicts ?? [])]
|
|
969
|
+
for (const conflict of state.conflicts) {
|
|
970
|
+
if (!merged.some((existing) => existing.server === conflict.server)) merged.push(conflict)
|
|
971
|
+
}
|
|
972
|
+
// Code-unit order, the rule the rest of the plugin sorts names by, so a
|
|
973
|
+
// project of two sessions reports one stable list.
|
|
974
|
+
merged.sort((left, right) =>
|
|
975
|
+
left.server < right.server ? -1 : left.server > right.server ? 1 : 0,
|
|
976
|
+
)
|
|
977
|
+
project.conflicts = merged
|
|
978
|
+
}
|
|
979
|
+
}
|
|
980
|
+
// Counters outlive the sessions that produced them, so they are read from
|
|
981
|
+
// the durable store instead of accumulated per session. The policy is
|
|
982
|
+
// published for every project, stored or not: the panel reads a project's
|
|
983
|
+
// mode and pins from here, and an absent field is meant for a host older
|
|
984
|
+
// than the policy store rather than for a project that never changed one.
|
|
985
|
+
for (const project of byProject.values()) {
|
|
986
|
+
const usage = this.options.usage?.forProject(project.projectRoot)
|
|
987
|
+
if (usage !== undefined) project.usage = usage
|
|
988
|
+
project.policy = this.policyFor(project.projectRoot)
|
|
989
|
+
// Which documents this project reads is a config fact, not a row fact, and
|
|
990
|
+
// the panel needs it to number a row's priority: publish it per project so
|
|
991
|
+
// the number matches the read order of this deployment.
|
|
992
|
+
project.files = this.readFiles(project.projectRoot)
|
|
993
|
+
// The tab is drawn from the snapshot, so the newest page rides here and the
|
|
994
|
+
// ring's size says how much more the route can page. A project that never
|
|
995
|
+
// recorded an event carries neither field — no empty array.
|
|
996
|
+
const logs = latest(project.projectRoot, LOG_PAGE_SIZE)
|
|
997
|
+
if (logs.length > 0) {
|
|
998
|
+
project.logs = logs
|
|
999
|
+
project.logCount = countOf(project.projectRoot)
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
// A second presentation owner belongs to the loaded profile, not to one
|
|
1003
|
+
// project, so the scan runs once per snapshot and the record rides every
|
|
1004
|
+
// project. Absent means this plugin assembles alone, which is what keeps a
|
|
1005
|
+
// panel from drawing a coexistence notice that is not true.
|
|
1006
|
+
const presentation = this.presentationOwner()
|
|
1007
|
+
if (presentation !== undefined) {
|
|
1008
|
+
for (const project of byProject.values()) project.presentation = presentation
|
|
1009
|
+
}
|
|
1010
|
+
return {
|
|
1011
|
+
ready: this.ready,
|
|
1012
|
+
projects: [...byProject.values()],
|
|
1013
|
+
sources: { local: [...this.config.localFiles], global: [...this.config.globalFiles] },
|
|
1014
|
+
watchedFiles: [...this.watchedRoots],
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
/**
|
|
1019
|
+
* Watch the picture instead of asking for it: the listener is told the current
|
|
1020
|
+
* state at once, then once per change that actually changes something — a pass
|
|
1021
|
+
* that committed, a mount that appeared or connected, a release, a save, a
|
|
1022
|
+
* policy write. A rescan that found the same servers announces nothing, so an
|
|
1023
|
+
* open panel receives no traffic for a project nothing is happening in.
|
|
1024
|
+
* @param listener - told the revision and the whole snapshot it belongs to.
|
|
1025
|
+
* @returns a disposer that stops watching.
|
|
1026
|
+
*/
|
|
1027
|
+
subscribe(listener: (change: SnapshotChange) => void): () => void {
|
|
1028
|
+
this.listeners.add(listener)
|
|
1029
|
+
try {
|
|
1030
|
+
listener({ revision: this.revision, snapshot: this.snapshot() })
|
|
1031
|
+
} catch (error) {
|
|
1032
|
+
this.ctx.logger.warn(`project-mcp: announcing the first snapshot failed: ${errorText(error)}`)
|
|
1033
|
+
}
|
|
1034
|
+
return () => {
|
|
1035
|
+
this.listeners.delete(listener)
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
/**
|
|
1040
|
+
* Announce the picture if it differs from the last one announced.
|
|
1041
|
+
*
|
|
1042
|
+
* The comparison is what keeps the status channel quiet: a pass runs on every
|
|
1043
|
+
* watcher event and every rescan tick, and almost all of them re-derive the
|
|
1044
|
+
* same rows. With no listener attached nothing is built at all — a headless
|
|
1045
|
+
* host pays nothing for a channel nobody reads.
|
|
1046
|
+
*/
|
|
1047
|
+
private notify(): void {
|
|
1048
|
+
if (this.listeners.size === 0 || this.disposed) return
|
|
1049
|
+
const snapshot = this.snapshot()
|
|
1050
|
+
const digest = JSON.stringify(snapshot)
|
|
1051
|
+
if (digest === this.announced) return
|
|
1052
|
+
this.announced = digest
|
|
1053
|
+
this.revision += 1
|
|
1054
|
+
const change: SnapshotChange = { revision: this.revision, snapshot }
|
|
1055
|
+
for (const listener of [...this.listeners]) {
|
|
1056
|
+
try {
|
|
1057
|
+
listener(change)
|
|
1058
|
+
} catch (error) {
|
|
1059
|
+
this.ctx.logger.warn(`project-mcp: announcing a change failed: ${errorText(error)}`)
|
|
1060
|
+
}
|
|
1061
|
+
}
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
/**
|
|
1065
|
+
* One session's snapshot row, carrying its live tool presentation only when
|
|
1066
|
+
* the host has mounted tools for it, and how much of the project's log history
|
|
1067
|
+
* belongs to it when there is any.
|
|
1068
|
+
* @param state - the session's own runtime state.
|
|
1069
|
+
* @param projectRoot - the project the session works in.
|
|
1070
|
+
* @returns the row; `tools` stays absent for an unmounted session, and
|
|
1071
|
+
* `logCount` for a session that recorded nothing.
|
|
1072
|
+
*/
|
|
1073
|
+
private sessionSnapshot(state: AgentState, projectRoot: string): SessionSnapshot {
|
|
1074
|
+
const session: SessionSnapshot = {
|
|
1075
|
+
id: state.agent.id,
|
|
1076
|
+
rows: this.liveRows(state),
|
|
1077
|
+
issues: state.issues,
|
|
1078
|
+
}
|
|
1079
|
+
const tools = this.sessionTools(state)
|
|
1080
|
+
if (tools !== undefined) session.tools = tools
|
|
1081
|
+
const logCount = countForSession(projectRoot, state.agent.id)
|
|
1082
|
+
if (logCount > 0) session.logCount = logCount
|
|
1083
|
+
session.conflicts = state.conflicts
|
|
1084
|
+
return session
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
/**
|
|
1088
|
+
* What one session offers the model, measured from its live state at call
|
|
1089
|
+
* time.
|
|
1090
|
+
*
|
|
1091
|
+
* The mounted set is the whole visible MCP surface — this plugin's project
|
|
1092
|
+
* mounts plus the profile plane and any F-19 forwarders — the same surface
|
|
1093
|
+
* the activation wiring measures against the budget, so the counts cannot
|
|
1094
|
+
* describe a different catalog than the one the request is built from. Total
|
|
1095
|
+
* on purpose: a probe that fails leaves the row out and warns instead of
|
|
1096
|
+
* failing the snapshot.
|
|
1097
|
+
* @param state - the session's own runtime state.
|
|
1098
|
+
* @returns the presentation row, or `undefined` when nothing is mounted.
|
|
1099
|
+
*/
|
|
1100
|
+
private sessionTools(state: AgentState): SessionTools | undefined {
|
|
1101
|
+
try {
|
|
1102
|
+
const mounted = this.visibleSchemas(state)
|
|
1103
|
+
if (mounted.length === 0) return undefined
|
|
1104
|
+
const activationEnabled = this.config.activationEnabled ?? DEFAULT_ACTIVATION_ENABLED
|
|
1105
|
+
return toolsFor({
|
|
1106
|
+
sessionId: state.agent.id,
|
|
1107
|
+
mounted,
|
|
1108
|
+
activation: activationEnabled ? this.seedActivation(state) : state.activation,
|
|
1109
|
+
auto: state.auto,
|
|
1110
|
+
activationEnabled,
|
|
1111
|
+
policy: this.policyFor(state.projectRoot),
|
|
1112
|
+
steps: state.steps,
|
|
1113
|
+
...(state.step === 0 ? {} : { step: state.step }),
|
|
1114
|
+
...(this.config.activationToolBudgetChars === undefined
|
|
1115
|
+
? {}
|
|
1116
|
+
: { budgetChars: this.config.activationToolBudgetChars }),
|
|
1117
|
+
})
|
|
1118
|
+
} catch (error) {
|
|
1119
|
+
this.ctx.logger.warn(
|
|
1120
|
+
`project-mcp: reading the tool presentation of session ${state.agent.id} failed: ${errorText(error)}`,
|
|
1121
|
+
)
|
|
1122
|
+
return undefined
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
/**
|
|
1127
|
+
* What this plugin currently mounts for one live agent: the project root the
|
|
1128
|
+
* agent resolved to and the server names it mounted there. `undefined` when
|
|
1129
|
+
* the agent is unknown or resolved to no project, so a tool call from it is
|
|
1130
|
+
* simply not counted.
|
|
1131
|
+
* @param agentId - agent (session) id a tool call ran for.
|
|
1132
|
+
*/
|
|
1133
|
+
mountsFor(agentId: string): AgentMounts | undefined {
|
|
1134
|
+
const state = this.states.get(agentId)
|
|
1135
|
+
if (state === undefined || state.projectRoot === undefined) return undefined
|
|
1136
|
+
return { projectRoot: state.projectRoot, servers: this.runtimeNamesOf(state) }
|
|
1137
|
+
}
|
|
1138
|
+
|
|
1139
|
+
/**
|
|
1140
|
+
* Pin or unpin one tool of one project.
|
|
1141
|
+
*
|
|
1142
|
+
* The project must be one this host currently has a live session in: the panel
|
|
1143
|
+
* only ever names a root it read from a snapshot, so anything else is a stale
|
|
1144
|
+
* click and is refused rather than stored for a project nothing would show. No
|
|
1145
|
+
* rescan follows — the policy is part of no declaring document — so the answer
|
|
1146
|
+
* carries the current snapshot with the fresh pin list.
|
|
1147
|
+
* @param request - project root, public tool name and the wanted pin state.
|
|
1148
|
+
* @returns the fresh snapshot, or the refusal code the route maps to a status.
|
|
1149
|
+
*/
|
|
1150
|
+
setPin(request: PinRequest): PolicyOutcome {
|
|
1151
|
+
const policy = this.options.policy
|
|
1152
|
+
if (policy === undefined) {
|
|
1153
|
+
return {
|
|
1154
|
+
ok: false,
|
|
1155
|
+
code: 'failed',
|
|
1156
|
+
message: 'this host has no tool-policy store',
|
|
1157
|
+
messageCode: 'save.noPolicyStore',
|
|
1158
|
+
}
|
|
1159
|
+
}
|
|
1160
|
+
if (!this.projectKnown(request.projectRoot)) {
|
|
1161
|
+
return {
|
|
1162
|
+
ok: false,
|
|
1163
|
+
code: 'not-found',
|
|
1164
|
+
message: `no live session in ${request.projectRoot}`,
|
|
1165
|
+
messageCode: 'save.noLiveSession',
|
|
1166
|
+
messageParams: { projectRoot: request.projectRoot },
|
|
1167
|
+
}
|
|
1168
|
+
}
|
|
1169
|
+
policy.setPin(request.projectRoot, request.tool, request.pinned)
|
|
1170
|
+
this.notify()
|
|
1171
|
+
return { ok: true, snapshot: this.snapshot() }
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
/**
|
|
1175
|
+
* Store one project's tool mode.
|
|
1176
|
+
*
|
|
1177
|
+
* The same two refusals as {@link setPin}, plus a mode no assembly knows: the
|
|
1178
|
+
* mode is read on every assembly, so a stored change applies to the next model
|
|
1179
|
+
* step without re-minting the session scope.
|
|
1180
|
+
* @param request - project root and the mode to store.
|
|
1181
|
+
* @returns the fresh snapshot, or the refusal code the route maps to a status.
|
|
1182
|
+
*/
|
|
1183
|
+
setPolicy(request: PolicyRequest): PolicyOutcome {
|
|
1184
|
+
if (!isToolMode(request.mode)) {
|
|
1185
|
+
return {
|
|
1186
|
+
ok: false,
|
|
1187
|
+
code: 'invalid',
|
|
1188
|
+
message: `unknown tool mode ${JSON.stringify(request.mode)}`,
|
|
1189
|
+
messageCode: 'save.unknownMode',
|
|
1190
|
+
messageParams: { mode: JSON.stringify(request.mode) },
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
const policy = this.options.policy
|
|
1194
|
+
if (policy === undefined) {
|
|
1195
|
+
return {
|
|
1196
|
+
ok: false,
|
|
1197
|
+
code: 'failed',
|
|
1198
|
+
message: 'this host has no tool-policy store',
|
|
1199
|
+
messageCode: 'save.noPolicyStore',
|
|
1200
|
+
}
|
|
1201
|
+
}
|
|
1202
|
+
if (!this.projectKnown(request.projectRoot)) {
|
|
1203
|
+
return {
|
|
1204
|
+
ok: false,
|
|
1205
|
+
code: 'not-found',
|
|
1206
|
+
message: `no live session in ${request.projectRoot}`,
|
|
1207
|
+
messageCode: 'save.noLiveSession',
|
|
1208
|
+
messageParams: { projectRoot: request.projectRoot },
|
|
1209
|
+
}
|
|
1210
|
+
}
|
|
1211
|
+
policy.setMode(request.projectRoot, request.mode)
|
|
1212
|
+
this.notify()
|
|
1213
|
+
return { ok: true, snapshot: this.snapshot() }
|
|
1214
|
+
}
|
|
1215
|
+
|
|
1216
|
+
/**
|
|
1217
|
+
* Choose which declaration of one contested `serverName` this project shows.
|
|
1218
|
+
*
|
|
1219
|
+
* The same two refusals as {@link setPin}, plus an answer no build knows. The
|
|
1220
|
+
* choice is stored first and the project reconciled right away, because a
|
|
1221
|
+
* choice is a mount changing name: the row it produces must be the row the
|
|
1222
|
+
* registry ends up carrying, not one that waits for the next turn.
|
|
1223
|
+
*
|
|
1224
|
+
* Nothing is refused for a name the project does not conflict over: the store
|
|
1225
|
+
* keeps a choice for a name that is not contested yet, so a declaration that
|
|
1226
|
+
* comes back — or a profile entry that is added later — finds the answer the
|
|
1227
|
+
* user already gave.
|
|
1228
|
+
* @param request - project root, contested name and the declaration to show.
|
|
1229
|
+
* @returns the fresh snapshot, or the refusal code the route maps to a status.
|
|
1230
|
+
*/
|
|
1231
|
+
setConflictChoice(request: ConflictRequest): PolicyOutcome {
|
|
1232
|
+
if (!isConflictChoice(request.choice)) {
|
|
1233
|
+
return {
|
|
1234
|
+
ok: false,
|
|
1235
|
+
code: 'invalid',
|
|
1236
|
+
message: `unknown conflict choice ${JSON.stringify(request.choice)}`,
|
|
1237
|
+
messageCode: 'save.unknownChoice',
|
|
1238
|
+
messageParams: { choice: JSON.stringify(request.choice) },
|
|
1239
|
+
}
|
|
1240
|
+
}
|
|
1241
|
+
if (!this.projectKnown(request.projectRoot)) {
|
|
1242
|
+
return {
|
|
1243
|
+
ok: false,
|
|
1244
|
+
code: 'not-found',
|
|
1245
|
+
message: `no live session in ${request.projectRoot}`,
|
|
1246
|
+
messageCode: 'save.noLiveSession',
|
|
1247
|
+
messageParams: { projectRoot: request.projectRoot },
|
|
1248
|
+
}
|
|
1249
|
+
}
|
|
1250
|
+
const policy = this.options.policy
|
|
1251
|
+
if (policy === undefined) {
|
|
1252
|
+
return {
|
|
1253
|
+
ok: false,
|
|
1254
|
+
code: 'failed',
|
|
1255
|
+
message: 'this host has no tool-policy store',
|
|
1256
|
+
messageCode: 'save.noPolicyStore',
|
|
1257
|
+
}
|
|
1258
|
+
}
|
|
1259
|
+
policy.setConflictChoice(request.projectRoot, request.server, request.choice)
|
|
1260
|
+
this.notify()
|
|
1261
|
+
// The pass that follows the click is what moves the entry between a
|
|
1262
|
+
// conflict report and a mount, and it is not awaited: an operator click
|
|
1263
|
+
// must not wait for a server to start.
|
|
1264
|
+
void this.syncNow(request.projectRoot)
|
|
1265
|
+
return { ok: true, snapshot: this.snapshot() }
|
|
1266
|
+
}
|
|
1267
|
+
|
|
1268
|
+
/**
|
|
1269
|
+
* The policy in force for one project root.
|
|
1270
|
+
*
|
|
1271
|
+
* Read at snapshot and assembly time — never captured — so a stored change is
|
|
1272
|
+
* visible to the next model step and to the next panel poll. A host built
|
|
1273
|
+
* without a store follows the shipped default for every project.
|
|
1274
|
+
* @param projectRoot - project root, or `undefined` before a session resolves one.
|
|
1275
|
+
* @returns the stored policy, or {@link DEFAULT_TOOL_POLICY} when there is none.
|
|
1276
|
+
*/
|
|
1277
|
+
private policyFor(projectRoot: string | undefined): ToolPolicy {
|
|
1278
|
+
if (projectRoot === undefined) return DEFAULT_TOOL_POLICY
|
|
1279
|
+
return this.options.policy?.forProject(projectRoot) ?? DEFAULT_TOOL_POLICY
|
|
1280
|
+
}
|
|
1281
|
+
|
|
1282
|
+
/**
|
|
1283
|
+
* Whether one project root has a live session on this host.
|
|
1284
|
+
* @param projectRoot - project root a policy request names.
|
|
1285
|
+
* @returns `true` when a bound session resolved to that root.
|
|
1286
|
+
*/
|
|
1287
|
+
private projectKnown(projectRoot: string): boolean {
|
|
1288
|
+
for (const state of this.states.values()) {
|
|
1289
|
+
if (state.projectRoot === projectRoot) return true
|
|
1290
|
+
}
|
|
1291
|
+
return false
|
|
1292
|
+
}
|
|
1293
|
+
|
|
1294
|
+
/**
|
|
1295
|
+
* Write one edited entry back to the document that declares it.
|
|
1296
|
+
*
|
|
1297
|
+
* The checks run in the contract's order and every one of them must pass
|
|
1298
|
+
* before a byte is written: the row must still exist, its declaring document
|
|
1299
|
+
* must belong to the project or to the (consented, enabled) global tier, the
|
|
1300
|
+
* revision must be the one the editor read, and the resulting entry must pass
|
|
1301
|
+
* the same parse path the mount uses. The document is then replaced by
|
|
1302
|
+
* {@link writeDocument} (`.bak`, then temp file, then rename) and rescanned,
|
|
1303
|
+
* so the answer carries a fresh snapshot.
|
|
1304
|
+
* @param request - the entry body, its declaring document and the read revision.
|
|
1305
|
+
* @returns the fresh snapshot, or the refusal code the route maps to a status.
|
|
1306
|
+
*/
|
|
1307
|
+
async saveEntry(request: SaveRequest): Promise<SaveOutcome> {
|
|
1308
|
+
const states = [...this.states.values()].filter((state) => state.projectRoot === request.projectRoot)
|
|
1309
|
+
const row = states
|
|
1310
|
+
.flatMap((state) => state.rows)
|
|
1311
|
+
.find((candidate) => candidate.name === request.server)
|
|
1312
|
+
if (row === undefined) {
|
|
1313
|
+
return {
|
|
1314
|
+
ok: false,
|
|
1315
|
+
code: 'not-found',
|
|
1316
|
+
message: `server "${request.server}" is not declared for ${request.projectRoot}`,
|
|
1317
|
+
messageCode: 'save.serverNotDeclared',
|
|
1318
|
+
messageParams: { server: request.server, projectRoot: request.projectRoot },
|
|
1319
|
+
}
|
|
1320
|
+
}
|
|
1321
|
+
const document = row.source
|
|
1322
|
+
if (document === undefined) {
|
|
1323
|
+
return {
|
|
1324
|
+
ok: false,
|
|
1325
|
+
code: 'blocked',
|
|
1326
|
+
message: `server "${request.server}" has no declaring document to write`,
|
|
1327
|
+
messageCode: 'save.noDeclaringDocument',
|
|
1328
|
+
messageParams: { server: request.server },
|
|
1329
|
+
}
|
|
1330
|
+
}
|
|
1331
|
+
const scope = writeScopeFor(document, request.projectRoot, {
|
|
1332
|
+
projectDocuments: localConfigPaths(request.projectRoot, this.config.localFiles),
|
|
1333
|
+
globalDocuments: this.globalFiles(),
|
|
1334
|
+
allowGlobalWrite: this.config.allowGlobalWrite === true,
|
|
1335
|
+
})
|
|
1336
|
+
if (scope.scope === 'readonly') {
|
|
1337
|
+
// The scope's own reason already carries its write.blocked.* code; the
|
|
1338
|
+
// save.notWritable fallback is for the reason-less shape alone.
|
|
1339
|
+
return {
|
|
1340
|
+
ok: false,
|
|
1341
|
+
code: 'blocked',
|
|
1342
|
+
message: scope.reason ?? `${document} is not writable`,
|
|
1343
|
+
messageCode: scope.blockedCode ?? 'save.notWritable',
|
|
1344
|
+
messageParams: scope.blockedParams ?? { document },
|
|
1345
|
+
}
|
|
1346
|
+
}
|
|
1347
|
+
if (scope.scope === 'global' && request.consent !== true) {
|
|
1348
|
+
return {
|
|
1349
|
+
ok: false,
|
|
1350
|
+
code: 'blocked',
|
|
1351
|
+
message: `writing ${document} needs explicit consent`,
|
|
1352
|
+
messageCode: 'save.needsConsent',
|
|
1353
|
+
messageParams: { document },
|
|
1354
|
+
}
|
|
1355
|
+
}
|
|
1356
|
+
if (scope.scope === 'global' && this.config.allowGlobalWrite !== true) {
|
|
1357
|
+
return {
|
|
1358
|
+
ok: false,
|
|
1359
|
+
code: 'blocked',
|
|
1360
|
+
message: `writing the global tier is disabled by this deployment (allowGlobalWrite: false)`,
|
|
1361
|
+
messageCode: 'save.globalDisabled',
|
|
1362
|
+
}
|
|
1363
|
+
}
|
|
1364
|
+
if (request.document !== document) {
|
|
1365
|
+
return {
|
|
1366
|
+
ok: false,
|
|
1367
|
+
code: 'not-found',
|
|
1368
|
+
message: `server "${request.server}" is now declared by ${document}`,
|
|
1369
|
+
messageCode: 'save.declaredElsewhere',
|
|
1370
|
+
messageParams: { server: request.server, document },
|
|
1371
|
+
}
|
|
1372
|
+
}
|
|
1373
|
+
let text: string
|
|
1374
|
+
try {
|
|
1375
|
+
text = readFileSync(document, 'utf8')
|
|
1376
|
+
} catch {
|
|
1377
|
+
return {
|
|
1378
|
+
ok: false,
|
|
1379
|
+
code: 'not-found',
|
|
1380
|
+
message: `the declaring document ${document} is gone`,
|
|
1381
|
+
messageCode: 'save.documentGone',
|
|
1382
|
+
messageParams: { document },
|
|
1383
|
+
}
|
|
1384
|
+
}
|
|
1385
|
+
if (documentRevision(text) !== request.revision) {
|
|
1386
|
+
return {
|
|
1387
|
+
ok: false,
|
|
1388
|
+
code: 'conflict',
|
|
1389
|
+
message: `${document} changed since the entry was read; reload it and edit again`,
|
|
1390
|
+
messageCode: 'save.documentChanged',
|
|
1391
|
+
messageParams: { document },
|
|
1392
|
+
}
|
|
1393
|
+
}
|
|
1394
|
+
let root: unknown
|
|
1395
|
+
try {
|
|
1396
|
+
root = JSON.parse(text) as unknown
|
|
1397
|
+
} catch (error) {
|
|
1398
|
+
return {
|
|
1399
|
+
ok: false,
|
|
1400
|
+
code: 'invalid',
|
|
1401
|
+
message: `the declaring document is not valid JSON: ${error instanceof Error ? error.message : String(error)}`,
|
|
1402
|
+
messageCode: 'save.invalidJson',
|
|
1403
|
+
messageParams: { document, error: error instanceof Error ? error.message : String(error) },
|
|
1404
|
+
}
|
|
1405
|
+
}
|
|
1406
|
+
const servers = isRecord(root) ? root.mcpServers : undefined
|
|
1407
|
+
if (!isRecord(servers)) {
|
|
1408
|
+
return {
|
|
1409
|
+
ok: false,
|
|
1410
|
+
code: 'blocked',
|
|
1411
|
+
message: `${document} does not use an "mcpServers" object, so this editor cannot rewrite it`,
|
|
1412
|
+
messageCode: 'save.noMcpServers',
|
|
1413
|
+
messageParams: { document },
|
|
1414
|
+
}
|
|
1415
|
+
}
|
|
1416
|
+
// The panel edits the sanitized `serverName`; the document key may differ
|
|
1417
|
+
// (`my server` vs `my-server`), so the declaration goes back under the key
|
|
1418
|
+
// the document actually holds.
|
|
1419
|
+
const key = Object.keys(servers).find(
|
|
1420
|
+
(candidate) => candidate === request.server || slugifyServerName(candidate) === request.server,
|
|
1421
|
+
)
|
|
1422
|
+
if (key === undefined) {
|
|
1423
|
+
return {
|
|
1424
|
+
ok: false,
|
|
1425
|
+
code: 'not-found',
|
|
1426
|
+
message: `server "${request.server}" is no longer declared in ${document}`,
|
|
1427
|
+
messageCode: 'save.noLongerDeclared',
|
|
1428
|
+
messageParams: { server: request.server, document },
|
|
1429
|
+
}
|
|
1430
|
+
}
|
|
1431
|
+
let next: string
|
|
1432
|
+
try {
|
|
1433
|
+
next = applyEntry(text, key, entryToDeclaration(request.entry, servers[key]))
|
|
1434
|
+
} catch (error) {
|
|
1435
|
+
// A WriteDocError already carries the refusal's wire code; anything else
|
|
1436
|
+
// crosses as prose alone.
|
|
1437
|
+
return {
|
|
1438
|
+
ok: false,
|
|
1439
|
+
code: 'invalid',
|
|
1440
|
+
message: error instanceof Error ? error.message : String(error),
|
|
1441
|
+
...(error instanceof WriteDocError
|
|
1442
|
+
? {
|
|
1443
|
+
messageCode: error.code,
|
|
1444
|
+
...(error.params === undefined ? {} : { messageParams: error.params }),
|
|
1445
|
+
}
|
|
1446
|
+
: {}),
|
|
1447
|
+
}
|
|
1448
|
+
}
|
|
1449
|
+
// Same parse path the mount uses: what the host would not mount, it does
|
|
1450
|
+
// not write either.
|
|
1451
|
+
const parsed = parseDocument(next, document, this.resolveContext(request.projectRoot))
|
|
1452
|
+
const candidate = parsed.entries.find((entry) => entry.name === request.server)
|
|
1453
|
+
if (candidate === undefined || candidate.error !== undefined || candidate.config === undefined) {
|
|
1454
|
+
// A parse failure's prose already has its own parse.* code (Task 2);
|
|
1455
|
+
// save.entryNotParsed names only the shapeless fallback.
|
|
1456
|
+
return {
|
|
1457
|
+
ok: false,
|
|
1458
|
+
code: 'invalid',
|
|
1459
|
+
message: candidate?.error ?? `the edited entry "${request.server}" did not parse`,
|
|
1460
|
+
messageCode: candidate?.errorCode ?? 'save.entryNotParsed',
|
|
1461
|
+
...(candidate?.errorCode === undefined
|
|
1462
|
+
? { messageParams: { server: request.server } }
|
|
1463
|
+
: candidate.errorParams === undefined
|
|
1464
|
+
? {}
|
|
1465
|
+
: { messageParams: candidate.errorParams }),
|
|
1466
|
+
}
|
|
1467
|
+
}
|
|
1468
|
+
try {
|
|
1469
|
+
writeDocument(document, next)
|
|
1470
|
+
} catch (error) {
|
|
1471
|
+
return {
|
|
1472
|
+
ok: false,
|
|
1473
|
+
code: 'failed',
|
|
1474
|
+
message: `writing ${document} failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
1475
|
+
messageCode: 'save.writeFailed',
|
|
1476
|
+
messageParams: { document, error: error instanceof Error ? error.message : String(error) },
|
|
1477
|
+
}
|
|
1478
|
+
}
|
|
1479
|
+
// Drop the read cache and the pass digest for this project: a write that
|
|
1480
|
+
// only reformats the document keeps the same mounted config, so the digest
|
|
1481
|
+
// alone would skip the row rebuild the editor needs.
|
|
1482
|
+
this.documents.delete(document)
|
|
1483
|
+
for (const state of states) state.digest = undefined
|
|
1484
|
+
// An edit belongs to the project that declares the entry: reconcile it as an
|
|
1485
|
+
// operator request for *its* sessions — so the change reaches a live mount —
|
|
1486
|
+
// and never as a request for another project, whose sessions must not start
|
|
1487
|
+
// a server because an entry moved here.
|
|
1488
|
+
await this.enqueue(new Set(states.map((state) => state.agent.id)))
|
|
1489
|
+
return { ok: true, snapshot: this.snapshot() }
|
|
1490
|
+
}
|
|
1491
|
+
|
|
1492
|
+
/**
|
|
1493
|
+
* Run one reconciliation pass and await it.
|
|
1494
|
+
*
|
|
1495
|
+
* The operator call: it requests every listed session — or, with a
|
|
1496
|
+
* `projectRoot`, only that project's — so a session whose declaration was
|
|
1497
|
+
* never mounted (or whose mount was dropped) may start here without a turn.
|
|
1498
|
+
* Every other pass — a turn, an event, the rescan tick — requests only the
|
|
1499
|
+
* sessions that asked. Scripted reconciliation uses this awaiting form; the
|
|
1500
|
+
* panel's `Sync` uses {@link syncSoon}.
|
|
1501
|
+
* @param projectRoot - restricts the pass to one project's sessions.
|
|
1502
|
+
*/
|
|
1503
|
+
async syncNow(projectRoot?: string): Promise<void> {
|
|
1504
|
+
await this.enqueue(this.requestsFor(projectRoot))
|
|
1505
|
+
}
|
|
1506
|
+
|
|
1507
|
+
/**
|
|
1508
|
+
* Ask for the same pass and return at once — the panel's `Sync`.
|
|
1509
|
+
*
|
|
1510
|
+
* Waiting for the pass is what turned a `Sync` on a project whose server was
|
|
1511
|
+
* still connecting into a hang: the HTTP answer, and with it the panel's busy
|
|
1512
|
+
* flag, stayed open for `connectTimeoutMs`. The pass runs in the background,
|
|
1513
|
+
* and the panel watches its outcome on the status channel.
|
|
1514
|
+
* @param projectRoot - restricts the pass to one project's sessions.
|
|
1515
|
+
*/
|
|
1516
|
+
syncSoon(projectRoot?: string): void {
|
|
1517
|
+
this.kick(projectRoot)
|
|
1518
|
+
}
|
|
1519
|
+
|
|
1520
|
+
/**
|
|
1521
|
+
* Queue the operator pass without awaiting it, containing a rejection the way
|
|
1522
|
+
* every other background pass does: by the time either operator route
|
|
1523
|
+
* answers, the pass is nobody's request to wait for.
|
|
1524
|
+
* @param projectRoot - restricts the pass to one project's sessions.
|
|
1525
|
+
*/
|
|
1526
|
+
private kick(projectRoot: string | undefined): void {
|
|
1527
|
+
void this.enqueue(this.requestsFor(projectRoot)).catch((error: unknown) => {
|
|
1528
|
+
this.ctx.logger.warn(`project-mcp: operator pass failed: ${errorText(error)}`)
|
|
1529
|
+
})
|
|
1530
|
+
}
|
|
1531
|
+
|
|
1532
|
+
/**
|
|
1533
|
+
* The sessions one operator pass may mount: every listed one, or the sessions
|
|
1534
|
+
* of a single project when the call came from a surface that shows one. The
|
|
1535
|
+
* project is named, not resolved here: {@link syncAgent} matches it against
|
|
1536
|
+
* each session's own working directory, so the very first operator call for a
|
|
1537
|
+
* session reaches the project it named.
|
|
1538
|
+
* @param projectRoot - the project the caller named, when it named one.
|
|
1539
|
+
* @returns the request the pass takes.
|
|
1540
|
+
*/
|
|
1541
|
+
private requestsFor(projectRoot: string | undefined): PassRequests {
|
|
1542
|
+
return projectRoot === undefined ? 'all' : { projectRoot }
|
|
1543
|
+
}
|
|
1544
|
+
|
|
1545
|
+
/** Queue one pass behind whatever is already running. */
|
|
1546
|
+
private enqueue(requests: PassRequests): Promise<void> {
|
|
1547
|
+
this.chain = this.chain.then(
|
|
1548
|
+
() => this.runPass(requests),
|
|
1549
|
+
() => this.runPass(requests),
|
|
1550
|
+
)
|
|
1551
|
+
return this.chain
|
|
1552
|
+
}
|
|
1553
|
+
|
|
1554
|
+
/**
|
|
1555
|
+
* Drop the mounts currently in an `error` state and ask for a pass that mounts
|
|
1556
|
+
* them again, so a server that was fixed outside the plugin is picked up
|
|
1557
|
+
* without editing its declaration. A stalled mount is restarted from scratch.
|
|
1558
|
+
*
|
|
1559
|
+
* The drop is awaited — it is local and quick, and the answer the route sends
|
|
1560
|
+
* back must already show those rows as unmounted rather than failed. The pass
|
|
1561
|
+
* is not: a server that boots slowly would otherwise hold the `POST retry`
|
|
1562
|
+
* answer open for `connectTimeoutMs`, which the panel showed as a hang. A
|
|
1563
|
+
* `projectRoot` keeps both the drop and the pass inside that one project, so
|
|
1564
|
+
* retrying a row never starts a server for another one.
|
|
1565
|
+
*
|
|
1566
|
+
* The drop is per project: one failed instance is shared by every session of
|
|
1567
|
+
* its project, so retrying it must not try to unmount it once per session.
|
|
1568
|
+
* @param projectRoot - restricts the drop and the pass to one project.
|
|
1569
|
+
*/
|
|
1570
|
+
async retry(projectRoot?: string): Promise<void> {
|
|
1571
|
+
// Every instance a session renders lives in its project's shared home — one
|
|
1572
|
+
// home per project, bridged or joined — so the project records are the whole
|
|
1573
|
+
// list of homes a retry has to walk.
|
|
1574
|
+
const homes: MountHome[] = [...this.projects.values()]
|
|
1575
|
+
for (const home of homes) {
|
|
1576
|
+
if (projectRoot !== undefined && home.projectRoot !== projectRoot) continue
|
|
1577
|
+
let dropped = false
|
|
1578
|
+
for (const [name, mount] of [...home.mounts]) {
|
|
1579
|
+
if (mount.status !== 'error') continue
|
|
1580
|
+
await this.unmount(home, name, { code: 'unmount.reason.operatorRetry', text: 'an operator retry replaces it' })
|
|
1581
|
+
dropped = true
|
|
1582
|
+
}
|
|
1583
|
+
// The documents are unchanged, so the pass below would take its steady
|
|
1584
|
+
// state shortcut — the dropped mount is exactly why it must not. Every
|
|
1585
|
+
// session that renders this home's rows must rebuild them. (A lazy
|
|
1586
|
+
// declaration that was never mounted needs no nudge: the operator pass
|
|
1587
|
+
// mounts it by itself, see the merge pass.)
|
|
1588
|
+
if (!dropped) continue
|
|
1589
|
+
for (const state of this.states.values()) {
|
|
1590
|
+
if (state.projectRoot === home.projectRoot) state.digest = undefined
|
|
1591
|
+
}
|
|
1592
|
+
}
|
|
1593
|
+
// The rows the drop just freed are visible now; the pass that mounts them
|
|
1594
|
+
// again reports for itself, one mount at a time.
|
|
1595
|
+
this.notify()
|
|
1596
|
+
this.kick(projectRoot)
|
|
1597
|
+
}
|
|
1598
|
+
|
|
1599
|
+
/** Dispose every mount, scope, watcher and timer owned by this runtime. */
|
|
1600
|
+
async disposeAll(): Promise<void> {
|
|
1601
|
+
this.disposed = true
|
|
1602
|
+
if (this.timer !== undefined) clearInterval(this.timer)
|
|
1603
|
+
if (this.debounce !== undefined) clearTimeout(this.debounce)
|
|
1604
|
+
this.timer = undefined
|
|
1605
|
+
this.debounce = undefined
|
|
1606
|
+
for (const watchers of this.watchers.values()) {
|
|
1607
|
+
for (const watcher of watchers) watcher.close()
|
|
1608
|
+
}
|
|
1609
|
+
this.watchers.clear()
|
|
1610
|
+
this.watchedDirs.clear()
|
|
1611
|
+
this.watchedRoots.clear()
|
|
1612
|
+
const states = [...this.states.values()]
|
|
1613
|
+
this.states.clear()
|
|
1614
|
+
this.documents.clear()
|
|
1615
|
+
this.secrets = undefined
|
|
1616
|
+
this.envFiles.clear()
|
|
1617
|
+
// Sessions first — each hands its hold back — then whatever no session names
|
|
1618
|
+
// any more, so a shared project is released exactly once either way.
|
|
1619
|
+
await Promise.all(states.map((state) => this.disposeState(state, { code: 'unmount.reason.unloading', text: 'the plugin is unloading' })))
|
|
1620
|
+
for (const project of [...this.projects.values()]) {
|
|
1621
|
+
await this.releaseProject(project, { code: 'unmount.reason.unloading', text: 'the plugin is unloading' })
|
|
1622
|
+
}
|
|
1623
|
+
this.projects.clear()
|
|
1624
|
+
// Last, so the teardown events above still reach the log: this runtime stops
|
|
1625
|
+
// being a consumer once it has nothing left to report.
|
|
1626
|
+
this.detachLog?.()
|
|
1627
|
+
this.detachLog = undefined
|
|
1628
|
+
}
|
|
1629
|
+
|
|
1630
|
+
private newState(agent: AgentLike): AgentState {
|
|
1631
|
+
return {
|
|
1632
|
+
agent,
|
|
1633
|
+
cwd: agent.session.header?.cwd,
|
|
1634
|
+
projectRoot: undefined,
|
|
1635
|
+
digest: undefined,
|
|
1636
|
+
scope: undefined,
|
|
1637
|
+
project: undefined,
|
|
1638
|
+
bridge: undefined,
|
|
1639
|
+
parentLinked: false,
|
|
1640
|
+
detachedKey: undefined,
|
|
1641
|
+
rows: [],
|
|
1642
|
+
issues: [],
|
|
1643
|
+
conflicts: [],
|
|
1644
|
+
lastActivityAt: undefined,
|
|
1645
|
+
busy: false,
|
|
1646
|
+
activationPending: false,
|
|
1647
|
+
activation: undefined,
|
|
1648
|
+
step: 0,
|
|
1649
|
+
steps: new Map(),
|
|
1650
|
+
activationDispose: undefined,
|
|
1651
|
+
guidanceDispose: undefined,
|
|
1652
|
+
auto: undefined,
|
|
1653
|
+
}
|
|
1654
|
+
}
|
|
1655
|
+
|
|
1656
|
+
private dropAgent(id: string): void {
|
|
1657
|
+
const state = this.states.get(id)
|
|
1658
|
+
this.states.delete(id)
|
|
1659
|
+
if (state !== undefined) void this.disposeState(state, { code: 'unmount.reason.sessionGone', text: 'the session went away' })
|
|
1660
|
+
this.sweepProjects()
|
|
1661
|
+
this.syncWatchers()
|
|
1662
|
+
this.notify()
|
|
1663
|
+
}
|
|
1664
|
+
|
|
1665
|
+
/**
|
|
1666
|
+
* Release the sessions the host registry no longer lists.
|
|
1667
|
+
*
|
|
1668
|
+
* A finished or abandoned session produces no further event — no
|
|
1669
|
+
* `agent/status`, no `idle` transition to clear the busy flag, nothing for
|
|
1670
|
+
* the idle sweep to time out from. The pass is the path that exists: whatever
|
|
1671
|
+
* the registry still lists is live, and anything else hands its servers back
|
|
1672
|
+
* here, even with the idle sweep disabled.
|
|
1673
|
+
*/
|
|
1674
|
+
private async releaseAbandoned(): Promise<void> {
|
|
1675
|
+
const listed = this.listAgents?.()
|
|
1676
|
+
if (listed === undefined) return
|
|
1677
|
+
const live = new Set(listed.map((agent) => agent.id))
|
|
1678
|
+
for (const id of [...this.states.keys()]) {
|
|
1679
|
+
if (live.has(id)) continue
|
|
1680
|
+
const state = this.states.get(id)
|
|
1681
|
+
this.states.delete(id)
|
|
1682
|
+
if (state !== undefined) await this.disposeState(state, { code: 'unmount.reason.sessionUnlisted', text: 'the registry no longer lists the session' })
|
|
1683
|
+
}
|
|
1684
|
+
}
|
|
1685
|
+
|
|
1686
|
+
/**
|
|
1687
|
+
* Whether one session is running a turn right now.
|
|
1688
|
+
*
|
|
1689
|
+
* The host's own status wins where it publishes one: `busy` only ever
|
|
1690
|
+
* reflects the events this plugin happened to see, so a session whose `idle`
|
|
1691
|
+
* transition never arrives would pin its mounts forever behind a stale flag.
|
|
1692
|
+
* @param state - the session to judge.
|
|
1693
|
+
* @returns true while the session must keep its mounts unconditionally.
|
|
1694
|
+
*/
|
|
1695
|
+
private working(state: AgentState): boolean {
|
|
1696
|
+
const live = state.agent.status
|
|
1697
|
+
return live === undefined ? state.busy : live === 'running'
|
|
1698
|
+
}
|
|
1699
|
+
|
|
1700
|
+
/**
|
|
1701
|
+
* Forget everything one session presented. The session's project is gone with
|
|
1702
|
+
* the scope (or the session is over), so a baseline seeded from that project's
|
|
1703
|
+
* counters must not leak into a different one. An idle release goes through
|
|
1704
|
+
* `releaseMounts`, not here.
|
|
1705
|
+
*
|
|
1706
|
+
* The hold on the old project's shared servers is given back here too: a
|
|
1707
|
+
* session that moves to another project — or disappears — must not keep the
|
|
1708
|
+
* project it left running for nobody.
|
|
1709
|
+
* @param state - the session state to clear.
|
|
1710
|
+
*/
|
|
1711
|
+
private async disposeState(state: AgentState, reason: CodedText): Promise<void> {
|
|
1712
|
+
state.digest = undefined
|
|
1713
|
+
state.rows = []
|
|
1714
|
+
state.issues = []
|
|
1715
|
+
state.activation = undefined
|
|
1716
|
+
state.auto = undefined
|
|
1717
|
+
await this.detach(state, reason)
|
|
1718
|
+
}
|
|
1719
|
+
|
|
1720
|
+
/**
|
|
1721
|
+
* Take one session's hold on a project: link its scope key to the project's
|
|
1722
|
+
* so the shared layer resolves for it, or install the forwarding bridge when
|
|
1723
|
+
* that link is impossible, then mint its own scope and install the session
|
|
1724
|
+
* wiring on it. Idempotent while the hold is unchanged.
|
|
1725
|
+
*
|
|
1726
|
+
* The link comes first because it is what makes the project's already-running
|
|
1727
|
+
* servers visible to this session from its first request on. A key the
|
|
1728
|
+
* harness already parented cannot be linked again — `dsh-scope` binds a key
|
|
1729
|
+
* once, and the agent-preset roster binds every composed agent to its
|
|
1730
|
+
* standing scope before the agent is published — so that session holds the
|
|
1731
|
+
* SAME project home and gets a forwarding bridge instead: thin definitions in
|
|
1732
|
+
* its own layer whose calls run the project's one instance (`src/bridge.ts`).
|
|
1733
|
+
* One process per project is the whole point; the alternative was one process
|
|
1734
|
+
* per session, which is what the panel showed in the web GUI.
|
|
1735
|
+
* @param state - the session taking the hold.
|
|
1736
|
+
* @param project - the project whose mounts it shares.
|
|
1737
|
+
* @returns the home the session now holds.
|
|
1738
|
+
*/
|
|
1739
|
+
private async holdProject(state: AgentState, project: ProjectState): Promise<MountHome> {
|
|
1740
|
+
const held = this.homeOf(state)
|
|
1741
|
+
if (held !== undefined && held.projectRoot === project.projectRoot) return held
|
|
1742
|
+
if (held !== undefined) await this.detach(state, { code: 'unmount.reason.sessionMoved', text: 'the session moved to another project' })
|
|
1743
|
+
// The session's own layer key is private to this session, so the link either
|
|
1744
|
+
// succeeds (this runtime just bound it, or owns the binding) or another
|
|
1745
|
+
// composition already parented that key — a foreign hold this runtime must
|
|
1746
|
+
// not move. The session still holds the project — the servers run once for
|
|
1747
|
+
// the whole project — and the bridge carries their tools into this session's
|
|
1748
|
+
// own layer, where the registry resolves them for exactly this key.
|
|
1749
|
+
state.parentLinked = linkScopeParent(state.agent, project.key)
|
|
1750
|
+
if (!state.parentLinked) {
|
|
1751
|
+
this.ctx.logger.debug?.(
|
|
1752
|
+
`project-mcp: session ${state.agent.id} keeps a foreign scope parent, so its tools are forwarded from ${project.projectRoot}`,
|
|
1753
|
+
)
|
|
1754
|
+
}
|
|
1755
|
+
state.project = project
|
|
1756
|
+
const home: MountHome = project
|
|
1757
|
+
this.ensureSessionScope(state.agent, state)
|
|
1758
|
+
if (state.parentLinked) this.dropBridge(state)
|
|
1759
|
+
else this.installBridge(state, project)
|
|
1760
|
+
return home
|
|
1761
|
+
}
|
|
1762
|
+
|
|
1763
|
+
/**
|
|
1764
|
+
* Give one session's hold back. Its own scope and wiring go away, its scope
|
|
1765
|
+
* key is unlinked from the project so the shared servers stop resolving for
|
|
1766
|
+
* it, and the project's instance is released exactly when this was the last
|
|
1767
|
+
* holder — a session that goes idle or leaves while another one still works
|
|
1768
|
+
* must not stop the servers that one is using.
|
|
1769
|
+
* @param state - the session releasing its hold.
|
|
1770
|
+
* @param reason - why the hold is going back; every instance this drops is
|
|
1771
|
+
* logged with it, so the log says why a server stopped, not only that it did.
|
|
1772
|
+
*/
|
|
1773
|
+
private async detach(state: AgentState, reason: CodedText): Promise<void> {
|
|
1774
|
+
const project = state.project
|
|
1775
|
+
state.project = undefined
|
|
1776
|
+
this.dropBridge(state)
|
|
1777
|
+
if (project !== undefined && state.parentLinked) {
|
|
1778
|
+
state.parentLinked = false
|
|
1779
|
+
state.detachedKey ??= {}
|
|
1780
|
+
if (!linkScopeParent(state.agent, state.detachedKey)) {
|
|
1781
|
+
this.ctx.logger.warn(
|
|
1782
|
+
`project-mcp: unlinking session ${state.agent.id} from its project failed: its session key is held by another composition`,
|
|
1783
|
+
)
|
|
1784
|
+
}
|
|
1785
|
+
}
|
|
1786
|
+
await this.disposeSessionScope(state, reason)
|
|
1787
|
+
if (project !== undefined && !this.hasHolders(project)) await this.releaseProject(project, reason)
|
|
1788
|
+
}
|
|
1789
|
+
|
|
1790
|
+
/** Drop the session scope and the wiring installed on it. Idempotent. */
|
|
1791
|
+
private async disposeSessionScope(state: AgentState, reason: CodedText): Promise<void> {
|
|
1792
|
+
const scope = state.scope
|
|
1793
|
+
state.scope = undefined
|
|
1794
|
+
this.releaseWiring(state)
|
|
1795
|
+
if (scope === undefined) return
|
|
1796
|
+
try {
|
|
1797
|
+
await scope.dispose()
|
|
1798
|
+
} catch (error) {
|
|
1799
|
+
this.ctx.logger.warn(`project-mcp: disposing session scope failed: ${errorText(error)}`)
|
|
1800
|
+
}
|
|
1801
|
+
}
|
|
1802
|
+
|
|
1803
|
+
/**
|
|
1804
|
+
* Whether any live session still holds one project's shared mounts.
|
|
1805
|
+
* @param project - the project to look for.
|
|
1806
|
+
* @returns `true` while at least one session keeps the instance alive.
|
|
1807
|
+
*/
|
|
1808
|
+
private hasHolders(project: ProjectState): boolean {
|
|
1809
|
+
for (const state of this.states.values()) {
|
|
1810
|
+
if (state.project === project) return true
|
|
1811
|
+
}
|
|
1812
|
+
return false
|
|
1813
|
+
}
|
|
1814
|
+
|
|
1815
|
+
/**
|
|
1816
|
+
* Release one project's shared servers and the scope that owns them.
|
|
1817
|
+
*
|
|
1818
|
+
* Runs when the project's last holder lets go, so a shared instance goes away
|
|
1819
|
+
* on exactly the trigger a per-session one did: the project's last session
|
|
1820
|
+
* releasing it (idle release, request, disposal, a move to another project, or
|
|
1821
|
+
* a declaration that mounts nothing any more). Idempotent.
|
|
1822
|
+
* @param project - the project to tear down.
|
|
1823
|
+
*/
|
|
1824
|
+
private async releaseProject(project: ProjectState, reason: CodedText): Promise<void> {
|
|
1825
|
+
for (const name of [...project.mounts.keys()]) await this.unmount(project, name, reason)
|
|
1826
|
+
const scope = project.scope
|
|
1827
|
+
project.scope = undefined
|
|
1828
|
+
if (scope !== undefined) {
|
|
1829
|
+
try {
|
|
1830
|
+
await scope.dispose()
|
|
1831
|
+
} catch (error) {
|
|
1832
|
+
this.ctx.logger.warn(
|
|
1833
|
+
`project-mcp: disposing the shared scope of ${project.projectRoot} failed: ${errorText(error)}`,
|
|
1834
|
+
)
|
|
1835
|
+
}
|
|
1836
|
+
}
|
|
1837
|
+
// The record itself stays while a session is still bound to this root: a
|
|
1838
|
+
// pass mounting concurrently (a session disposed while another one turns)
|
|
1839
|
+
// would otherwise create a second record — and a second instance — for one
|
|
1840
|
+
// root. `sweepProjects` forgets it once nothing is bound any more.
|
|
1841
|
+
this.sweepProjects()
|
|
1842
|
+
}
|
|
1843
|
+
|
|
1844
|
+
/**
|
|
1845
|
+
* Forget the project records no live session is bound to any more. A record
|
|
1846
|
+
* with mounts or a scope is never dropped: either one means someone still
|
|
1847
|
+
* holds the project.
|
|
1848
|
+
*/
|
|
1849
|
+
private sweepProjects(): void {
|
|
1850
|
+
for (const [projectRoot, project] of this.projects) {
|
|
1851
|
+
if (project.scope !== undefined || project.mounts.size > 0) continue
|
|
1852
|
+
if (this.hasRootSessions(projectRoot)) continue
|
|
1853
|
+
this.projects.delete(projectRoot)
|
|
1854
|
+
}
|
|
1855
|
+
}
|
|
1856
|
+
|
|
1857
|
+
/** Whether any live session resolved its working directory to one root. */
|
|
1858
|
+
private hasRootSessions(projectRoot: string): boolean {
|
|
1859
|
+
for (const state of this.states.values()) {
|
|
1860
|
+
if (state.projectRoot === projectRoot) return true
|
|
1861
|
+
}
|
|
1862
|
+
return false
|
|
1863
|
+
}
|
|
1864
|
+
|
|
1865
|
+
/**
|
|
1866
|
+
* The project record one root's sessions share, created with its first holder
|
|
1867
|
+
* and forgotten when its last one lets go.
|
|
1868
|
+
* @param projectRoot - resolved project root.
|
|
1869
|
+
* @returns the live record.
|
|
1870
|
+
*/
|
|
1871
|
+
private ensureProject(projectRoot: string): ProjectState {
|
|
1872
|
+
const existing = this.projects.get(projectRoot)
|
|
1873
|
+
if (existing !== undefined) return existing
|
|
1874
|
+
const project: ProjectState = {
|
|
1875
|
+
projectRoot,
|
|
1876
|
+
key: { projectRoot },
|
|
1877
|
+
scope: undefined,
|
|
1878
|
+
mounts: new Map(),
|
|
1879
|
+
shared: true,
|
|
1880
|
+
}
|
|
1881
|
+
this.projects.set(projectRoot, project)
|
|
1882
|
+
return project
|
|
1883
|
+
}
|
|
1884
|
+
|
|
1885
|
+
/**
|
|
1886
|
+
* The home one session mounts in: the project it holds, bridged or joined.
|
|
1887
|
+
* `undefined` while it holds nothing.
|
|
1888
|
+
* @param state - the session to read.
|
|
1889
|
+
* @returns the session's mount home, or `undefined` when it holds none.
|
|
1890
|
+
*/
|
|
1891
|
+
private homeOf(state: AgentState): MountHome | undefined {
|
|
1892
|
+
return state.project
|
|
1893
|
+
}
|
|
1894
|
+
|
|
1895
|
+
/**
|
|
1896
|
+
* The mounts one session renders right now: its own home's when it has one for
|
|
1897
|
+
* this root, otherwise the project's shared set, so a session that holds
|
|
1898
|
+
* nothing still notices another session's mounts and re-renders its rows.
|
|
1899
|
+
* @param state - the session to read.
|
|
1900
|
+
* @param projectRoot - the project root the pass is reconciling.
|
|
1901
|
+
* @returns the mount map whose changes this session's digest tracks.
|
|
1902
|
+
*/
|
|
1903
|
+
private visibleMounts(state: AgentState, projectRoot: string): ReadonlyMap<string, MountedInstance> {
|
|
1904
|
+
const home = this.homeOf(state)
|
|
1905
|
+
if (home !== undefined && home.projectRoot === projectRoot) return home.mounts
|
|
1906
|
+
return this.projects.get(projectRoot)?.mounts ?? NO_MOUNTS
|
|
1907
|
+
}
|
|
1908
|
+
|
|
1909
|
+
/**
|
|
1910
|
+
* The live mounts one session currently holds. Empty for a session that holds
|
|
1911
|
+
* nothing: the servers run for their project, and only a holder shares them.
|
|
1912
|
+
* @param state - the session to read.
|
|
1913
|
+
* @returns the shared mount map, or a shared empty one.
|
|
1914
|
+
*/
|
|
1915
|
+
private mountsOf(state: AgentState): ReadonlyMap<string, MountedInstance> {
|
|
1916
|
+
return this.homeOf(state)?.mounts ?? NO_MOUNTS
|
|
1917
|
+
}
|
|
1918
|
+
|
|
1919
|
+
/**
|
|
1920
|
+
* The `serverName` every one of the session's mounts registers under.
|
|
1921
|
+
*
|
|
1922
|
+
* The registry — and every name it publishes — is keyed by this, not by the
|
|
1923
|
+
* declared name: a shadowed declaration registers as its local alias, and a
|
|
1924
|
+
* lookup by the contested name would read as "this project mounts nothing".
|
|
1925
|
+
* @param state - the session to read.
|
|
1926
|
+
* @returns the runtime names, one per live mount.
|
|
1927
|
+
*/
|
|
1928
|
+
private runtimeNamesOf(state: AgentState): Set<string> {
|
|
1929
|
+
return new Set([...this.mountsOf(state).values()].map((mount) => mount.runtimeName))
|
|
1930
|
+
}
|
|
1931
|
+
|
|
1932
|
+
/**
|
|
1933
|
+
* Unregister everything the current scope's session wiring installed. The
|
|
1934
|
+
* scope fiber disposes the same registrations with the real services, while a
|
|
1935
|
+
* host that publishes plain `systemPrompt`/`tools` stubs has only this path.
|
|
1936
|
+
* Idempotent.
|
|
1937
|
+
*/
|
|
1938
|
+
private releaseWiring(state: AgentState): void {
|
|
1939
|
+
this.releaseGuidance(state)
|
|
1940
|
+
this.releaseActivation(state)
|
|
1941
|
+
}
|
|
1942
|
+
|
|
1943
|
+
/**
|
|
1944
|
+
* Unregister the guidance section of the current scope, if one is installed.
|
|
1945
|
+
* Released exactly where the scope is — an idle release and agent disposal —
|
|
1946
|
+
* so no section ever describes mounts that are gone.
|
|
1947
|
+
*/
|
|
1948
|
+
private releaseGuidance(state: AgentState): void {
|
|
1949
|
+
const dispose = state.guidanceDispose
|
|
1950
|
+
state.guidanceDispose = undefined
|
|
1951
|
+
if (dispose === undefined) return
|
|
1952
|
+
try {
|
|
1953
|
+
dispose()
|
|
1954
|
+
} catch (error) {
|
|
1955
|
+
this.ctx.logger.warn(
|
|
1956
|
+
`project-mcp: releasing guidance for session ${state.agent.id} failed: ${errorText(error)}`,
|
|
1957
|
+
)
|
|
1958
|
+
}
|
|
1959
|
+
}
|
|
1960
|
+
|
|
1961
|
+
/**
|
|
1962
|
+
* Unregister the activation wiring of the current scope. Idempotent: the
|
|
1963
|
+
* scope fiber disposes the same registrations with the real registry, while a
|
|
1964
|
+
* host that publishes a plain `tools` stub has only this path.
|
|
1965
|
+
*/
|
|
1966
|
+
private releaseActivation(state: AgentState): void {
|
|
1967
|
+
const dispose = state.activationDispose
|
|
1968
|
+
state.activationDispose = undefined
|
|
1969
|
+
if (dispose === undefined) return
|
|
1970
|
+
try {
|
|
1971
|
+
dispose()
|
|
1972
|
+
} catch (error) {
|
|
1973
|
+
this.ctx.logger.warn(
|
|
1974
|
+
`project-mcp: releasing activation for session ${state.agent.id} failed: ${errorText(error)}`,
|
|
1975
|
+
)
|
|
1976
|
+
}
|
|
1977
|
+
}
|
|
1978
|
+
|
|
1979
|
+
/**
|
|
1980
|
+
* Ask for a pass. A pending pass is kept instead of being pushed back: the
|
|
1981
|
+
* rescan tick is often shorter than the debounce, and restarting the timer on
|
|
1982
|
+
* every tick would starve reconciliation forever. Bursts of watcher events
|
|
1983
|
+
* still collapse into the one queued pass, and each pass re-reads the
|
|
1984
|
+
* documents through the digest, so a late event costs one cheap pass.
|
|
1985
|
+
*/
|
|
1986
|
+
private schedule(reason: string): void {
|
|
1987
|
+
if (this.disposed) return
|
|
1988
|
+
this.ctx.logger.debug?.(`project-mcp: sync scheduled (${reason})`)
|
|
1989
|
+
if (this.debounce !== undefined) return
|
|
1990
|
+
this.debounce = setTimeout(() => {
|
|
1991
|
+
this.debounce = undefined
|
|
1992
|
+
void this.enqueue(NO_REQUESTS)
|
|
1993
|
+
}, this.config.debounceMs)
|
|
1994
|
+
this.debounce.unref?.()
|
|
1995
|
+
}
|
|
1996
|
+
|
|
1997
|
+
/**
|
|
1998
|
+
* Turn boundary. `running` is the moment a session becomes active, which is
|
|
1999
|
+
* what `lazy` waits for; `idle` closes the busy window that idle release
|
|
2000
|
+
* watches. A plain notification, so it never delays a turn.
|
|
2001
|
+
*/
|
|
2002
|
+
private onStatus(event: AgentEventLike): void {
|
|
2003
|
+
if (this.disposed) return
|
|
2004
|
+
const state = this.states.get(event.agent.id)
|
|
2005
|
+
if (state === undefined) return
|
|
2006
|
+
// Both transitions are an activity boundary: a tool that has not been called
|
|
2007
|
+
// for `toolIdleMs` falls out here, before the turn that follows can see it.
|
|
2008
|
+
this.pruneActivation(state)
|
|
2009
|
+
if (event.status === 'running') {
|
|
2010
|
+
this.touch(state, { activate: true, busy: true })
|
|
2011
|
+
return
|
|
2012
|
+
}
|
|
2013
|
+
this.touch(state, { activate: false, busy: false })
|
|
2014
|
+
}
|
|
2015
|
+
|
|
2016
|
+
/**
|
|
2017
|
+
* Before every step of a turn: keep this session's project mounted, waiting
|
|
2018
|
+
* for a pending activation so that the step's request already sees the
|
|
2019
|
+
* project's tools. The waterfall always continues — a project MCP server is
|
|
2020
|
+
* never a reason to hold up an agent step.
|
|
2021
|
+
*/
|
|
2022
|
+
private async onPreStep(event: AgentEventLike, next: () => Promise<unknown>): Promise<unknown> {
|
|
2023
|
+
try {
|
|
2024
|
+
const state = this.states.get(event.agent.id)
|
|
2025
|
+
if (state !== undefined) {
|
|
2026
|
+
// This hook is the harness's own step boundary, so it is where the
|
|
2027
|
+
// per-session counter advances: an activation made during this step,
|
|
2028
|
+
// and the row a panel reads after it, both carry the number of the step
|
|
2029
|
+
// they belong to instead of a placeholder.
|
|
2030
|
+
state.step += 1
|
|
2031
|
+
if (!this.disposed) {
|
|
2032
|
+
this.touch(state, { activate: true })
|
|
2033
|
+
await this.awaitActivation(state)
|
|
2034
|
+
}
|
|
2035
|
+
}
|
|
2036
|
+
} catch (error) {
|
|
2037
|
+
this.ctx.logger.warn(`project-mcp: activation before a step failed: ${errorText(error)}`)
|
|
2038
|
+
}
|
|
2039
|
+
return next()
|
|
2040
|
+
}
|
|
2041
|
+
|
|
2042
|
+
/** Record activity and, with nothing mounted, ask for an activation pass. */
|
|
2043
|
+
private touch(state: AgentState, options: { activate: boolean; busy?: boolean }): void {
|
|
2044
|
+
state.lastActivityAt = Date.now()
|
|
2045
|
+
if (options.busy !== undefined) state.busy = options.busy
|
|
2046
|
+
if (!options.activate || this.mountsOf(state).size > 0) return
|
|
2047
|
+
state.activationPending = true
|
|
2048
|
+
this.schedule('activity')
|
|
2049
|
+
}
|
|
2050
|
+
|
|
2051
|
+
/**
|
|
2052
|
+
* Wait (bounded) for the activation pass a turn asked for.
|
|
2053
|
+
*
|
|
2054
|
+
* The pass carries no operator request on purpose: the caller's
|
|
2055
|
+
* `activationPending` is what entitles this session to mount, and leaving the
|
|
2056
|
+
* request empty is what keeps the pass from starting servers in every other
|
|
2057
|
+
* project whose sessions happen to be live.
|
|
2058
|
+
*/
|
|
2059
|
+
private async awaitActivation(state: AgentState): Promise<void> {
|
|
2060
|
+
if (!state.activationPending) return
|
|
2061
|
+
const pass = this.enqueue(NO_REQUESTS).catch(() => undefined)
|
|
2062
|
+
const waitMs = this.config.activationWaitMs
|
|
2063
|
+
if (waitMs <= 0) return
|
|
2064
|
+
await Promise.race([pass, delay(waitMs)])
|
|
2065
|
+
}
|
|
2066
|
+
|
|
2067
|
+
/**
|
|
2068
|
+
* Reconcile every known session once, then the sweep and the watchers.
|
|
2069
|
+
* @param requests - the sessions that may mount without their own turn asking.
|
|
2070
|
+
*/
|
|
2071
|
+
private async runPass(requests: PassRequests): Promise<void> {
|
|
2072
|
+
if (this.disposed) return
|
|
2073
|
+
// A session the host no longer lists is finished: no later event will ever
|
|
2074
|
+
// report it, so this pass is the path that hands its mounts back.
|
|
2075
|
+
await this.releaseAbandoned()
|
|
2076
|
+
// Sessions are independent: one slow connect must not serialize the rest.
|
|
2077
|
+
await Promise.all(
|
|
2078
|
+
[...this.states.values()].map(async (state) => {
|
|
2079
|
+
try {
|
|
2080
|
+
await this.syncAgent(state, requests)
|
|
2081
|
+
} catch (error) {
|
|
2082
|
+
this.ctx.logger.warn(
|
|
2083
|
+
`project-mcp: sync failed for session ${state.agent.id}: ${errorText(error)}`,
|
|
2084
|
+
)
|
|
2085
|
+
}
|
|
2086
|
+
}),
|
|
2087
|
+
)
|
|
2088
|
+
await this.evictIdle()
|
|
2089
|
+
this.sweepProjects()
|
|
2090
|
+
this.syncWatchers()
|
|
2091
|
+
this.notify()
|
|
2092
|
+
}
|
|
2093
|
+
|
|
2094
|
+
/**
|
|
2095
|
+
* Release the mounts of sessions that have been quiet for `idleTimeoutMs`.
|
|
2096
|
+
* Their rows stay visible as `idle`, so the project's declaration remains
|
|
2097
|
+
* discoverable while not a single child process is running for it.
|
|
2098
|
+
*/
|
|
2099
|
+
private async evictIdle(): Promise<void> {
|
|
2100
|
+
const timeout = this.config.idleTimeoutMs
|
|
2101
|
+
if (timeout <= 0) return
|
|
2102
|
+
const now = Date.now()
|
|
2103
|
+
for (const state of [...this.states.values()]) {
|
|
2104
|
+
if (this.mountsOf(state).size === 0 || this.working(state)) continue
|
|
2105
|
+
const since = state.lastActivityAt
|
|
2106
|
+
if (since === undefined || now - since < timeout) continue
|
|
2107
|
+
await this.releaseMounts(
|
|
2108
|
+
state,
|
|
2109
|
+
(count) => ({
|
|
2110
|
+
code: 'idle.releasedInactive',
|
|
2111
|
+
text: `released after ${formatSeconds(now - since)} without activity — ${count} server(s) stopped; the next turn mounts them again`,
|
|
2112
|
+
params: { seconds: formatSeconds(now - since), count: String(count) },
|
|
2113
|
+
}),
|
|
2114
|
+
{ code: 'unmount.reason.sessionIdle', text: 'the session went idle' },
|
|
2115
|
+
)
|
|
2116
|
+
}
|
|
2117
|
+
}
|
|
2118
|
+
|
|
2119
|
+
/**
|
|
2120
|
+
* Give one session's servers back now, or every mounted session's when no id
|
|
2121
|
+
* is given. Drives the panel's "release" action; the rows stay as `idle` and
|
|
2122
|
+
* the next turn mounts them again. A session that releases the last hold on a
|
|
2123
|
+
* project takes the shared instance down with it, and one that releases while
|
|
2124
|
+
* another session of the project holds leaves it running for that session.
|
|
2125
|
+
*/
|
|
2126
|
+
async release(agentId?: string): Promise<void> {
|
|
2127
|
+
for (const state of [...this.states.values()]) {
|
|
2128
|
+
if (agentId !== undefined && state.agent.id !== agentId) continue
|
|
2129
|
+
if (this.mountsOf(state).size === 0) continue
|
|
2130
|
+
await this.releaseMounts(
|
|
2131
|
+
state,
|
|
2132
|
+
(count) => ({
|
|
2133
|
+
code: 'idle.releasedRequest',
|
|
2134
|
+
text: `released on request — ${count} server(s) stopped; the next turn mounts them again`,
|
|
2135
|
+
params: { count: String(count) },
|
|
2136
|
+
}),
|
|
2137
|
+
{ code: 'unmount.reason.operatorReleased', text: 'an operator released it' },
|
|
2138
|
+
)
|
|
2139
|
+
}
|
|
2140
|
+
this.notify()
|
|
2141
|
+
}
|
|
2142
|
+
|
|
2143
|
+
/**
|
|
2144
|
+
* Give one session's hold back, keeping its rows as `idle`.
|
|
2145
|
+
*
|
|
2146
|
+
* The shared servers themselves follow the last holder: this detaches the
|
|
2147
|
+
* session (its scope, wiring and parent link) and releases the project only
|
|
2148
|
+
* when no other session holds it, so releasing one session of a project that
|
|
2149
|
+
* another session is still working in leaves that session's servers running.
|
|
2150
|
+
* @param state - the session releasing.
|
|
2151
|
+
* @param describe - reason for its rows, given the number of servers it held.
|
|
2152
|
+
*/
|
|
2153
|
+
private async releaseMounts(
|
|
2154
|
+
state: AgentState,
|
|
2155
|
+
describe: (count: number) => CodedText,
|
|
2156
|
+
reason: CodedText,
|
|
2157
|
+
): Promise<void> {
|
|
2158
|
+
const held = this.homeOf(state)
|
|
2159
|
+
const mounted = new Set(held === undefined ? [] : held.mounts.keys())
|
|
2160
|
+
const diagnostics = new Set(
|
|
2161
|
+
[...(held?.mounts.values() ?? [])].flatMap((mount) =>
|
|
2162
|
+
mount.detail === undefined ? [] : [mount.detail],
|
|
2163
|
+
),
|
|
2164
|
+
)
|
|
2165
|
+
state.activationPending = false
|
|
2166
|
+
state.busy = false
|
|
2167
|
+
await this.detach(state, reason)
|
|
2168
|
+
const summary = describe(mounted.size)
|
|
2169
|
+
state.rows = state.rows.map((row) => (mounted.has(row.name) ? idleRow(row, summary) : row))
|
|
2170
|
+
state.issues = state.issues.filter((issue) => !diagnostics.has(issue.message))
|
|
2171
|
+
this.ctx.logger.debug?.(`project-mcp: session ${state.agent.id}: ${summary.text}`)
|
|
2172
|
+
}
|
|
2173
|
+
|
|
2174
|
+
/**
|
|
2175
|
+
* Re-read one agent's project and reconcile its mounts.
|
|
2176
|
+
* @param state - the session to reconcile.
|
|
2177
|
+
* @param operatorRequested - an operator pass named this exact session.
|
|
2178
|
+
*/
|
|
2179
|
+
async syncAgent(state: AgentState, requests: PassRequests = NO_REQUESTS): Promise<void> {
|
|
2180
|
+
const agent = state.agent
|
|
2181
|
+
const cwd = agent.session.header?.cwd
|
|
2182
|
+
state.cwd = cwd
|
|
2183
|
+
const projectRoot =
|
|
2184
|
+
cwd === undefined || cwd === ''
|
|
2185
|
+
? undefined
|
|
2186
|
+
: findProjectRoot(cwd, this.config.projectMarkers, this.config.fileMarkers)
|
|
2187
|
+
// An operator asks for a session directly, or for a project — the second
|
|
2188
|
+
// only matches once the session's own working directory has been read,
|
|
2189
|
+
// which is why it is decided here rather than before the pass.
|
|
2190
|
+
const operatorRequested =
|
|
2191
|
+
requests === 'all' ||
|
|
2192
|
+
('projectRoot' in requests
|
|
2193
|
+
? requests.projectRoot === projectRoot
|
|
2194
|
+
: requests.has(state.agent.id))
|
|
2195
|
+
|
|
2196
|
+
if (projectRoot === undefined) {
|
|
2197
|
+
// The root was just read and none was found. A session's working directory
|
|
2198
|
+
// cannot stop being inside its project without the session changing, so
|
|
2199
|
+
// this is a stale read — a concurrent sweep of the working tree, a temp
|
|
2200
|
+
// directory removed under a test. Either way the session keeps the hold it
|
|
2201
|
+
// has: a release here would tear down live mounts that the next read finds
|
|
2202
|
+
// again, and a session that genuinely has no project holds nothing to
|
|
2203
|
+
// release. A pending first mount still has to be cleared, because no turn
|
|
2204
|
+
// should wait for a pass that has nothing to do.
|
|
2205
|
+
state.activationPending = false
|
|
2206
|
+
return
|
|
2207
|
+
}
|
|
2208
|
+
// A session that moved to another project starts from a clean scope.
|
|
2209
|
+
if (projectRoot !== state.projectRoot) {
|
|
2210
|
+
await this.disposeState(state, { code: 'unmount.reason.sessionMoved', text: 'the session moved to another project' })
|
|
2211
|
+
state.projectRoot = projectRoot
|
|
2212
|
+
}
|
|
2213
|
+
|
|
2214
|
+
const { entries, issues, documents, sources } = this.readProject(projectRoot)
|
|
2215
|
+
const reserved = this.config.profileWins ? this.profileServerNames() : new Set<string>()
|
|
2216
|
+
// The local names this project's shadowed declarations would take, resolved
|
|
2217
|
+
// once for the whole pass: the row, the mount and the conflict report all
|
|
2218
|
+
// read this one answer, so the alias the panel offers is the alias the
|
|
2219
|
+
// registry ends up carrying.
|
|
2220
|
+
const policy = this.policyFor(projectRoot)
|
|
2221
|
+
const aliases = resolveConflictNames({
|
|
2222
|
+
entries: entries.map((entry) => ({ name: entry.name, reserved: reserved.has(entry.name) })),
|
|
2223
|
+
prefix: this.config.localPrefix,
|
|
2224
|
+
projectRoot,
|
|
2225
|
+
})
|
|
2226
|
+
/**
|
|
2227
|
+
* The shadowed names this pass actually mounts, and under which name.
|
|
2228
|
+
*
|
|
2229
|
+
* A name whose user kept the profile's copy is deliberately absent: it is a
|
|
2230
|
+
* conflict report, not a mount. `local` mounts this project's entry under the
|
|
2231
|
+
* alias the panel offers; `native` mounts it under the name it declares,
|
|
2232
|
+
* where it is the nearer declaration for this project's own sessions and so
|
|
2233
|
+
* shadows the profile instance's tools of that name there. The profile
|
|
2234
|
+
* instance itself is never touched: it keeps running, and every other project
|
|
2235
|
+
* keeps resolving it. A `native` entry is therefore mapped to `undefined` and
|
|
2236
|
+
* is still a chosen mount — `has` is the question, never the value.
|
|
2237
|
+
*/
|
|
2238
|
+
const choices = aliasesOf(policy)
|
|
2239
|
+
const chosen = new Map<string, string | undefined>()
|
|
2240
|
+
for (const [name, alias] of aliases) {
|
|
2241
|
+
const choice = choices[name] ?? 'profile'
|
|
2242
|
+
if (choice === 'local') chosen.set(name, alias)
|
|
2243
|
+
else if (choice === 'native') chosen.set(name, undefined)
|
|
2244
|
+
}
|
|
2245
|
+
state.conflicts = conflictsFor(entries, sources, reserved, aliases, policy)
|
|
2246
|
+
|
|
2247
|
+
const rows: ServerRow[] = []
|
|
2248
|
+
const desired = new Map<string, ParsedEntry>()
|
|
2249
|
+
for (const entry of entries) {
|
|
2250
|
+
const base = baseRow(entry, projectRoot, documents.get(entry.source))
|
|
2251
|
+
if (entry.error !== undefined) {
|
|
2252
|
+
rows.push({
|
|
2253
|
+
...base,
|
|
2254
|
+
status: 'error',
|
|
2255
|
+
detail: entry.error,
|
|
2256
|
+
...(entry.errorCode === undefined ? {} : { detailCode: entry.errorCode }),
|
|
2257
|
+
...(entry.errorParams === undefined ? {} : { detailParams: entry.errorParams }),
|
|
2258
|
+
})
|
|
2259
|
+
continue
|
|
2260
|
+
}
|
|
2261
|
+
if (!entry.enabled) {
|
|
2262
|
+
rows.push({ ...base, status: 'disabled', detail: 'declared with enabled: false', detailCode: 'idle.disabled' })
|
|
2263
|
+
continue
|
|
2264
|
+
}
|
|
2265
|
+
if (reserved.has(entry.name)) {
|
|
2266
|
+
const alias = aliases.get(entry.name)
|
|
2267
|
+
// The user chose this project's copy, and the pass has a name to mount it
|
|
2268
|
+
// under: the local alias, or the contested name itself when they opted to
|
|
2269
|
+
// shadow the profile's instance in this project's sessions. Either way the
|
|
2270
|
+
// declaration mounts like any other, and the profile's instance is left
|
|
2271
|
+
// running for every other project.
|
|
2272
|
+
if (chosen.has(entry.name)) {
|
|
2273
|
+
desired.set(entry.name, entry)
|
|
2274
|
+
// The row is `active` and carries no detail of its own: `decorate` drops
|
|
2275
|
+
// a row's detail while it has a mount, so a line explaining the choice
|
|
2276
|
+
// would never reach a surface. The conflict report below is where a
|
|
2277
|
+
// mounted name still says which of the three readings it is.
|
|
2278
|
+
const detail = conflictDetail(entry.name, alias)
|
|
2279
|
+
rows.push({
|
|
2280
|
+
...base,
|
|
2281
|
+
detail: detail.text,
|
|
2282
|
+
detailCode: detail.code,
|
|
2283
|
+
...(detail.params === undefined ? {} : { detailParams: detail.params }),
|
|
2284
|
+
})
|
|
2285
|
+
continue
|
|
2286
|
+
}
|
|
2287
|
+
const detail = conflictDetail(entry.name, alias)
|
|
2288
|
+
rows.push({
|
|
2289
|
+
...base,
|
|
2290
|
+
status: 'conflict',
|
|
2291
|
+
detail: detail.text,
|
|
2292
|
+
detailCode: detail.code,
|
|
2293
|
+
...(detail.params === undefined ? {} : { detailParams: detail.params }),
|
|
2294
|
+
})
|
|
2295
|
+
continue
|
|
2296
|
+
}
|
|
2297
|
+
desired.set(entry.name, entry)
|
|
2298
|
+
rows.push(base)
|
|
2299
|
+
}
|
|
2300
|
+
|
|
2301
|
+
const documentIssues: SnapshotIssue[] = issues.map((issue) => ({
|
|
2302
|
+
source: issue.source,
|
|
2303
|
+
...(issue.server === undefined ? {} : { server: issue.server }),
|
|
2304
|
+
level: issue.level,
|
|
2305
|
+
message: issue.message,
|
|
2306
|
+
...(issue.code === undefined ? {} : { code: issue.code }),
|
|
2307
|
+
...(issue.params === undefined ? {} : { params: issue.params }),
|
|
2308
|
+
}))
|
|
2309
|
+
|
|
2310
|
+
// The project's shared instance, if it already has one. Its mounts are what
|
|
2311
|
+
// this session holds when it is already attached, and what it is about to
|
|
2312
|
+
// share when it attaches below — both are read live, never copied.
|
|
2313
|
+
const existing = this.projects.get(projectRoot)
|
|
2314
|
+
// The mounts whose changes this session's digest tracks: its own home's
|
|
2315
|
+
// when it has one, otherwise the project's shared set. A session that holds
|
|
2316
|
+
// nothing must still notice another session mounting, settling or dropping
|
|
2317
|
+
// a server, because its rows are a rendering of exactly those mounts.
|
|
2318
|
+
const mounts = this.visibleMounts(state, projectRoot)
|
|
2319
|
+
|
|
2320
|
+
// Steady state: the documents, their resolved configs, the profile
|
|
2321
|
+
// reservations and the published state of the shared mounts are identical
|
|
2322
|
+
// and every mount has settled, so this pass has nothing to reconcile — no
|
|
2323
|
+
// merge, no tool-catalog scan, no remount. The shared-mount part of the
|
|
2324
|
+
// digest matters because another session of this project can have mounted,
|
|
2325
|
+
// settled or dropped a server without any document changing, and this
|
|
2326
|
+
// session's rows are a rendering of exactly those mounts.
|
|
2327
|
+
//
|
|
2328
|
+
// One state is *not* settled even so: a session whose project declares
|
|
2329
|
+
// something mountable and which `lazy` has mounted nothing for. Its inputs
|
|
2330
|
+
// are byte-identical to the pass that only published the declaration, so the
|
|
2331
|
+
// digest cannot tell them apart — an operator pass (`syncNow`, `retry`) has
|
|
2332
|
+
// to mount it now instead of waiting for a turn that may never come.
|
|
2333
|
+
const mountable = desired.size > 0
|
|
2334
|
+
// Whether *this* session already holds mounts. The project can be running
|
|
2335
|
+
// for another session of it while this one holds nothing, and such a
|
|
2336
|
+
// session must not be attached by a pass of its own: holding would make it
|
|
2337
|
+
// keep an instance it never asked for alive past its last real holder, and
|
|
2338
|
+
// would put the project's tools into a session that never turned.
|
|
2339
|
+
const held = this.mountsOf(state).size > 0
|
|
2340
|
+
// What this session is allowed to start in this pass, and why. `undefined`
|
|
2341
|
+
// is the answer for every session that is not working in its project: it is
|
|
2342
|
+
// live, it declares servers, and none of them may run.
|
|
2343
|
+
const trigger = mountTrigger({
|
|
2344
|
+
lazy: this.config.lazy,
|
|
2345
|
+
activationPending: state.activationPending,
|
|
2346
|
+
mounted: held,
|
|
2347
|
+
operatorRequested,
|
|
2348
|
+
})
|
|
2349
|
+
const awaitedMount = trigger === 'operator' && this.config.lazy && !held && mountable
|
|
2350
|
+
/**
|
|
2351
|
+
* Identity of this pass's inputs, recomputed once the mounts settled — a
|
|
2352
|
+
* mount created or dropped by this very pass is then part of it, so the
|
|
2353
|
+
* next pass recognizes the steady state instead of rebuilding one more time.
|
|
2354
|
+
*/
|
|
2355
|
+
const settle = (): void => {
|
|
2356
|
+
state.digest = digestOf(entries, reserved, this.visibleMounts(state, projectRoot), chosen)
|
|
2357
|
+
}
|
|
2358
|
+
/**
|
|
2359
|
+
* The project record; only a session that may run something takes a hold,
|
|
2360
|
+
* and minting the record is what lets every other session of the root share
|
|
2361
|
+
* the instance it starts.
|
|
2362
|
+
*/
|
|
2363
|
+
const project = trigger === undefined || desired.size === 0 ? existing : this.ensureProject(projectRoot)
|
|
2364
|
+
const digest = digestOf(entries, reserved, mounts, chosen)
|
|
2365
|
+
if (!awaitedMount && state.digest === digest && this.settled(state) && !state.activationPending) return
|
|
2366
|
+
|
|
2367
|
+
// `lazy` defers a session's *first* mount to its first turn. Removals and
|
|
2368
|
+
// edits are always reconciled below; an operator call (`syncNow`, `retry`)
|
|
2369
|
+
// and a pending activation mount regardless.
|
|
2370
|
+
//
|
|
2371
|
+
// `mounted` in the decision above makes `undefined` unreachable while this
|
|
2372
|
+
// session holds servers, so publishing rows here never hides a live mount.
|
|
2373
|
+
if (trigger === undefined) {
|
|
2374
|
+
// Nothing runs for this session: publish what the project declares (it is
|
|
2375
|
+
// what the next turn will mount) without starting a single server.
|
|
2376
|
+
state.rows = rows.map((row) => (desired.has(row.name) ? idleRow(row, LAZY_DETAIL) : row))
|
|
2377
|
+
state.issues = documentIssues
|
|
2378
|
+
settle()
|
|
2379
|
+
return
|
|
2380
|
+
}
|
|
2381
|
+
|
|
2382
|
+
// A session that may mount takes its hold first: the parent link is what
|
|
2383
|
+
// makes the project's already running servers visible to it, and minting
|
|
2384
|
+
// the session scope is what carries the session wiring. A session whose
|
|
2385
|
+
// scope key the harness already parented cannot take that link at all and
|
|
2386
|
+
// gets a home of its own, which is why the hold returns the home the pass
|
|
2387
|
+
// reconciles instead of the pass assuming the project's. A project that
|
|
2388
|
+
// declares nothing mountable mints no session scope at all — the
|
|
2389
|
+
// declarations below are published and nothing runs.
|
|
2390
|
+
let home: MountHome | undefined
|
|
2391
|
+
if (desired.size > 0 && project !== undefined) {
|
|
2392
|
+
home = await this.holdProject(state, project)
|
|
2393
|
+
} else {
|
|
2394
|
+
home = this.homeOf(state) ?? existing
|
|
2395
|
+
}
|
|
2396
|
+
|
|
2397
|
+
if (home !== undefined) {
|
|
2398
|
+
// One home is reconciled, not one session's share of it: an edit or a
|
|
2399
|
+
// removal in the document is every holder's business, and a declaration
|
|
2400
|
+
// either exists for all sessions that resolve the home or for none.
|
|
2401
|
+
for (const [name, mount] of [...home.mounts]) {
|
|
2402
|
+
const entry = desired.get(name)
|
|
2403
|
+
if (entry?.config === undefined) {
|
|
2404
|
+
// A reserved name this project was mounting leaves for one of two
|
|
2405
|
+
// reasons — the declaration is gone, or the user went back to the
|
|
2406
|
+
// profile's copy — and the lifecycle log is where a reader tells them
|
|
2407
|
+
// apart.
|
|
2408
|
+
await this.unmount(
|
|
2409
|
+
home,
|
|
2410
|
+
name,
|
|
2411
|
+
reserved.has(name)
|
|
2412
|
+
? { code: 'unmount.reason.profileShown', text: 'this project shows the profile-level copy instead' }
|
|
2413
|
+
: { code: 'unmount.reason.undeclared', text: 'the documents no longer declare it' },
|
|
2414
|
+
)
|
|
2415
|
+
continue
|
|
2416
|
+
}
|
|
2417
|
+
// A mount that no longer carries the local name this pass chose is
|
|
2418
|
+
// remounted, not kept: the alias is the whole of what the user changed,
|
|
2419
|
+
// and a registration is only ever created under one name.
|
|
2420
|
+
if (mount.runtimeName !== runtimeNameOf(entry, chosen.get(name))) {
|
|
2421
|
+
await this.unmount(home, name, { code: 'unmount.reason.nameChanged', text: 'its local name changed' })
|
|
2422
|
+
continue
|
|
2423
|
+
}
|
|
2424
|
+
if (mount.fingerprint !== fingerprint(entry.config)) {
|
|
2425
|
+
await this.unmount(home, name, { code: 'unmount.reason.declarationChanged', text: 'its declaration changed' })
|
|
2426
|
+
}
|
|
2427
|
+
}
|
|
2428
|
+
|
|
2429
|
+
// Registration only: no `mount` here waits for its server, so this loop
|
|
2430
|
+
// is what a pass costs per declaration, not the handshake behind it.
|
|
2431
|
+
for (const [name, entry] of desired) {
|
|
2432
|
+
if (entry.config === undefined || home.mounts.has(name)) continue
|
|
2433
|
+
this.mount(state, home, name, entry, trigger, chosen.get(name))
|
|
2434
|
+
}
|
|
2435
|
+
if (home.mounts.size === 0) {
|
|
2436
|
+
// Nothing is mounted by design: this session keeps no hold, and a
|
|
2437
|
+
// shared scope goes with its last holder, so no server outlives the
|
|
2438
|
+
// session that asked for it.
|
|
2439
|
+
await this.detach(state, { code: 'unmount.reason.nothingMountable', text: 'nothing it declares is mountable any more' })
|
|
2440
|
+
if (home.shared && !this.hasHolders(home as ProjectState)) {
|
|
2441
|
+
await this.releaseProject(home as ProjectState, { code: 'unmount.reason.nothingMountable', text: 'nothing it declares is mountable any more' })
|
|
2442
|
+
}
|
|
2443
|
+
}
|
|
2444
|
+
}
|
|
2445
|
+
|
|
2446
|
+
// The declarations as the documents give them. A mounted server keeps its
|
|
2447
|
+
// declared row here: the mount's own status is applied when the picture is
|
|
2448
|
+
// read ({@link liveRows}), so a drop, a new mount or a connect that happens
|
|
2449
|
+
// between two passes is visible without waiting for the next one.
|
|
2450
|
+
state.rows = rows.map((row) =>
|
|
2451
|
+
desired.has(row.name) && home?.mounts.has(row.name) !== true
|
|
2452
|
+
// A declaration that `lazy` has not mounted yet, or a newly added one.
|
|
2453
|
+
? idleRow(row, LAZY_DETAIL)
|
|
2454
|
+
: row,
|
|
2455
|
+
)
|
|
2456
|
+
state.issues = documentIssues
|
|
2457
|
+
state.activationPending = false
|
|
2458
|
+
// Start the idle clock for a session that never reported activity, so an
|
|
2459
|
+
// unused one still releases its servers.
|
|
2460
|
+
state.lastActivityAt ??= Date.now()
|
|
2461
|
+
this.refreshStatuses(agent, state)
|
|
2462
|
+
// After the status scan, so a mount the watchdog has just flagged reports
|
|
2463
|
+
// its stall in the same pass that turned its row into an error.
|
|
2464
|
+
state.issues.push(...this.mountDiagnostics(state, projectRoot))
|
|
2465
|
+
settle()
|
|
2466
|
+
// The rows this session contributes are what they are now: announce them
|
|
2467
|
+
// before the pass moves on, so a mount that needed its full connect window
|
|
2468
|
+
// does not hold the whole picture back.
|
|
2469
|
+
this.notify()
|
|
2470
|
+
}
|
|
2471
|
+
|
|
2472
|
+
/**
|
|
2473
|
+
* Start one declared server in the session's mount home and record the mount,
|
|
2474
|
+
* which every session that home serves then resolves.
|
|
2475
|
+
*
|
|
2476
|
+
* Exactly one `info` line is written per created process — never on a rescan
|
|
2477
|
+
* that re-derives the same mount, and never when another session of the
|
|
2478
|
+
* project attaches to a shared instance that is already running — so an
|
|
2479
|
+
* operator can tell which session caused a server to start, in which project,
|
|
2480
|
+
* and what asked for it.
|
|
2481
|
+
*
|
|
2482
|
+
* The registration is the whole of what this pass does here: the fiber's
|
|
2483
|
+
* activation is *watched*, never awaited, so a server that never answers
|
|
2484
|
+
* costs the pass — and with it every turn waiting on that pass — nothing.
|
|
2485
|
+
* The mount is recorded before the wait, so a later pass finds it in place
|
|
2486
|
+
* and mounts nothing a second time; the outcome reaches the row through
|
|
2487
|
+
* {@link observeActivation} on failure and through {@link refreshStatuses}
|
|
2488
|
+
* on success.
|
|
2489
|
+
* @param state - the session whose pass creates the instance.
|
|
2490
|
+
* @param home - the scope the instance belongs to: the project's shared one,
|
|
2491
|
+
* or the session's own when it could not join the project's chain.
|
|
2492
|
+
* @param name - declared `serverName`.
|
|
2493
|
+
* @param entry - the parsed declaration to mount.
|
|
2494
|
+
* @param trigger - why this pass was allowed to start it.
|
|
2495
|
+
* @param alias - local name to register under, when a profile instance owns
|
|
2496
|
+
* the declared one and the user chose to see the project's copy too.
|
|
2497
|
+
*/
|
|
2498
|
+
private mount(
|
|
2499
|
+
state: AgentState,
|
|
2500
|
+
home: MountHome,
|
|
2501
|
+
name: string,
|
|
2502
|
+
entry: ParsedEntry,
|
|
2503
|
+
trigger: MountTrigger,
|
|
2504
|
+
alias?: string,
|
|
2505
|
+
): void {
|
|
2506
|
+
const config = entry.config
|
|
2507
|
+
if (config === undefined) return
|
|
2508
|
+
const runtimeName = runtimeNameOf(entry, alias)
|
|
2509
|
+
const mount: MountedInstance = {
|
|
2510
|
+
name,
|
|
2511
|
+
runtimeName,
|
|
2512
|
+
projectRoot: home.projectRoot,
|
|
2513
|
+
fingerprint: fingerprint(config),
|
|
2514
|
+
fiber: undefined,
|
|
2515
|
+
status: 'connecting',
|
|
2516
|
+
detail: undefined,
|
|
2517
|
+
detailCode: undefined,
|
|
2518
|
+
detailParams: undefined,
|
|
2519
|
+
source: entry.source,
|
|
2520
|
+
transport: config.transport,
|
|
2521
|
+
endpoint: describeEndpoint(config),
|
|
2522
|
+
startedAt: Date.now(),
|
|
2523
|
+
stalled: false,
|
|
2524
|
+
failed: false,
|
|
2525
|
+
}
|
|
2526
|
+
home.mounts.set(name, mount)
|
|
2527
|
+
// The row turns `connecting` the moment the mount exists; announcing it here
|
|
2528
|
+
// is what makes a `Retry` visible in the panel while the server is still
|
|
2529
|
+
// booting, instead of only when the pass that started it returns.
|
|
2530
|
+
this.notify()
|
|
2531
|
+
try {
|
|
2532
|
+
const scope = this.ensureProjectScope(home as ProjectState)
|
|
2533
|
+
if (scope === undefined) {
|
|
2534
|
+
throw new Error('the project scope could not be minted, so the instance has no scope to register in')
|
|
2535
|
+
}
|
|
2536
|
+
const plugin = this.options.plugin ?? mcpClient
|
|
2537
|
+
// Call through the receiver: `ctx.plugin` is a context-bound method and
|
|
2538
|
+
// an extracted reference would lose `this`.
|
|
2539
|
+
const target = scope.ctx as unknown as {
|
|
2540
|
+
plugin(plugin: unknown, config: unknown): MountFiber
|
|
2541
|
+
}
|
|
2542
|
+
const fiber = target.plugin(plugin, clientConfig(runtimeConfigOf(config, runtimeName)))
|
|
2543
|
+
mount.fiber = fiber
|
|
2544
|
+
const sharing: CodedText = state.parentLinked
|
|
2545
|
+
? { code: 'mount.sharingShared', text: 'one shared instance for every session of this project' }
|
|
2546
|
+
: {
|
|
2547
|
+
code: 'mount.sharingForwarded',
|
|
2548
|
+
text: "one shared instance for this project, forwarded into this session's own layer",
|
|
2549
|
+
}
|
|
2550
|
+
this.logLifecycle({
|
|
2551
|
+
at: Date.now(),
|
|
2552
|
+
level: 'info',
|
|
2553
|
+
logLevel: 'info',
|
|
2554
|
+
projectRoot: mount.projectRoot,
|
|
2555
|
+
sessionId: state.agent.id,
|
|
2556
|
+
server: name,
|
|
2557
|
+
message: `mounting for session ${state.agent.id} (trigger: ${trigger}; ${sharing.text})`,
|
|
2558
|
+
code: 'mount.starting',
|
|
2559
|
+
params: { sessionId: state.agent.id, trigger, sharingCode: sharing.code },
|
|
2560
|
+
line: `mounting ${name}${runtimeName === name ? '' : ` as ${runtimeName}`} for session ${state.agent.id} in ${home.projectRoot} (trigger: ${trigger}; ${sharing.text})`,
|
|
2561
|
+
})
|
|
2562
|
+
// Not awaited: the pass returns with the mount recorded and `connecting`,
|
|
2563
|
+
// and whatever the activation turns out to be is written from behind it.
|
|
2564
|
+
this.observeActivation(home, mount, `activation of ${name}`, fiber)
|
|
2565
|
+
} catch (error) {
|
|
2566
|
+
this.recordMountFailure(home, mount, error)
|
|
2567
|
+
}
|
|
2568
|
+
}
|
|
2569
|
+
|
|
2570
|
+
/**
|
|
2571
|
+
* Publish one lifecycle event, and announce it.
|
|
2572
|
+
*
|
|
2573
|
+
* The plugin's five lifecycle facts — mounting, `is up`, a stall, a failed
|
|
2574
|
+
* mount, unmounting — leave the runtime through this one method and no other,
|
|
2575
|
+
* and the snapshot announcement follows every one of them, as it did when each
|
|
2576
|
+
* site kept the three writes in step by hand. What the DSH log prints and what
|
|
2577
|
+
* the ring holds are the subscribers' business now: the runtime only says what
|
|
2578
|
+
* happened (`src/notifications.ts`).
|
|
2579
|
+
* @param event - the fact, already carrying its level, session and server.
|
|
2580
|
+
*/
|
|
2581
|
+
private logLifecycle(event: PluginEvent): void {
|
|
2582
|
+
emitEvent(event)
|
|
2583
|
+
this.notify()
|
|
2584
|
+
}
|
|
2585
|
+
|
|
2586
|
+
/**
|
|
2587
|
+
* Watch one mount's activation in the background, so the registering pass
|
|
2588
|
+
* never waits for it.
|
|
2589
|
+
*
|
|
2590
|
+
* A failure is the one outcome the pass used to report itself, and it is
|
|
2591
|
+
* written exactly as it was when it did: the row turns `error`, `failed`
|
|
2592
|
+
* keeps {@link refreshStatuses} from polling a dead fiber, and the detail is
|
|
2593
|
+
* {@link failureDetail}. A success and a timeout write nothing — a mount
|
|
2594
|
+
* whose tools became visible is turned `active` by the status scan of the
|
|
2595
|
+
* next pass, which logs the `is up` line, and a mount that is merely slow is
|
|
2596
|
+
* the watchdog's stall to report.
|
|
2597
|
+
*
|
|
2598
|
+
* Nothing awaits the returned promise, so it must never reject: `waitFor`
|
|
2599
|
+
* already answers a rejected fiber with `{ kind: 'failed' }`, and the final
|
|
2600
|
+
* `catch` is the backstop for the recorder itself.
|
|
2601
|
+
* @param home - the home the mount was recorded in, read to see it is current.
|
|
2602
|
+
* @param mount - the mount whose activation this watches.
|
|
2603
|
+
* @param label - the wait label, as `waitFor` names it in the debug line.
|
|
2604
|
+
* @param fiber - the fiber whose activation this watches.
|
|
2605
|
+
*/
|
|
2606
|
+
private observeActivation(
|
|
2607
|
+
home: MountHome,
|
|
2608
|
+
mount: MountedInstance,
|
|
2609
|
+
label: string,
|
|
2610
|
+
fiber: MountFiber,
|
|
2611
|
+
): void {
|
|
2612
|
+
void this.settleActivation(home, mount, label, fiber).catch((error: unknown) => {
|
|
2613
|
+
this.ctx.logger.warn(
|
|
2614
|
+
`project-mcp: watching the activation of ${mount.name} failed: ${errorText(error)}`,
|
|
2615
|
+
)
|
|
2616
|
+
})
|
|
2617
|
+
}
|
|
2618
|
+
|
|
2619
|
+
/**
|
|
2620
|
+
* The watched wait itself: one activation to its outcome, then the failure
|
|
2621
|
+
* written if it had one.
|
|
2622
|
+
* @param home - the home the mount was recorded in.
|
|
2623
|
+
* @param mount - the mount whose activation this waits for.
|
|
2624
|
+
* @param label - the wait label, as `waitFor` names it in the debug line.
|
|
2625
|
+
* @param fiber - the fiber whose activation this waits for.
|
|
2626
|
+
*/
|
|
2627
|
+
private async settleActivation(
|
|
2628
|
+
home: MountHome,
|
|
2629
|
+
mount: MountedInstance,
|
|
2630
|
+
label: string,
|
|
2631
|
+
fiber: MountFiber,
|
|
2632
|
+
): Promise<void> {
|
|
2633
|
+
const outcome = await this.waitFor(label, activation(fiber))
|
|
2634
|
+
// A later pass may already have dropped or replaced this mount — an operator
|
|
2635
|
+
// retry, an edited declaration, a teardown. The fiber going down with its
|
|
2636
|
+
// home is not a failure of a mount nobody serves any more.
|
|
2637
|
+
if (home.mounts.get(mount.name) !== mount) return
|
|
2638
|
+
if (outcome.kind === 'failed') {
|
|
2639
|
+
this.recordMountFailure(home, mount, outcome.error)
|
|
2640
|
+
this.announceHome(home)
|
|
2641
|
+
return
|
|
2642
|
+
}
|
|
2643
|
+
// The server's tools exist as of this moment, so this is where the sessions
|
|
2644
|
+
// that read the project through the bridge actually receive them: the mount
|
|
2645
|
+
// was registered before its fiber had published anything, and a session whose
|
|
2646
|
+
// key predates that registration has no other signal. On a real registry the
|
|
2647
|
+
// `tools/change` subscription carries the same news.
|
|
2648
|
+
this.syncBridgesOf(home)
|
|
2649
|
+
// Success: the tools may have appeared long after the pass that registered
|
|
2650
|
+
// the mount returned, and a deployment with `watch: false` and no idle sweep
|
|
2651
|
+
// has no rescan timer to notice. Announcing here is what turns `connecting`
|
|
2652
|
+
// into `active` — and logs `is up` — the moment it is true, instead of up to
|
|
2653
|
+
// `rescanIntervalMs` later.
|
|
2654
|
+
this.announceHome(home)
|
|
2655
|
+
}
|
|
2656
|
+
|
|
2657
|
+
/**
|
|
2658
|
+
* Re-read one home's mounts for every session that holds it, then tell the
|
|
2659
|
+
* panels.
|
|
2660
|
+
*
|
|
2661
|
+
* Called from behind a pass — a mount settles after its pass has returned —
|
|
2662
|
+
* so for a deployment without a rescan timer this is the only moment that
|
|
2663
|
+
* moves a row off `connecting`. Idempotent: the transition log fires on a
|
|
2664
|
+
* change, so a second call for the same mount writes nothing.
|
|
2665
|
+
* @param home - the home whose instances settled.
|
|
2666
|
+
*/
|
|
2667
|
+
private announceHome(home: MountHome): void {
|
|
2668
|
+
if (this.disposed) return
|
|
2669
|
+
for (const state of this.states.values()) {
|
|
2670
|
+
if (this.homeOf(state) !== home) continue
|
|
2671
|
+
this.refreshStatuses(state.agent, state)
|
|
2672
|
+
}
|
|
2673
|
+
this.notify()
|
|
2674
|
+
}
|
|
2675
|
+
|
|
2676
|
+
/**
|
|
2677
|
+
* Record a mount that could not be activated: the row's `error`, the detail
|
|
2678
|
+
* an operator reads, and the one warning line. Shared by the synchronous
|
|
2679
|
+
* registration failures and the watched activations above, so both report
|
|
2680
|
+
* the same three facts in the same words.
|
|
2681
|
+
* @param home - the home the failed instance belongs to.
|
|
2682
|
+
* @param mount - the mount to mark failed.
|
|
2683
|
+
* @param error - what the fiber or the registration failed with.
|
|
2684
|
+
*/
|
|
2685
|
+
private recordMountFailure(home: MountHome, mount: MountedInstance, error: unknown): void {
|
|
2686
|
+
mount.status = 'error'
|
|
2687
|
+
mount.failed = true
|
|
2688
|
+
const failure = failureDetail(mount, error)
|
|
2689
|
+
mount.detail = failure.text
|
|
2690
|
+
mount.detailCode = failure.code
|
|
2691
|
+
mount.detailParams = failure.params
|
|
2692
|
+
// The Logs tab gets the same three facts, first line as the row's message and
|
|
2693
|
+
// the whole detail for its second line. The instance serves every session of
|
|
2694
|
+
// its project, so the failure is a project event and names no session.
|
|
2695
|
+
this.logLifecycle({
|
|
2696
|
+
at: Date.now(),
|
|
2697
|
+
level: 'error',
|
|
2698
|
+
logLevel: 'warn',
|
|
2699
|
+
projectRoot: mount.projectRoot,
|
|
2700
|
+
server: mount.name,
|
|
2701
|
+
message: `mount failed — ${errorText(error)}`,
|
|
2702
|
+
code: 'mount.failed',
|
|
2703
|
+
params: { error: errorText(error) },
|
|
2704
|
+
detail: mount.detail,
|
|
2705
|
+
detailCode: failure.code,
|
|
2706
|
+
...(failure.params === undefined ? {} : { detailParams: failure.params }),
|
|
2707
|
+
line: mount.detail,
|
|
2708
|
+
})
|
|
2709
|
+
}
|
|
2710
|
+
|
|
2711
|
+
/**
|
|
2712
|
+
* The session-scope context the bridge registers through: the minted scope's
|
|
2713
|
+
* context carries the session's scope tag, so a registration made through it
|
|
2714
|
+
* lands in exactly this session's layer.
|
|
2715
|
+
*/
|
|
2716
|
+
private bridgeContextOf(scope: Pick<Scope, 'ctx' | 'dispose'>): BridgeContextLike {
|
|
2717
|
+
if (this.options.bridgeContext !== undefined) return this.options.bridgeContext(scope)
|
|
2718
|
+
return {
|
|
2719
|
+
get: (name) => (scope.ctx as unknown as { get(service: string): unknown }).get(name),
|
|
2720
|
+
}
|
|
2721
|
+
}
|
|
2722
|
+
|
|
2723
|
+
/** The registry surface the bridge reads; defaults to the plugin's own. */
|
|
2724
|
+
private bridgeRegistry(): BridgeRegistryLike {
|
|
2725
|
+
if (this.options.registry !== undefined) return this.options.registry
|
|
2726
|
+
const ctx = this.ctx as unknown as {
|
|
2727
|
+
tools: {
|
|
2728
|
+
get(name: string, scope?: object): ReturnType<BridgeRegistryLike['get']>
|
|
2729
|
+
schemas(scope?: object): ReturnType<BridgeRegistryLike['schemas']>
|
|
2730
|
+
}
|
|
2731
|
+
}
|
|
2732
|
+
// Bound through the receiver: an extracted `ctx.tools.get` reference would
|
|
2733
|
+
// lose the registry's `this`.
|
|
2734
|
+
return {
|
|
2735
|
+
get: (name, scope) => ctx.tools.get(name, scope),
|
|
2736
|
+
schemas: (scope) => ctx.tools.schemas(scope),
|
|
2737
|
+
}
|
|
2738
|
+
}
|
|
2739
|
+
|
|
2740
|
+
/**
|
|
2741
|
+
* Install the forwarding bridge on one session: thin definitions in the
|
|
2742
|
+
* session's own layer over the project's live tools.
|
|
2743
|
+
*
|
|
2744
|
+
* Idempotent while the session keeps its project. The `tools/change`
|
|
2745
|
+
* subscription is what keeps the bridge level with a server that publishes
|
|
2746
|
+
* its tools long after the pass that registered the mount returned — the
|
|
2747
|
+
* session's layer is brought up to date before the next turn reads it.
|
|
2748
|
+
* A failure is contained: the session keeps its hold on the project's servers
|
|
2749
|
+
* and gets no tools from them until the next pass retries the sync.
|
|
2750
|
+
* @param state - the session taking the bridge.
|
|
2751
|
+
* @param project - the project whose tools are forwarded.
|
|
2752
|
+
*/
|
|
2753
|
+
private installBridge(state: AgentState, project: ProjectState): void {
|
|
2754
|
+
if (state.bridge !== undefined || state.scope === undefined) return
|
|
2755
|
+
const context = this.bridgeContextOf(state.scope)
|
|
2756
|
+
const registry = this.bridgeRegistry()
|
|
2757
|
+
const servers = (): ReadonlySet<string> => this.runtimeNamesOf(state)
|
|
2758
|
+
const batch = new ForwardBatch({
|
|
2759
|
+
names: () => {
|
|
2760
|
+
try {
|
|
2761
|
+
return projectToolNames(
|
|
2762
|
+
state.project?.key ?? {},
|
|
2763
|
+
(scope) => this.bridgeSchemas(scope),
|
|
2764
|
+
servers(),
|
|
2765
|
+
)
|
|
2766
|
+
} catch (error) {
|
|
2767
|
+
// A probe that failed says nothing about the project's set: the batch
|
|
2768
|
+
// it could not describe is the batch that stays live.
|
|
2769
|
+
this.ctx.logger.warn(
|
|
2770
|
+
`project-mcp: reading the tools to forward to session ${state.agent.id} failed: ${errorText(error)}`,
|
|
2771
|
+
)
|
|
2772
|
+
return undefined
|
|
2773
|
+
}
|
|
2774
|
+
},
|
|
2775
|
+
register: (names) => forwardProjectTools({
|
|
2776
|
+
ctx: context,
|
|
2777
|
+
project: state.project?.key ?? {},
|
|
2778
|
+
names,
|
|
2779
|
+
registry,
|
|
2780
|
+
}),
|
|
2781
|
+
})
|
|
2782
|
+
const bridge: BridgeForwarders = {
|
|
2783
|
+
batch,
|
|
2784
|
+
detach: () => undefined,
|
|
2785
|
+
}
|
|
2786
|
+
// The listener lives on the session scope and is dropped with it, so a
|
|
2787
|
+
// released session never keeps syncing against a project it left.
|
|
2788
|
+
const detach = state.scope.ctx.on('tools/change', () => this.syncBridge(state))
|
|
2789
|
+
bridge.detach = typeof detach === 'function' ? (detach as () => void) : () => undefined
|
|
2790
|
+
state.bridge = bridge
|
|
2791
|
+
this.syncBridge(state)
|
|
2792
|
+
}
|
|
2793
|
+
|
|
2794
|
+
/**
|
|
2795
|
+
* Bring one session's forwarders level with the project's live tools.
|
|
2796
|
+
*
|
|
2797
|
+
* The pass itself — including the re-entry its own registrations force on it
|
|
2798
|
+
* through `tools/change` — belongs to the session's {@link ForwardBatch}; this
|
|
2799
|
+
* is where a failure is contained and reported. A failed pass leaves the
|
|
2800
|
+
* session with no forwarder until the next pass retries (`namesIn` stays
|
|
2801
|
+
* unset), and never takes the session's hold on the project down.
|
|
2802
|
+
* @param state - the session whose bridge to sync.
|
|
2803
|
+
*/
|
|
2804
|
+
private syncBridge(state: AgentState): void {
|
|
2805
|
+
const bridge = state.bridge
|
|
2806
|
+
if (bridge === undefined) return
|
|
2807
|
+
try {
|
|
2808
|
+
bridge.batch.sync()
|
|
2809
|
+
} catch (error) {
|
|
2810
|
+
this.ctx.logger.warn(
|
|
2811
|
+
`project-mcp: forwarding the tools of ${state.project?.projectRoot ?? 'the project'} into session ${state.agent.id} failed: ${errorText(error)}`,
|
|
2812
|
+
)
|
|
2813
|
+
}
|
|
2814
|
+
}
|
|
2815
|
+
|
|
2816
|
+
/** The project scope's visible schemas, as {@link projectToolNames} reads them. */
|
|
2817
|
+
private bridgeSchemas(scope: object): ReturnType<BridgeRegistryLike['schemas']> {
|
|
2818
|
+
return this.bridgeRegistry().schemas(scope)
|
|
2819
|
+
}
|
|
2820
|
+
|
|
2821
|
+
/** Drop one session's bridge: its forwarders and its subscription. Idempotent. */
|
|
2822
|
+
private dropBridge(state: AgentState): void {
|
|
2823
|
+
const bridge = state.bridge
|
|
2824
|
+
if (bridge === undefined) return
|
|
2825
|
+
state.bridge = undefined
|
|
2826
|
+
try {
|
|
2827
|
+
bridge.batch.drop()
|
|
2828
|
+
} catch (error) {
|
|
2829
|
+
this.ctx.logger.warn(
|
|
2830
|
+
`project-mcp: dropping the forwarded tools of session ${state.agent.id} failed: ${errorText(error)}`,
|
|
2831
|
+
)
|
|
2832
|
+
}
|
|
2833
|
+
try {
|
|
2834
|
+
bridge.detach()
|
|
2835
|
+
} catch {
|
|
2836
|
+
// The scope disposal that follows drops the same subscription; a throw
|
|
2837
|
+
// here must not keep the session's hold from being released.
|
|
2838
|
+
}
|
|
2839
|
+
}
|
|
2840
|
+
|
|
2841
|
+
/**
|
|
2842
|
+
* The project's shared scope, minted with its first mount. One scope per
|
|
2843
|
+
* project is what makes mcp-client's `serverName` reservation per project
|
|
2844
|
+
* rather than per session, and it is disposed when the project's last holder
|
|
2845
|
+
* lets go, so the instance lifetime matches a per-session mount's.
|
|
2846
|
+
* @param project - the project to mount into.
|
|
2847
|
+
* @returns the scope, reused when the project already has one.
|
|
2848
|
+
*/
|
|
2849
|
+
private ensureProjectScope(project: ProjectState): Pick<Scope, 'ctx' | 'dispose'> {
|
|
2850
|
+
const existing = project.scope
|
|
2851
|
+
if (existing !== undefined) return existing
|
|
2852
|
+
const scope = this.mintScope(project.key)
|
|
2853
|
+
project.scope = scope
|
|
2854
|
+
return scope
|
|
2855
|
+
}
|
|
2856
|
+
|
|
2857
|
+
/**
|
|
2858
|
+
* Wait for one fiber operation, bounded by `connectTimeoutMs`. A server that
|
|
2859
|
+
* never answers must not hold a pass (or a project's teardown) open forever;
|
|
2860
|
+
* the fiber stays alive and later passes keep watching it.
|
|
2861
|
+
*/
|
|
2862
|
+
private async waitFor<T>(label: string, wait: Promise<T>): Promise<WaitOutcome<T>> {
|
|
2863
|
+
const limit = this.config.connectTimeoutMs
|
|
2864
|
+
const settled = wait.then(
|
|
2865
|
+
(value): WaitOutcome<T> => ({ kind: 'settled', value }),
|
|
2866
|
+
(error): WaitOutcome<T> => ({ kind: 'failed', error }),
|
|
2867
|
+
)
|
|
2868
|
+
if (limit <= 0) return await settled
|
|
2869
|
+
const outcome = await Promise.race([
|
|
2870
|
+
settled,
|
|
2871
|
+
delay(limit).then((): WaitOutcome<T> => ({ kind: 'timeout' })),
|
|
2872
|
+
])
|
|
2873
|
+
if (outcome.kind === 'timeout') {
|
|
2874
|
+
this.ctx.logger.debug?.(
|
|
2875
|
+
`project-mcp: ${label} did not settle within ${formatSeconds(limit)}; the pass continues without it`,
|
|
2876
|
+
)
|
|
2877
|
+
}
|
|
2878
|
+
return outcome
|
|
2879
|
+
}
|
|
2880
|
+
|
|
2881
|
+
/**
|
|
2882
|
+
* Whether every mount has settled, so a rescan can return without work. A
|
|
2883
|
+
* stalled mount keeps the pass alive on purpose: only a fresh status scan can
|
|
2884
|
+
* notice that the client's background retry finally connected.
|
|
2885
|
+
*/
|
|
2886
|
+
private settled(state: AgentState): boolean {
|
|
2887
|
+
for (const mount of this.mountsOf(state).values()) {
|
|
2888
|
+
if (mount.stalled) return false
|
|
2889
|
+
if (mount.status !== 'active' && mount.status !== 'error') return false
|
|
2890
|
+
}
|
|
2891
|
+
return true
|
|
2892
|
+
}
|
|
2893
|
+
|
|
2894
|
+
/**
|
|
2895
|
+
* Mint one scope through the injected factory, or through the module itself.
|
|
2896
|
+
* The parent link of a session key is established by {@link holdProject} before
|
|
2897
|
+
* this runs and deliberately not passed as `createScope`'s own `parent`
|
|
2898
|
+
* option: binding twice on one key throws, and the retained binding is what
|
|
2899
|
+
* makes a release and a project change re-linkable.
|
|
2900
|
+
* @param key - session key or project key the scope's registrations own.
|
|
2901
|
+
* @returns the minted scope.
|
|
2902
|
+
*/
|
|
2903
|
+
private mintScope(key: AgentLike | ProjectScopeKey): Pick<Scope, 'ctx' | 'dispose'> {
|
|
2904
|
+
if (this.options.createScope !== undefined) return this.options.createScope(this.ctx, key)
|
|
2905
|
+
return createScope(this.ctx, key)
|
|
2906
|
+
}
|
|
2907
|
+
|
|
2908
|
+
/**
|
|
2909
|
+
* Mint the session scope on first use and install the session wiring on it:
|
|
2910
|
+
* the project-MCP guidance section and, when activation is on, the wiring
|
|
2911
|
+
* that lets a project's MCP tools be *found* (`mcp_search_tools`) and put
|
|
2912
|
+
* back into an assembly a presentation plugin filtered.
|
|
2913
|
+
*
|
|
2914
|
+
* Both are installed once per scope and both read the project's live state, so
|
|
2915
|
+
* a rescan that changes the mounted set changes what they say without
|
|
2916
|
+
* re-registering anything. `detach` disposes the scope and releases the wiring
|
|
2917
|
+
* explicitly, and the next attach installs a fresh one over the surviving
|
|
2918
|
+
* session state.
|
|
2919
|
+
*
|
|
2920
|
+
* A failed mint is contained: the session keeps its hold on the shared mounts
|
|
2921
|
+
* (they are registered on the project scope, which is unaffected) and only
|
|
2922
|
+
* loses its own wiring, instead of failing the pass.
|
|
2923
|
+
*/
|
|
2924
|
+
private ensureSessionScope(agent: AgentLike, state: AgentState): void {
|
|
2925
|
+
if (state.scope !== undefined) return
|
|
2926
|
+
let scope: Pick<Scope, 'ctx' | 'dispose'>
|
|
2927
|
+
try {
|
|
2928
|
+
scope = this.mintScope(state.agent)
|
|
2929
|
+
} catch (error) {
|
|
2930
|
+
this.ctx.logger.warn(
|
|
2931
|
+
`project-mcp: minting the scope of session ${agent.id} failed: ${errorText(error)}`,
|
|
2932
|
+
)
|
|
2933
|
+
return
|
|
2934
|
+
}
|
|
2935
|
+
state.scope = scope
|
|
2936
|
+
// The guidance section is independent of activation: with activation off
|
|
2937
|
+
// every tool is listed and the section only names the mount, so it stays a
|
|
2938
|
+
// true statement either way.
|
|
2939
|
+
if (this.config.guidanceEnabled ?? DEFAULT_GUIDANCE_ENABLED) {
|
|
2940
|
+
try {
|
|
2941
|
+
state.guidanceDispose = installGuidance({
|
|
2942
|
+
ctx: scope.ctx as unknown as GuidanceContextLike,
|
|
2943
|
+
text: () => this.guidanceText(agent, state),
|
|
2944
|
+
onError: (error) => {
|
|
2945
|
+
this.ctx.logger.warn(
|
|
2946
|
+
`project-mcp: guidance section failed for session ${agent.id}: ${errorText(error)}`,
|
|
2947
|
+
)
|
|
2948
|
+
},
|
|
2949
|
+
})
|
|
2950
|
+
} catch (error) {
|
|
2951
|
+
this.ctx.logger.warn(
|
|
2952
|
+
`project-mcp: guidance wiring failed for session ${agent.id}: ${errorText(error)}`,
|
|
2953
|
+
)
|
|
2954
|
+
}
|
|
2955
|
+
}
|
|
2956
|
+
if (!(this.config.activationEnabled ?? DEFAULT_ACTIVATION_ENABLED)) return
|
|
2957
|
+
try {
|
|
2958
|
+
state.activationDispose = installActivation({
|
|
2959
|
+
ctx: scope.ctx as unknown as ActivationContextLike,
|
|
2960
|
+
state: () => this.seedActivation(state),
|
|
2961
|
+
setState: (next) => {
|
|
2962
|
+
state.activation = next
|
|
2963
|
+
},
|
|
2964
|
+
available: () => this.activationCandidates(state),
|
|
2965
|
+
visible: () => this.visibleSchemas(state),
|
|
2966
|
+
foreign: () => this.foreignNamesOf(state),
|
|
2967
|
+
// The policy is read at every assembly rather than captured here, so a
|
|
2968
|
+
// mode or pin stored from the panel applies from the next model step on
|
|
2969
|
+
// without re-minting the scope the listener lives in.
|
|
2970
|
+
policy: () => this.policyFor(state.projectRoot),
|
|
2971
|
+
// The step the session is on, read when a search activates names: the
|
|
2972
|
+
// wiring keeps no counter of its own, because an activation outlives
|
|
2973
|
+
// the scope the wiring lives in and its stamp has to outlive it too.
|
|
2974
|
+
step: () => state.step,
|
|
2975
|
+
onActivated: (names, step) => {
|
|
2976
|
+
for (const name of names) state.steps.set(name, step)
|
|
2977
|
+
},
|
|
2978
|
+
onCompaction: () => {
|
|
2979
|
+
state.steps.clear()
|
|
2980
|
+
},
|
|
2981
|
+
autoState: state.auto ?? createAutoOfferState(),
|
|
2982
|
+
setAutoState: (next) => {
|
|
2983
|
+
state.auto = next
|
|
2984
|
+
},
|
|
2985
|
+
...(this.config.activationAutoLimit === undefined
|
|
2986
|
+
? {}
|
|
2987
|
+
: { autoLimit: this.config.activationAutoLimit }),
|
|
2988
|
+
...(this.config.activationAutoStickySteps === undefined
|
|
2989
|
+
? {}
|
|
2990
|
+
: { autoStickySteps: this.config.activationAutoStickySteps }),
|
|
2991
|
+
...(this.config.activationToolBudgetChars === undefined
|
|
2992
|
+
? {}
|
|
2993
|
+
: { toolBudgetChars: this.config.activationToolBudgetChars }),
|
|
2994
|
+
onError: (error) => {
|
|
2995
|
+
this.ctx.logger.warn(
|
|
2996
|
+
`project-mcp: activation failed for session ${agent.id}: ${errorText(error)}`,
|
|
2997
|
+
)
|
|
2998
|
+
},
|
|
2999
|
+
})
|
|
3000
|
+
} catch (error) {
|
|
3001
|
+
this.ctx.logger.warn(
|
|
3002
|
+
`project-mcp: activation wiring failed for session ${agent.id}: ${errorText(error)}`,
|
|
3003
|
+
)
|
|
3004
|
+
}
|
|
3005
|
+
}
|
|
3006
|
+
|
|
3007
|
+
/**
|
|
3008
|
+
* The session's activation state, seeded from its project's counters on first
|
|
3009
|
+
* use. Later scopes of the same session keep it; only a project change or a
|
|
3010
|
+
* teardown drops it.
|
|
3011
|
+
*/
|
|
3012
|
+
private seedActivation(state: AgentState): ActivationState {
|
|
3013
|
+
const existing = state.activation
|
|
3014
|
+
if (existing !== undefined) return existing
|
|
3015
|
+
const projectRoot = state.projectRoot
|
|
3016
|
+
const usage = projectRoot === undefined ? undefined : this.options.usage?.forProject(projectRoot)
|
|
3017
|
+
const seeded = createActivationState(
|
|
3018
|
+
seedFromUsage(usage, {
|
|
3019
|
+
count: this.config.activationSeeded ?? DEFAULT_ACTIVATION_SEEDED,
|
|
3020
|
+
minCalls: this.config.activationMinCalls ?? DEFAULT_ACTIVATION_MIN_CALLS,
|
|
3021
|
+
}),
|
|
3022
|
+
)
|
|
3023
|
+
state.activation = seeded
|
|
3024
|
+
return seeded
|
|
3025
|
+
}
|
|
3026
|
+
|
|
3027
|
+
/**
|
|
3028
|
+
* The schemas this plugin may offer this session: exactly the tools whose
|
|
3029
|
+
* public name belongs to a server it mounted for this agent's project. A
|
|
3030
|
+
* profile-level or other-project tool is never a candidate, and the prefix is
|
|
3031
|
+
* never parsed blindly — the runtime's own mount records decide.
|
|
3032
|
+
*/
|
|
3033
|
+
private activationCandidates(state: AgentState): ToolSchemaLike[] {
|
|
3034
|
+
const servers = this.runtimeNamesOf(state)
|
|
3035
|
+
if (servers.size === 0) return []
|
|
3036
|
+
return this.mountedSchemas(state)
|
|
3037
|
+
.filter((schema) => matchServer(schema.name, servers) !== undefined)
|
|
3038
|
+
}
|
|
3039
|
+
|
|
3040
|
+
/**
|
|
3041
|
+
* The schemas the session's own mount home publishes, read through the home's
|
|
3042
|
+
* scope key rather than the session's.
|
|
3043
|
+
*
|
|
3044
|
+
* The two are the same catalog by construction: a session that joined the
|
|
3045
|
+
* project's chain resolves the project's layer, and a session that could not
|
|
3046
|
+
* gets exactly those tools forwarded into its own layer. Reading the home's
|
|
3047
|
+
* view is what keeps this probe independent of the forwarding timing — a
|
|
3048
|
+
* server is up as soon as its tools are registered on the project scope, and
|
|
3049
|
+
* a bridge sync that has not run yet must not read as "not up".
|
|
3050
|
+
* @param state - the session whose home is probed.
|
|
3051
|
+
* @returns the visible schemas of its home, or none while it holds nothing.
|
|
3052
|
+
*/
|
|
3053
|
+
private mountedSchemas(state: AgentState): ToolSchemaLike[] {
|
|
3054
|
+
const home = this.homeOf(state)
|
|
3055
|
+
if (home === undefined) return []
|
|
3056
|
+
// A bridge is kept level by the mount, activation and `tools/change`
|
|
3057
|
+
// signals; this is the same sync on the read path, so a session's own layer
|
|
3058
|
+
// can never lag behind the catalog this probe returns. Unchanged names
|
|
3059
|
+
// short-circuit inside, so the cost is one name comparison.
|
|
3060
|
+
this.syncBridge(state)
|
|
3061
|
+
try {
|
|
3062
|
+
return this.ctx.tools.schemas(home.key)
|
|
3063
|
+
} catch (error) {
|
|
3064
|
+
this.ctx.logger.warn(
|
|
3065
|
+
`project-mcp: reading the tool catalog of session ${state.agent.id} failed: ${errorText(error)}`,
|
|
3066
|
+
)
|
|
3067
|
+
return []
|
|
3068
|
+
}
|
|
3069
|
+
}
|
|
3070
|
+
|
|
3071
|
+
/**
|
|
3072
|
+
* Every MCP schema the session's own scope chain resolves beyond this
|
|
3073
|
+
* plugin's project mounts: the profile plane and any F-19 forwarders. Read
|
|
3074
|
+
* through the session's key rather than the home's, so the deferral budget
|
|
3075
|
+
* and the discovery tool measure the whole surface the request actually
|
|
3076
|
+
* carries. Only `mcp__`-prefixed names enter, and the discovery tool is left
|
|
3077
|
+
* out by value — not by prefix — so the activation wiring can offer it on its
|
|
3078
|
+
* own. The per-server usage counters stay on the project plane: this probe
|
|
3079
|
+
* reads the catalog, never the counters.
|
|
3080
|
+
*
|
|
3081
|
+
* @param state - the session whose visible surface is probed.
|
|
3082
|
+
* @returns the visible MCP schemas, or none when the read fails.
|
|
3083
|
+
*/
|
|
3084
|
+
private visibleSchemas(state: AgentState): ToolSchemaLike[] {
|
|
3085
|
+
try {
|
|
3086
|
+
return this.ctx.tools.schemas(state.agent).filter(
|
|
3087
|
+
(schema) => schema.name.startsWith('mcp__') && schema.name !== SEARCH_TOOL_NAME,
|
|
3088
|
+
)
|
|
3089
|
+
} catch (error) {
|
|
3090
|
+
this.ctx.logger.warn(
|
|
3091
|
+
`project-mcp: reading the visible MCP surface of session ${state.agent.id} failed: ${errorText(error)}`,
|
|
3092
|
+
)
|
|
3093
|
+
return []
|
|
3094
|
+
}
|
|
3095
|
+
}
|
|
3096
|
+
|
|
3097
|
+
/**
|
|
3098
|
+
* The MCP tool names this session must never be offered: everything another
|
|
3099
|
+
* project mounted in this process publishes. The union is read through each
|
|
3100
|
+
* other project's own scope key — not the session's — so a name the host
|
|
3101
|
+
* defect leaked into the session's chain is caught here by provenance rather
|
|
3102
|
+
* than by prefix. Conservative, so a name the session may legitimately see is
|
|
3103
|
+
* never marked foreign: the set subtracts the session's own project's runtime
|
|
3104
|
+
* names and every profile-level server name (a profile entry is none of this
|
|
3105
|
+
* plugin's business even when another project declares the same name).
|
|
3106
|
+
* @param state - the session whose request is being assembled.
|
|
3107
|
+
* @returns the foreign tool names, or none when the read fails.
|
|
3108
|
+
*/
|
|
3109
|
+
private foreignNamesOf(state: AgentState): ReadonlySet<string> {
|
|
3110
|
+
const own = this.runtimeNamesOf(state)
|
|
3111
|
+
const profile = this.profileServerNames()
|
|
3112
|
+
const legitimate = new Set<string>([...own, ...profile])
|
|
3113
|
+
const foreign = new Set<string>()
|
|
3114
|
+
for (const project of this.projects.values()) {
|
|
3115
|
+
if (project.projectRoot === state.projectRoot) continue
|
|
3116
|
+
let schemas: ToolSchemaLike[]
|
|
3117
|
+
try {
|
|
3118
|
+
schemas = this.ctx.tools.schemas(project.key)
|
|
3119
|
+
} catch (error) {
|
|
3120
|
+
this.ctx.logger.warn(
|
|
3121
|
+
`project-mcp: reading another project's catalog for session ${state.agent.id} failed: ${errorText(error)}`,
|
|
3122
|
+
)
|
|
3123
|
+
continue
|
|
3124
|
+
}
|
|
3125
|
+
for (const schema of schemas) {
|
|
3126
|
+
if (!schema.name.startsWith('mcp__')) continue
|
|
3127
|
+
if (matchServer(schema.name, legitimate) !== undefined) continue
|
|
3128
|
+
foreign.add(schema.name)
|
|
3129
|
+
}
|
|
3130
|
+
}
|
|
3131
|
+
return foreign
|
|
3132
|
+
}
|
|
3133
|
+
|
|
3134
|
+
/**
|
|
3135
|
+
* The live text of the session's guidance section.
|
|
3136
|
+
*
|
|
3137
|
+
* It reads the mount records and the registry at every assembly, so a rescan
|
|
3138
|
+
* that mounted or dropped a server — and a search that activated a tool — are
|
|
3139
|
+
* reflected without re-registering the section. Total: any failure returns the
|
|
3140
|
+
* empty string, because a section that throws would fail the model request
|
|
3141
|
+
* that asked for the assembly.
|
|
3142
|
+
*/
|
|
3143
|
+
private guidanceText(agent: AgentLike, state: AgentState): string {
|
|
3144
|
+
try {
|
|
3145
|
+
const projectRoot = state.projectRoot
|
|
3146
|
+
if (projectRoot === undefined || this.mountsOf(state).size === 0) return ''
|
|
3147
|
+
const activationEnabled = this.config.activationEnabled ?? DEFAULT_ACTIVATION_ENABLED
|
|
3148
|
+
// With activation on, the presented set is the session's counter baseline
|
|
3149
|
+
// plus its activations; with it off, the registry lists every tool.
|
|
3150
|
+
const presented = activationEnabled ? presentedNames(this.seedActivation(state)) : undefined
|
|
3151
|
+
// Matched by the name each mount registers under, never by its declared
|
|
3152
|
+
// one: a shadowed declaration carries a local alias, and a registry lookup
|
|
3153
|
+
// by the contested name would drop its tools from the count.
|
|
3154
|
+
const mounted = new Set([...this.mountsOf(state).values()].map((mount) => mount.runtimeName))
|
|
3155
|
+
const toolsByServer = new Map<string, string[]>()
|
|
3156
|
+
const offered: string[] = []
|
|
3157
|
+
const deferred: string[] = []
|
|
3158
|
+
for (const schema of this.mountedSchemas(state)) {
|
|
3159
|
+
const server = matchServer(schema.name, mounted)
|
|
3160
|
+
if (server === undefined) continue
|
|
3161
|
+
const name = schema.name.slice(`mcp__${server}__`.length)
|
|
3162
|
+
const tools = toolsByServer.get(server)
|
|
3163
|
+
if (tools === undefined) toolsByServer.set(server, [name])
|
|
3164
|
+
else tools.push(name)
|
|
3165
|
+
if (presented === undefined || presented.has(schema.name)) offered.push(name)
|
|
3166
|
+
else deferred.push(name)
|
|
3167
|
+
}
|
|
3168
|
+
const servers: GuidanceServer[] = [...this.mountsOf(state).values()].map((mount) => ({
|
|
3169
|
+
name: mount.name,
|
|
3170
|
+
status: mount.status,
|
|
3171
|
+
...(mount.transport === undefined ? {} : { transport: mount.transport }),
|
|
3172
|
+
tools: toolsByServer.get(mount.runtimeName) ?? [],
|
|
3173
|
+
}))
|
|
3174
|
+
// The seeded baseline's insertion order is the usage rank order
|
|
3175
|
+
// (most-called first); keep it and strip the server prefix, so the
|
|
3176
|
+
// guidance names the session's hot tools like every other short name.
|
|
3177
|
+
const mostUsed: string[] = []
|
|
3178
|
+
if (activationEnabled) {
|
|
3179
|
+
for (const fullName of this.seedActivation(state).baseline) {
|
|
3180
|
+
const server = matchServer(fullName, mounted)
|
|
3181
|
+
if (server !== undefined) mostUsed.push(fullName.slice(`mcp__${server}__`.length))
|
|
3182
|
+
}
|
|
3183
|
+
}
|
|
3184
|
+
return buildGuidance({
|
|
3185
|
+
project: projectLabel(projectRoot, homedir()),
|
|
3186
|
+
servers,
|
|
3187
|
+
offered,
|
|
3188
|
+
deferred,
|
|
3189
|
+
mostUsed,
|
|
3190
|
+
activationEnabled,
|
|
3191
|
+
})
|
|
3192
|
+
} catch (error) {
|
|
3193
|
+
this.ctx.logger.warn(
|
|
3194
|
+
`project-mcp: building guidance for session ${agent.id} failed: ${errorText(error)}`,
|
|
3195
|
+
)
|
|
3196
|
+
return ''
|
|
3197
|
+
}
|
|
3198
|
+
}
|
|
3199
|
+
|
|
3200
|
+
/**
|
|
3201
|
+
* Refresh the freshness of a tool a session actually called. It rides the same
|
|
3202
|
+
* `tools/result` subscription the counters use, so no second observer exists.
|
|
3203
|
+
* @param agentId - calling agent, when the call was agent-scoped.
|
|
3204
|
+
* @param toolName - public registry name of the call.
|
|
3205
|
+
*/
|
|
3206
|
+
noteToolUse(agentId: string | undefined, toolName: string): void {
|
|
3207
|
+
if (agentId === undefined) return
|
|
3208
|
+
const state = this.states.get(agentId)
|
|
3209
|
+
if (state?.activation === undefined) return
|
|
3210
|
+
state.activation = noteUse(state.activation, toolName, Date.now())
|
|
3211
|
+
}
|
|
3212
|
+
|
|
3213
|
+
/** Drop the session-activated tools that outlived `toolIdleMs` without a call. */
|
|
3214
|
+
private pruneActivation(state: AgentState): void {
|
|
3215
|
+
const current = state.activation
|
|
3216
|
+
if (current === undefined) return
|
|
3217
|
+
state.activation = pruneIdle(current, Date.now(), this.config.toolIdleMs ?? DEFAULT_TOOL_IDLE_MS)
|
|
3218
|
+
// A step record belongs to the activation it was made for, so a name that
|
|
3219
|
+
// fell out of the window takes its record with it; one that returns is
|
|
3220
|
+
// stamped again with the step it returns on.
|
|
3221
|
+
if (state.activation !== current) {
|
|
3222
|
+
for (const name of [...state.steps.keys()]) {
|
|
3223
|
+
if (!state.activation.active.has(name)) state.steps.delete(name)
|
|
3224
|
+
}
|
|
3225
|
+
}
|
|
3226
|
+
}
|
|
3227
|
+
|
|
3228
|
+
private async unmount(home: MountHome, name: string, reason: CodedText): Promise<void> {
|
|
3229
|
+
const mount = home.mounts.get(name)
|
|
3230
|
+
if (mount === undefined) return
|
|
3231
|
+
home.mounts.delete(name)
|
|
3232
|
+
this.logUnmount(home, mount, reason)
|
|
3233
|
+
await this.disposeFiber(mount)
|
|
3234
|
+
}
|
|
3235
|
+
|
|
3236
|
+
/**
|
|
3237
|
+
* The line that closes a mount's life, the pair of the `mounting` line.
|
|
3238
|
+
*
|
|
3239
|
+
* The reason is the part a reader cannot infer from the log's order: an edit,
|
|
3240
|
+
* an idle release, an operator retry and a session teardown all unmount, and
|
|
3241
|
+
* only some of them are followed by a mount of the same server. The run time
|
|
3242
|
+
* tells a server that never came up from one that served and was replaced.
|
|
3243
|
+
* @param home - the home the instance lived in.
|
|
3244
|
+
* @param mount - the instance going away.
|
|
3245
|
+
* @param reason - why it is going away: the operator's sentence and its wire
|
|
3246
|
+
* code (F-48), nested two-level into the `unmounting` event as `reasonCode`.
|
|
3247
|
+
*/
|
|
3248
|
+
private logUnmount(home: MountHome, mount: MountedInstance, reason: CodedText): void {
|
|
3249
|
+
const now = Date.now()
|
|
3250
|
+
const ran = formatDuration(now - mount.startedAt)
|
|
3251
|
+
// `unmounting` after a failure is the tail of that failure, so the tab keeps
|
|
3252
|
+
// it red; every other release is a warning. The instance serves every session
|
|
3253
|
+
// of its project, so its release is a project event that names no session.
|
|
3254
|
+
this.logLifecycle({
|
|
3255
|
+
at: now,
|
|
3256
|
+
level: mount.failed ? 'error' : 'warn',
|
|
3257
|
+
logLevel: 'info',
|
|
3258
|
+
projectRoot: mount.projectRoot,
|
|
3259
|
+
server: mount.name,
|
|
3260
|
+
message: `unmounting — ${reason.text} (it ran for ${ran})`,
|
|
3261
|
+
code: 'unmounting',
|
|
3262
|
+
params: { reasonCode: reason.code, ran },
|
|
3263
|
+
...(mount.detail === undefined ? {} : { detail: mount.detail }),
|
|
3264
|
+
...(mount.detailCode === undefined ? {} : { detailCode: mount.detailCode }),
|
|
3265
|
+
...(mount.detailParams === undefined ? {} : { detailParams: mount.detailParams }),
|
|
3266
|
+
line: `unmounting ${mount.name} in ${home.projectRoot} — ${reason.text} (it ran for ${ran})`,
|
|
3267
|
+
})
|
|
3268
|
+
}
|
|
3269
|
+
|
|
3270
|
+
/**
|
|
3271
|
+
* Bring every foreign holder of one home level with its live tools.
|
|
3272
|
+
*
|
|
3273
|
+
* The mount and unmount sites call this because they are the moments the
|
|
3274
|
+
* project's tool set actually changes: a session's own pass can run before the
|
|
3275
|
+
* server it shares has published anything (its own mount is only registered
|
|
3276
|
+
* after the hold), and this is what fills its forwarders in behind it. The
|
|
3277
|
+
* `tools/change` subscription and the read-path sync cover the same event on
|
|
3278
|
+
* a real registry; a third trigger costs nothing, because an unchanged name
|
|
3279
|
+
* set short-circuits.
|
|
3280
|
+
* @param home - the home whose tools changed.
|
|
3281
|
+
*/
|
|
3282
|
+
private syncBridgesOf(home: MountHome): void {
|
|
3283
|
+
for (const state of this.states.values()) {
|
|
3284
|
+
if (state.bridge !== undefined && state.project === home) this.syncBridge(state)
|
|
3285
|
+
}
|
|
3286
|
+
}
|
|
3287
|
+
|
|
3288
|
+
private async disposeFiber(mount: MountedInstance): Promise<void> {
|
|
3289
|
+
const fiber = mount.fiber
|
|
3290
|
+
mount.fiber = undefined
|
|
3291
|
+
if (fiber === undefined) return
|
|
3292
|
+
const outcome = await this.waitFor(
|
|
3293
|
+
`disposal of ${mount.name}`,
|
|
3294
|
+
Promise.resolve().then(() => fiber.dispose()),
|
|
3295
|
+
)
|
|
3296
|
+
if (outcome.kind === 'failed') {
|
|
3297
|
+
this.ctx.logger.warn(`project-mcp: disposing ${mount.name} failed: ${errorText(outcome.error)}`)
|
|
3298
|
+
}
|
|
3299
|
+
}
|
|
3300
|
+
|
|
3301
|
+
/**
|
|
3302
|
+
* Refresh `active`/`connecting` from the tools actually visible to the agent,
|
|
3303
|
+
* and turn a mount that never produced a tool into a detailed `error` row.
|
|
3304
|
+
* The watchdog is strictly read-only: it never disposes a slow server, and a
|
|
3305
|
+
* mount that connects later returns to `active` on its own.
|
|
3306
|
+
*/
|
|
3307
|
+
private refreshStatuses(agent: AgentLike, state: AgentState): void {
|
|
3308
|
+
const timeout = this.config.connectTimeoutMs
|
|
3309
|
+
const now = Date.now()
|
|
3310
|
+
for (const mount of this.mountsOf(state).values()) {
|
|
3311
|
+
// Activation failed outright: the fiber is dead, so there is nothing to
|
|
3312
|
+
// poll and nothing to revive without a new mount (`projectMcp.retry()`).
|
|
3313
|
+
if (mount.failed) continue
|
|
3314
|
+
if (this.hasTools(state, mount.runtimeName)) {
|
|
3315
|
+
if (mount.status !== 'active') {
|
|
3316
|
+
const elapsed = formatDuration(now - mount.startedAt)
|
|
3317
|
+
// Success is an event of its own level: the tab draws it green, not as
|
|
3318
|
+
// one more info line, and the line names the session that sees it.
|
|
3319
|
+
this.logLifecycle({
|
|
3320
|
+
at: now,
|
|
3321
|
+
level: 'up',
|
|
3322
|
+
logLevel: 'info',
|
|
3323
|
+
projectRoot: mount.projectRoot,
|
|
3324
|
+
sessionId: agent.id,
|
|
3325
|
+
server: mount.name,
|
|
3326
|
+
message: `is up — tools visible to session ${agent.id} after ${elapsed}`,
|
|
3327
|
+
code: 'mount.up',
|
|
3328
|
+
params: { sessionId: agent.id, elapsed },
|
|
3329
|
+
line: `${mount.name} is up in ${state.projectRoot ?? 'the project'} — its tools are visible to session ${agent.id} after ${elapsed}`,
|
|
3330
|
+
})
|
|
3331
|
+
}
|
|
3332
|
+
mount.status = 'active'
|
|
3333
|
+
mount.detail = undefined
|
|
3334
|
+
mount.detailCode = undefined
|
|
3335
|
+
mount.detailParams = undefined
|
|
3336
|
+
mount.stalled = false
|
|
3337
|
+
continue
|
|
3338
|
+
}
|
|
3339
|
+
const elapsed = now - mount.startedAt
|
|
3340
|
+
if (timeout > 0 && elapsed >= timeout) {
|
|
3341
|
+
const firstReport = !mount.stalled
|
|
3342
|
+
mount.status = 'error'
|
|
3343
|
+
mount.stalled = true
|
|
3344
|
+
const stall = stallDetail(mount, elapsed)
|
|
3345
|
+
mount.detail = stall.text
|
|
3346
|
+
mount.detailCode = stall.code
|
|
3347
|
+
mount.detailParams = stall.params
|
|
3348
|
+
if (firstReport) {
|
|
3349
|
+
// Reported once per stall (the watchdog re-reads it every pass), with
|
|
3350
|
+
// the three facts the row shows and no retry advice.
|
|
3351
|
+
this.logLifecycle({
|
|
3352
|
+
at: now,
|
|
3353
|
+
level: 'warn',
|
|
3354
|
+
logLevel: 'warn',
|
|
3355
|
+
projectRoot: mount.projectRoot,
|
|
3356
|
+
sessionId: agent.id,
|
|
3357
|
+
server: mount.name,
|
|
3358
|
+
message: `no tool appeared in ${formatDuration(elapsed)}`,
|
|
3359
|
+
code: 'mount.stalled',
|
|
3360
|
+
params: { elapsed: formatDuration(elapsed) },
|
|
3361
|
+
detail: stall.text,
|
|
3362
|
+
detailCode: stall.code,
|
|
3363
|
+
...(stall.params === undefined ? {} : { detailParams: stall.params }),
|
|
3364
|
+
line: stall.text,
|
|
3365
|
+
})
|
|
3366
|
+
}
|
|
3367
|
+
continue
|
|
3368
|
+
}
|
|
3369
|
+
mount.status = 'connecting'
|
|
3370
|
+
mount.stalled = false
|
|
3371
|
+
mount.detail = undefined
|
|
3372
|
+
mount.detailCode = undefined
|
|
3373
|
+
mount.detailParams = undefined
|
|
3374
|
+
}
|
|
3375
|
+
}
|
|
3376
|
+
|
|
3377
|
+
/**
|
|
3378
|
+
* The session's rows with their live mount state applied.
|
|
3379
|
+
*
|
|
3380
|
+
* Read-time, not stored: a mount that appears, connects or fails between two
|
|
3381
|
+
* passes changes what a panel must show, while the row belongs to the pass
|
|
3382
|
+
* that last re-derived it. Decorating here is what lets the status channel
|
|
3383
|
+
* report a mount the moment the pass creates it, rather than when that pass
|
|
3384
|
+
* finally returns.
|
|
3385
|
+
* @param state - the session whose rows to read.
|
|
3386
|
+
* @returns one row per declaration, in document order.
|
|
3387
|
+
*/
|
|
3388
|
+
private liveRows(state: AgentState): ServerRow[] {
|
|
3389
|
+
const mounts = this.mountsOf(state)
|
|
3390
|
+
return state.rows.map((row) => decorate(row, mounts.get(row.name)))
|
|
3391
|
+
}
|
|
3392
|
+
|
|
3393
|
+
/** Mount failures of this pass, published as first-class snapshot issues. */
|
|
3394
|
+
private mountDiagnostics(state: AgentState, projectRoot: string): SnapshotIssue[] {
|
|
3395
|
+
const diagnostics: SnapshotIssue[] = []
|
|
3396
|
+
for (const mount of this.mountsOf(state).values()) {
|
|
3397
|
+
if (mount.status !== 'error' || mount.detail === undefined) continue
|
|
3398
|
+
diagnostics.push({
|
|
3399
|
+
source: mount.source ?? projectRoot,
|
|
3400
|
+
server: mount.name,
|
|
3401
|
+
level: 'error',
|
|
3402
|
+
message: mount.detail,
|
|
3403
|
+
// The detail's wire companions ride along, so the issue translates the
|
|
3404
|
+
// same way the event's detail does (F-48).
|
|
3405
|
+
...(mount.detailCode === undefined ? {} : { code: mount.detailCode }),
|
|
3406
|
+
...(mount.detailParams === undefined ? {} : { params: mount.detailParams }),
|
|
3407
|
+
})
|
|
3408
|
+
}
|
|
3409
|
+
return diagnostics
|
|
3410
|
+
}
|
|
3411
|
+
|
|
3412
|
+
private hasTools(state: AgentState, serverName: string): boolean {
|
|
3413
|
+
const prefix = `mcp__${serverName}__`
|
|
3414
|
+
return this.mountedSchemas(state).some((schema) => schema.name.startsWith(prefix))
|
|
3415
|
+
}
|
|
3416
|
+
|
|
3417
|
+
/**
|
|
3418
|
+
* Global documents of this deployment, lowest priority first. Read before a
|
|
3419
|
+
* project's own documents, so a project declaration always wins.
|
|
3420
|
+
*/
|
|
3421
|
+
private globalFiles(): string[] {
|
|
3422
|
+
return globalConfigPaths(this.config.globalFiles)
|
|
3423
|
+
}
|
|
3424
|
+
|
|
3425
|
+
/**
|
|
3426
|
+
* Every document one project is configured to read, in priority order — the
|
|
3427
|
+
* order they are read in, which is what the panel's `priority n/total` counts.
|
|
3428
|
+
*/
|
|
3429
|
+
private readFiles(projectRoot: string): ConfiguredFile[] {
|
|
3430
|
+
return [
|
|
3431
|
+
...this.globalFiles().map((path): ConfiguredFile => ({ path, scope: 'global' })),
|
|
3432
|
+
...localConfigPaths(projectRoot, this.config.localFiles).map(
|
|
3433
|
+
(path): ConfiguredFile => ({ path, scope: 'project' }),
|
|
3434
|
+
),
|
|
3435
|
+
]
|
|
3436
|
+
}
|
|
3437
|
+
|
|
3438
|
+
private readProject(projectRoot: string): {
|
|
3439
|
+
entries: ParsedEntry[]
|
|
3440
|
+
issues: ParseIssue[]
|
|
3441
|
+
documents: Map<string, DocumentInfo>
|
|
3442
|
+
/**
|
|
3443
|
+
* Every document that declared each `serverName`, in declaration order —
|
|
3444
|
+
* lowest priority first, exactly the order {@link mergeEntries} applies, so
|
|
3445
|
+
* the winner of a duplicated name is the last path recorded here.
|
|
3446
|
+
*/
|
|
3447
|
+
sources: Map<string, string[]>
|
|
3448
|
+
} {
|
|
3449
|
+
const paths = [...this.globalFiles(), ...localConfigPaths(projectRoot, this.config.localFiles)]
|
|
3450
|
+
const resolveContext = this.resolveContext(projectRoot)
|
|
3451
|
+
const groups: ParsedEntry[][] = []
|
|
3452
|
+
const issues: ParseIssue[] = []
|
|
3453
|
+
const documents = new Map<string, DocumentInfo>()
|
|
3454
|
+
const sources = new Map<string, string[]>()
|
|
3455
|
+
for (const path of paths) {
|
|
3456
|
+
const document = this.readDocument(path, resolveContext)
|
|
3457
|
+
if (document === undefined) continue
|
|
3458
|
+
groups.push(document.entries)
|
|
3459
|
+
issues.push(...document.issues)
|
|
3460
|
+
documents.set(path, this.documentInfo(path, projectRoot, document, resolveContext))
|
|
3461
|
+
for (const entry of document.entries) {
|
|
3462
|
+
const declared = sources.get(entry.name)
|
|
3463
|
+
if (declared === undefined) sources.set(entry.name, [path])
|
|
3464
|
+
else if (!declared.includes(path)) declared.push(path)
|
|
3465
|
+
}
|
|
3466
|
+
}
|
|
3467
|
+
const { entries, overridden } = mergeEntries(groups)
|
|
3468
|
+
for (const name of new Set(overridden)) {
|
|
3469
|
+
issues.push({
|
|
3470
|
+
source: projectRoot,
|
|
3471
|
+
server: name,
|
|
3472
|
+
level: 'warning',
|
|
3473
|
+
message: `serverName "${name}" was declared in more than one document; the highest-priority definition wins`,
|
|
3474
|
+
// The code the client's file grouping compares — never the prose,
|
|
3475
|
+
// which the client may have translated.
|
|
3476
|
+
code: 'parse.server.multiDocument',
|
|
3477
|
+
params: { name },
|
|
3478
|
+
})
|
|
3479
|
+
}
|
|
3480
|
+
return { entries, issues, documents, sources }
|
|
3481
|
+
}
|
|
3482
|
+
|
|
3483
|
+
/**
|
|
3484
|
+
* Everything the editor needs about one declaring document: its revision and
|
|
3485
|
+
* write tier, plus the entry body of each server that parsed.
|
|
3486
|
+
*/
|
|
3487
|
+
private documentInfo(
|
|
3488
|
+
path: string,
|
|
3489
|
+
projectRoot: string,
|
|
3490
|
+
document: CachedDocument,
|
|
3491
|
+
resolveContext: ResolveContext,
|
|
3492
|
+
): DocumentInfo {
|
|
3493
|
+
const entries = new Map<string, EntrySnapshot>()
|
|
3494
|
+
const declared = document.raw
|
|
3495
|
+
if (declared !== undefined) {
|
|
3496
|
+
const byName = new Map<string, unknown>()
|
|
3497
|
+
for (const [key, value] of Object.entries(declared)) {
|
|
3498
|
+
const name = SERVER_NAME_PATTERN.test(key) ? key : slugifyServerName(key)
|
|
3499
|
+
if (name !== '') byName.set(name, value)
|
|
3500
|
+
}
|
|
3501
|
+
for (const entry of document.entries) {
|
|
3502
|
+
if (entry.config === undefined) continue
|
|
3503
|
+
const raw = byName.get(entry.name)
|
|
3504
|
+
entries.set(entry.name, buildEntrySnapshot(raw, entry.config.transport, credentialKeys(raw, resolveContext)))
|
|
3505
|
+
}
|
|
3506
|
+
}
|
|
3507
|
+
const scope = writeScopeFor(path, projectRoot, {
|
|
3508
|
+
projectDocuments: localConfigPaths(projectRoot, this.config.localFiles),
|
|
3509
|
+
globalDocuments: this.globalFiles(),
|
|
3510
|
+
allowGlobalWrite: this.config.allowGlobalWrite === true,
|
|
3511
|
+
})
|
|
3512
|
+
return { revision: documentRevision(document.text), entries, ...scope }
|
|
3513
|
+
}
|
|
3514
|
+
|
|
3515
|
+
private readDocument(path: string, resolveContext: ResolveContext): CachedDocument | undefined {
|
|
3516
|
+
let stats
|
|
3517
|
+
try {
|
|
3518
|
+
stats = statSync(path)
|
|
3519
|
+
} catch {
|
|
3520
|
+
this.documents.delete(path)
|
|
3521
|
+
return undefined
|
|
3522
|
+
}
|
|
3523
|
+
const cached = this.documents.get(path)
|
|
3524
|
+
if (
|
|
3525
|
+
cached !== undefined &&
|
|
3526
|
+
cached.mtimeMs === stats.mtimeMs &&
|
|
3527
|
+
cached.size === stats.size &&
|
|
3528
|
+
cached.stamp === (resolveContext.stamp ?? '')
|
|
3529
|
+
) {
|
|
3530
|
+
return cached
|
|
3531
|
+
}
|
|
3532
|
+
let text: string
|
|
3533
|
+
try {
|
|
3534
|
+
text = readFileSync(path, 'utf8')
|
|
3535
|
+
} catch {
|
|
3536
|
+
return undefined
|
|
3537
|
+
}
|
|
3538
|
+
const parsed = parseDocument(text, path, resolveContext)
|
|
3539
|
+
let raw: Record<string, unknown> | undefined
|
|
3540
|
+
try {
|
|
3541
|
+
raw = extractServerMap(JSON.parse(text) as unknown) ?? undefined
|
|
3542
|
+
} catch {
|
|
3543
|
+
// Invalid JSON: `parseDocument` already reported it per entry.
|
|
3544
|
+
raw = undefined
|
|
3545
|
+
}
|
|
3546
|
+
const document: CachedDocument = {
|
|
3547
|
+
mtimeMs: stats.mtimeMs,
|
|
3548
|
+
size: stats.size,
|
|
3549
|
+
text,
|
|
3550
|
+
stamp: resolveContext.stamp ?? '',
|
|
3551
|
+
raw,
|
|
3552
|
+
entries: parsed.entries,
|
|
3553
|
+
issues: parsed.issues,
|
|
3554
|
+
}
|
|
3555
|
+
this.documents.set(path, document)
|
|
3556
|
+
return document
|
|
3557
|
+
}
|
|
3558
|
+
|
|
3559
|
+
private resolveContext(projectRoot: string): ResolveContext {
|
|
3560
|
+
const dotenv = this.readProjectEnv(projectRoot)
|
|
3561
|
+
const secrets = this.readSecrets()
|
|
3562
|
+
return {
|
|
3563
|
+
env: process.env,
|
|
3564
|
+
dotenv: dotenv.values,
|
|
3565
|
+
inputs: this.config.inputs,
|
|
3566
|
+
secrets: secrets.values,
|
|
3567
|
+
stamp: `${dotenv.stamp}\u0001${secrets.stamp}`,
|
|
3568
|
+
projectRoot,
|
|
3569
|
+
toolCallTimeoutMs: this.config.toolCallTimeoutMs,
|
|
3570
|
+
failOnStartupError: this.config.failOnStartupError,
|
|
3571
|
+
}
|
|
3572
|
+
}
|
|
3573
|
+
|
|
3574
|
+
/**
|
|
3575
|
+
* The project's own dotenv values, plus the identity of the files they came
|
|
3576
|
+
* from. Documents are merged lowest priority first, so `<project>/.dsh/.env`
|
|
3577
|
+
* overrides the plain `<project>/.env`; each file is re-read only when its
|
|
3578
|
+
* mtime/size changes, and a file that is gone leaves both the map and the
|
|
3579
|
+
* stamp (so deleting `.env` un-resolves its references on the next pass).
|
|
3580
|
+
*/
|
|
3581
|
+
private readProjectEnv(projectRoot: string): { values: Record<string, string>; stamp: string } {
|
|
3582
|
+
const values: Record<string, string> = {}
|
|
3583
|
+
if (this.config.envFiles === false) return { values, stamp: '' }
|
|
3584
|
+
const parts: string[] = []
|
|
3585
|
+
for (const path of projectEnvPaths(projectRoot)) {
|
|
3586
|
+
let stats
|
|
3587
|
+
try {
|
|
3588
|
+
stats = statSync(path)
|
|
3589
|
+
} catch {
|
|
3590
|
+
this.envFiles.delete(path)
|
|
3591
|
+
continue
|
|
3592
|
+
}
|
|
3593
|
+
const cached = this.envFiles.get(path)
|
|
3594
|
+
const entry =
|
|
3595
|
+
cached !== undefined && cached.mtimeMs === stats.mtimeMs && cached.size === stats.size
|
|
3596
|
+
? cached
|
|
3597
|
+
: { mtimeMs: stats.mtimeMs, size: stats.size, values: readEnvFile(path) }
|
|
3598
|
+
this.envFiles.set(path, entry)
|
|
3599
|
+
Object.assign(values, entry.values)
|
|
3600
|
+
parts.push(`${path}:${entry.mtimeMs}:${entry.size}`)
|
|
3601
|
+
}
|
|
3602
|
+
return { values, stamp: parts.join('|') }
|
|
3603
|
+
}
|
|
3604
|
+
|
|
3605
|
+
/**
|
|
3606
|
+
* Credentials, re-read only when the document changes. Every pass of every
|
|
3607
|
+
* session resolves `${input:NAME}` references, so an uncached read here cost
|
|
3608
|
+
* one synchronous stat plus YAML parse per session per pass. The stamp is the
|
|
3609
|
+
* same identity the document cache compares.
|
|
3610
|
+
*/
|
|
3611
|
+
private readSecrets(): { values: Record<string, string>; stamp: string } {
|
|
3612
|
+
const path = this.config.credentialsFile
|
|
3613
|
+
let stats
|
|
3614
|
+
try {
|
|
3615
|
+
stats = statSync(path)
|
|
3616
|
+
} catch {
|
|
3617
|
+
this.secrets = undefined
|
|
3618
|
+
return { values: {}, stamp: '' }
|
|
3619
|
+
}
|
|
3620
|
+
const stamp = `${stats.mtimeMs}:${stats.size}`
|
|
3621
|
+
const cached = this.secrets
|
|
3622
|
+
if (cached !== undefined && cached.mtimeMs === stats.mtimeMs && cached.size === stats.size) {
|
|
3623
|
+
return { values: cached.values, stamp }
|
|
3624
|
+
}
|
|
3625
|
+
const values = readSecrets(path)
|
|
3626
|
+
this.secrets = { mtimeMs: stats.mtimeMs, size: stats.size, values }
|
|
3627
|
+
return { values, stamp }
|
|
3628
|
+
}
|
|
3629
|
+
|
|
3630
|
+
private profileServerNames(): Set<string> {
|
|
3631
|
+
const names = new Set<string>()
|
|
3632
|
+
let entries: LoaderEntryLike[] = []
|
|
3633
|
+
try {
|
|
3634
|
+
const loader = (this.ctx as unknown as { get(name: string): unknown }).get('loader') as
|
|
3635
|
+
| LoaderLike
|
|
3636
|
+
| undefined
|
|
3637
|
+
entries = loader?.entries?.() ?? []
|
|
3638
|
+
} catch {
|
|
3639
|
+
return names
|
|
3640
|
+
}
|
|
3641
|
+
for (const entry of entries) {
|
|
3642
|
+
const options = entry.options ?? {}
|
|
3643
|
+
if (options.disabled === true) continue
|
|
3644
|
+
if (!MCP_CLIENT_ENTRY_NAMES.has(String(options.name))) continue
|
|
3645
|
+
const name = options.config?.serverName
|
|
3646
|
+
if (typeof name !== 'string') continue
|
|
3647
|
+
if (entry.fiber?.state === FIBER_ACTIVE) names.add(name)
|
|
3648
|
+
}
|
|
3649
|
+
return names
|
|
3650
|
+
}
|
|
3651
|
+
|
|
3652
|
+
/**
|
|
3653
|
+
* The other loaded plugin that owns the assembled tool list, if the profile
|
|
3654
|
+
* has one.
|
|
3655
|
+
*
|
|
3656
|
+
* Read from the same `loader.entries()` this plugin already consults for the
|
|
3657
|
+
* reserved `serverName`s, for the same reason: the profile is where a second
|
|
3658
|
+
* owner is mounted, and a running entry is the only kind that shapes a
|
|
3659
|
+
* request. An entry named like a known presentation plugin but not active is
|
|
3660
|
+
* mounted-and-stopped, which shapes nothing, so it is reported no more than an
|
|
3661
|
+
* absent one is.
|
|
3662
|
+
*
|
|
3663
|
+
* @returns the owner, or `undefined` when this plugin assembles alone.
|
|
3664
|
+
*/
|
|
3665
|
+
private presentationOwner(): PresentationOwner | undefined {
|
|
3666
|
+
let entries: LoaderEntryLike[] = []
|
|
3667
|
+
try {
|
|
3668
|
+
const loader = (this.ctx as unknown as { get(name: string): unknown }).get('loader') as
|
|
3669
|
+
| LoaderLike
|
|
3670
|
+
| undefined
|
|
3671
|
+
entries = loader?.entries?.() ?? []
|
|
3672
|
+
} catch {
|
|
3673
|
+
return undefined
|
|
3674
|
+
}
|
|
3675
|
+
for (const entry of entries) {
|
|
3676
|
+
const options = entry.options ?? {}
|
|
3677
|
+
if (options.disabled === true) continue
|
|
3678
|
+
if (!PRESENTATION_OWNER_ENTRY_NAMES.has(String(options.name))) continue
|
|
3679
|
+
if (entry.fiber?.state !== FIBER_ACTIVE) continue
|
|
3680
|
+
// The module specifier is what the profile wrote down, so it is the most
|
|
3681
|
+
// useful label; the entry id disambiguates two mounts of one module and
|
|
3682
|
+
// stands in when a hand-written profile names the plugin by path.
|
|
3683
|
+
const name =
|
|
3684
|
+
typeof options.name === 'string' && options.name !== ''
|
|
3685
|
+
? options.name
|
|
3686
|
+
: typeof options.id === 'string'
|
|
3687
|
+
? options.id
|
|
3688
|
+
: ''
|
|
3689
|
+
return { name, note: PRESENTATION_OWNER_NOTE, noteCode: 'present.ownerNote' }
|
|
3690
|
+
}
|
|
3691
|
+
return undefined
|
|
3692
|
+
}
|
|
3693
|
+
|
|
3694
|
+
/**
|
|
3695
|
+
* Keep one watcher set per project with live agents. Only the project's own
|
|
3696
|
+
* document directories are watched recursively: an unrelated file storm
|
|
3697
|
+
* (install caches, build output, git metadata) never reaches this plugin, so
|
|
3698
|
+
* it costs no events and no passes. A flat watch on the project root notices
|
|
3699
|
+
* a config directory appearing or disappearing, and the rescan timer is the
|
|
3700
|
+
* safety net for anything else.
|
|
3701
|
+
*/
|
|
3702
|
+
private syncWatchers(): void {
|
|
3703
|
+
const roots = new Set<string>()
|
|
3704
|
+
for (const state of this.states.values()) {
|
|
3705
|
+
if (state.projectRoot !== undefined) roots.add(state.projectRoot)
|
|
3706
|
+
}
|
|
3707
|
+
for (const [root, watchers] of [...this.watchers]) {
|
|
3708
|
+
if (roots.has(root)) continue
|
|
3709
|
+
this.closeWatchers(root, watchers)
|
|
3710
|
+
}
|
|
3711
|
+
if (!this.config.watch) return
|
|
3712
|
+
for (const root of roots) {
|
|
3713
|
+
const existing = this.watchers.get(root)
|
|
3714
|
+
if (existing !== undefined) {
|
|
3715
|
+
const desired = this.watchTargets(root)
|
|
3716
|
+
if (sameTargets(this.watchedDirs.get(root) ?? [], desired)) continue
|
|
3717
|
+
this.closeWatchers(root, existing)
|
|
3718
|
+
}
|
|
3719
|
+
const targets = this.watchTargets(root)
|
|
3720
|
+
const watchers = this.watchProject(root, targets)
|
|
3721
|
+
if (watchers.length === 0) continue
|
|
3722
|
+
this.watchers.set(root, watchers)
|
|
3723
|
+
this.watchedDirs.set(root, targets)
|
|
3724
|
+
this.watchedRoots.add(root)
|
|
3725
|
+
}
|
|
3726
|
+
}
|
|
3727
|
+
|
|
3728
|
+
private closeWatchers(root: string, watchers: FSWatcher[]): void {
|
|
3729
|
+
for (const watcher of watchers) watcher.close()
|
|
3730
|
+
this.watchers.delete(root)
|
|
3731
|
+
this.watchedDirs.delete(root)
|
|
3732
|
+
this.watchedRoots.delete(root)
|
|
3733
|
+
}
|
|
3734
|
+
|
|
3735
|
+
/** Directories (and document files) worth watching for one root. */
|
|
3736
|
+
private watchTargets(root: string): WatchTarget[] {
|
|
3737
|
+
const targets: WatchTarget[] = []
|
|
3738
|
+
for (const directory of configDirectories(root, this.config.localFiles)) {
|
|
3739
|
+
if (directory !== root) targets.push({ path: directory, directory: true })
|
|
3740
|
+
}
|
|
3741
|
+
// A global document is watched as a file: watching its whole home directory
|
|
3742
|
+
// would put the watcher on every unrelated write under `$HOME`.
|
|
3743
|
+
for (const file of this.globalFiles()) targets.push({ path: file, directory: false })
|
|
3744
|
+
return targets
|
|
3745
|
+
}
|
|
3746
|
+
|
|
3747
|
+
private watchProject(root: string, targets: readonly WatchTarget[]): FSWatcher[] {
|
|
3748
|
+
const onChange = (): void => this.schedule('watch')
|
|
3749
|
+
const watchers: FSWatcher[] = []
|
|
3750
|
+
const add = (path: string, recursive: boolean): void => {
|
|
3751
|
+
try {
|
|
3752
|
+
const watcher = watch(path, { recursive, persistent: false }, onChange)
|
|
3753
|
+
watcher.on('error', () => undefined)
|
|
3754
|
+
watchers.push(watcher)
|
|
3755
|
+
} catch {
|
|
3756
|
+
// The target can disappear between the existence check and the watch.
|
|
3757
|
+
}
|
|
3758
|
+
}
|
|
3759
|
+
// Flat: catches a config directory appearing or disappearing.
|
|
3760
|
+
add(root, false)
|
|
3761
|
+
for (const target of targets) {
|
|
3762
|
+
if (!target.directory) {
|
|
3763
|
+
add(target.path, false)
|
|
3764
|
+
continue
|
|
3765
|
+
}
|
|
3766
|
+
if (this.recursiveWatch !== false) {
|
|
3767
|
+
try {
|
|
3768
|
+
const watcher = watch(target.path, { recursive: true, persistent: false }, onChange)
|
|
3769
|
+
watcher.on('error', () => undefined)
|
|
3770
|
+
watchers.push(watcher)
|
|
3771
|
+
this.recursiveWatch = true
|
|
3772
|
+
continue
|
|
3773
|
+
} catch (error) {
|
|
3774
|
+
this.recursiveWatch = false
|
|
3775
|
+
this.ctx.logger.debug?.(
|
|
3776
|
+
`project-mcp: recursive watch unavailable for ${target.path} (${errorText(error)}); using flat watches`,
|
|
3777
|
+
)
|
|
3778
|
+
}
|
|
3779
|
+
}
|
|
3780
|
+
add(target.path, false)
|
|
3781
|
+
}
|
|
3782
|
+
return watchers
|
|
3783
|
+
}
|
|
3784
|
+
}
|
|
3785
|
+
|
|
3786
|
+
/**
|
|
3787
|
+
* The real `serverName` conflicts of one reconciled pass, in a stable order.
|
|
3788
|
+
*
|
|
3789
|
+
* Two declarations fight over a name and only one of them mounts, so a panel
|
|
3790
|
+
* that shows the surviving row alone would hide the loss:
|
|
3791
|
+
*
|
|
3792
|
+
* - `profile` — a profile-level `mcp-client` instance already owns the name. The
|
|
3793
|
+
* project's entry does not mount under it while the profile's copy is the one
|
|
3794
|
+
* shown (the default); it mounts under a name this project chose otherwise —
|
|
3795
|
+
* the local alias, or the contested name itself, where it is the nearer
|
|
3796
|
+
* declaration and shadows the profile instance's tools in this project's
|
|
3797
|
+
* sessions. It is a conflict only where the profile is allowed to win
|
|
3798
|
+
* ({@link RuntimeConfig.profileWins}); the row carries `status: 'conflict'`
|
|
3799
|
+
* for exactly the names this project does not mount.
|
|
3800
|
+
* - `duplicate` — two documents of one project declare the same name and
|
|
3801
|
+
* {@link mergeEntries} keeps the highest-priority declaration, so the other
|
|
3802
|
+
* one is silently ignored.
|
|
3803
|
+
*
|
|
3804
|
+
* Only names defined for this project are reported: a source recorded for a name
|
|
3805
|
+
* the merge dropped (a document that reappeared between passes) is a document
|
|
3806
|
+
* detail, not a conflict this row set can explain.
|
|
3807
|
+
*
|
|
3808
|
+
* @param entries - merged entries, one per resolved name.
|
|
3809
|
+
* @param sources - declaring documents per name, lowest priority first.
|
|
3810
|
+
* @param reserved - profile-reserved names that shadow the project's entry.
|
|
3811
|
+
* @param aliases - the local name each shadowed declaration would take, when
|
|
3812
|
+
* this project has one to give ({@link resolveConflictNames}); a project with
|
|
3813
|
+
* none can still answer `native`, which needs no prefix.
|
|
3814
|
+
* @param policy - the project's policy: what the user already chose about each
|
|
3815
|
+
* contested name.
|
|
3816
|
+
* @returns one report per name, sorted by name; empty when nothing conflicts.
|
|
3817
|
+
*/
|
|
3818
|
+
function conflictsFor(
|
|
3819
|
+
entries: readonly ParsedEntry[],
|
|
3820
|
+
sources: ReadonlyMap<string, string[]>,
|
|
3821
|
+
reserved: ReadonlySet<string>,
|
|
3822
|
+
aliases: ReadonlyMap<string, string>,
|
|
3823
|
+
policy: ToolPolicy,
|
|
3824
|
+
): ServerConflict[] {
|
|
3825
|
+
const conflicts: ServerConflict[] = []
|
|
3826
|
+
for (const entry of entries) {
|
|
3827
|
+
const name = entry.name
|
|
3828
|
+
// The winner is listed first in both kinds: the profile instance that owns
|
|
3829
|
+
// the name, or the document the merge kept, which is the last one to
|
|
3830
|
+
// declare it.
|
|
3831
|
+
const declared = [...(sources.get(name) ?? [])]
|
|
3832
|
+
const winner = declared[declared.length - 1] ?? entry.source
|
|
3833
|
+
const others = declared.slice(0, -1).reverse()
|
|
3834
|
+
if (reserved.has(name)) {
|
|
3835
|
+
const alias = aliases.get(name)
|
|
3836
|
+
const choice = aliasesOf(policy)[name] ?? 'profile'
|
|
3837
|
+
// The choice is published even where this project has no alias to offer:
|
|
3838
|
+
// `native` needs no prefix, so an alias-less project still has two answers
|
|
3839
|
+
// and a panel that hid the choice would offer it none.
|
|
3840
|
+
conflicts.push({
|
|
3841
|
+
server: name,
|
|
3842
|
+
kind: 'profile',
|
|
3843
|
+
sources: [winner, ...others],
|
|
3844
|
+
...(alias === undefined ? {} : { alias }),
|
|
3845
|
+
choice,
|
|
3846
|
+
// The prose is byte-identical to what the site always emitted; the
|
|
3847
|
+
// code and its flat params ride beside it for the client to translate
|
|
3848
|
+
// (F-48).
|
|
3849
|
+
...(alias === undefined
|
|
3850
|
+
? { code: 'conflict.profile', params: { name } }
|
|
3851
|
+
: { code: 'conflict.profileAlias', params: { name, alias } }),
|
|
3852
|
+
message:
|
|
3853
|
+
alias === undefined
|
|
3854
|
+
? `"${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.`
|
|
3855
|
+
: `"${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.`,
|
|
3856
|
+
})
|
|
3857
|
+
continue
|
|
3858
|
+
}
|
|
3859
|
+
if (others.length === 0) continue
|
|
3860
|
+
conflicts.push({
|
|
3861
|
+
server: name,
|
|
3862
|
+
kind: 'duplicate',
|
|
3863
|
+
sources: [winner, ...others],
|
|
3864
|
+
code: 'conflict.documents',
|
|
3865
|
+
// Numbers stringify at emission: params are flat strings end to end.
|
|
3866
|
+
params: { name, count: String(declared.length), winner },
|
|
3867
|
+
message: `"${name}" is declared in ${declared.length} documents; ${winner} wins and the other declaration is not mounted.`,
|
|
3868
|
+
})
|
|
3869
|
+
}
|
|
3870
|
+
// Code-unit order, the same rule the rest of the plugin sorts tool names by.
|
|
3871
|
+
return conflicts.sort((left, right) =>
|
|
3872
|
+
left.server < right.server ? -1 : left.server > right.server ? 1 : 0,
|
|
3873
|
+
)
|
|
3874
|
+
}
|
|
3875
|
+
|
|
3876
|
+
function baseRow(entry: ParsedEntry, projectRoot: string, document: DocumentInfo | undefined): ServerRow {
|
|
3877
|
+
const snapshot = document?.entries.get(entry.name)
|
|
3878
|
+
return {
|
|
3879
|
+
name: entry.name,
|
|
3880
|
+
status: 'error',
|
|
3881
|
+
projectRoot,
|
|
3882
|
+
source: entry.source,
|
|
3883
|
+
...(entry.config === undefined ? {} : { transport: entry.config.transport }),
|
|
3884
|
+
...(document === undefined
|
|
3885
|
+
? {}
|
|
3886
|
+
: {
|
|
3887
|
+
...(snapshot === undefined ? {} : { entry: snapshot }),
|
|
3888
|
+
writeScope: document.scope,
|
|
3889
|
+
...(document.reason === undefined ? {} : { writeBlockedReason: document.reason }),
|
|
3890
|
+
// The wire companions ride beside the prose: the client translates
|
|
3891
|
+
// the code and falls back to the byte-identical reason.
|
|
3892
|
+
...(document.blockedCode === undefined ? {} : { blockedCode: document.blockedCode }),
|
|
3893
|
+
...(document.blockedParams === undefined ? {} : { blockedParams: document.blockedParams }),
|
|
3894
|
+
documentRevision: document.revision,
|
|
3895
|
+
}),
|
|
3896
|
+
}
|
|
3897
|
+
}
|
|
3898
|
+
|
|
3899
|
+
/** `env`/`headers` keys of one declared entry whose value comes from credentials. */
|
|
3900
|
+
function credentialKeys(declared: unknown, resolveContext: ResolveContext): CredentialKeys {
|
|
3901
|
+
const record = isRecord(declared) ? declared : {}
|
|
3902
|
+
return { env: credentialKeySet(record.env, resolveContext), headers: credentialKeySet(record.headers, resolveContext) }
|
|
3903
|
+
}
|
|
3904
|
+
|
|
3905
|
+
function credentialKeySet(section: unknown, resolveContext: ResolveContext): ReadonlySet<string> {
|
|
3906
|
+
const keys = new Set<string>()
|
|
3907
|
+
if (!isRecord(section)) return keys
|
|
3908
|
+
for (const [key, value] of Object.entries(section)) {
|
|
3909
|
+
if (typeof value === 'string' && referencesCredentials(value, resolveContext)) keys.add(key)
|
|
3910
|
+
}
|
|
3911
|
+
return keys
|
|
3912
|
+
}
|
|
3913
|
+
|
|
3914
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
3915
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
3916
|
+
}
|
|
3917
|
+
|
|
3918
|
+
/** Row of a declared server that is not mounted, with the reason in `detail`. */
|
|
3919
|
+
function idleRow(row: ServerRow, reason: CodedText): ServerRow {
|
|
3920
|
+
// Strip a previous detail's companions too, or a recycled error row would
|
|
3921
|
+
// keep a stale code under the new prose.
|
|
3922
|
+
const { detail: _stale, detailCode: _staleCode, detailParams: _staleParams, ...rest } = row
|
|
3923
|
+
return {
|
|
3924
|
+
...rest,
|
|
3925
|
+
status: 'idle',
|
|
3926
|
+
detail: reason.text,
|
|
3927
|
+
detailCode: reason.code,
|
|
3928
|
+
...(reason.params === undefined ? {} : { detailParams: reason.params }),
|
|
3929
|
+
}
|
|
3930
|
+
}
|
|
3931
|
+
|
|
3932
|
+
function formatSeconds(ms: number): string {
|
|
3933
|
+
return `${(ms / 1000).toFixed(1)}s`
|
|
3934
|
+
}
|
|
3935
|
+
|
|
3936
|
+
/**
|
|
3937
|
+
* Duration as an operator reads it: milliseconds under a second, seconds under
|
|
3938
|
+
* a minute, then minutes and seconds. A watchdog that fires at 40 ms must not
|
|
3939
|
+
* print `0.0s`, and a mount that has been waiting for four and a half minutes
|
|
3940
|
+
* should not print `266.7s`.
|
|
3941
|
+
*/
|
|
3942
|
+
function formatDuration(ms: number): string {
|
|
3943
|
+
if (ms < 1000) return `${Math.round(ms)}ms`
|
|
3944
|
+
if (ms < 60_000) return `${(ms / 1000).toFixed(1)}s`
|
|
3945
|
+
const minutes = Math.floor(ms / 60_000)
|
|
3946
|
+
const seconds = Math.round((ms - minutes * 60_000) / 1000)
|
|
3947
|
+
return seconds === 60 ? `${minutes + 1}m` : `${minutes}m ${seconds}s`
|
|
3948
|
+
}
|
|
3949
|
+
|
|
3950
|
+
/** Unref'd timer, so a bounded wait never keeps a process alive on its own. */
|
|
3951
|
+
function delay(ms: number): Promise<void> {
|
|
3952
|
+
return new Promise((resolve) => {
|
|
3953
|
+
const timer = setTimeout(resolve, ms)
|
|
3954
|
+
timer.unref?.()
|
|
3955
|
+
})
|
|
3956
|
+
}
|
|
3957
|
+
|
|
3958
|
+
/**
|
|
3959
|
+
* Endpoint label for an error message. Arguments and query strings are the two
|
|
3960
|
+
* places a declared entry can carry a secret (`--api-key=…`, `?token=…`), so
|
|
3961
|
+
* neither ever reaches a row, a log line or the snapshot.
|
|
3962
|
+
*/
|
|
3963
|
+
function describeEndpoint(config: NonNullable<ParsedEntry['config']>): string {
|
|
3964
|
+
if (config.transport === 'streamable-http') return `streamable-http ${visibleUrl(config.url)}`
|
|
3965
|
+
return `stdio ${config.command}`
|
|
3966
|
+
}
|
|
3967
|
+
|
|
3968
|
+
/**
|
|
3969
|
+
* Detail of a mount whose activation failed, including the underlying error and
|
|
3970
|
+
* the exact declaration to look at.
|
|
3971
|
+
*
|
|
3972
|
+
* Multi-line on purpose: the row's detail is the only place an operator sees
|
|
3973
|
+
* why a server is not there, and a run-on sentence that starts with the error
|
|
3974
|
+
* and ends with the file path reads as prose instead of the three facts it is.
|
|
3975
|
+
*/
|
|
3976
|
+
function failureDetail(mount: MountedInstance, error: unknown): CodedText {
|
|
3977
|
+
const params = {
|
|
3978
|
+
name: mount.name,
|
|
3979
|
+
error: errorText(error),
|
|
3980
|
+
endpoint: mount.endpoint,
|
|
3981
|
+
// The `{source}` fallback stays English under zh/ru: params are flat strings,
|
|
3982
|
+
// so a translatable fragment would need the wire extension Ruling 4 names.
|
|
3983
|
+
// Accepted partial — F-48 ledger Ruling 5 (same class as parse.ref.failedInKey).
|
|
3984
|
+
source: mount.source ?? 'the project document',
|
|
3985
|
+
}
|
|
3986
|
+
return {
|
|
3987
|
+
code: 'mount.failedDetail',
|
|
3988
|
+
text: [
|
|
3989
|
+
`${params.name}: mount failed — ${params.error}`,
|
|
3990
|
+
`endpoint: ${params.endpoint}`,
|
|
3991
|
+
`declared in: ${params.source}`,
|
|
3992
|
+
].join('\n'),
|
|
3993
|
+
params,
|
|
3994
|
+
}
|
|
3995
|
+
}
|
|
3996
|
+
|
|
3997
|
+
/**
|
|
3998
|
+
* Detail of a mount that has produced no tool inside `connectTimeoutMs`. The
|
|
3999
|
+
* server is left running: a slow start (an `npx` cold fetch, a container pull)
|
|
4000
|
+
* is not an error, only a condition the operator needs to see.
|
|
4001
|
+
*
|
|
4002
|
+
* Facts only — the name and the wait, the endpoint, the declaring document. The
|
|
4003
|
+
* row already carries the status, the transport chip and a `Retry` button, and
|
|
4004
|
+
* a stdio server's own reason is on its stderr, in the DSH log; anything more
|
|
4005
|
+
* here is text an operator has to read past to find the three lines that matter.
|
|
4006
|
+
*/
|
|
4007
|
+
function stallDetail(mount: MountedInstance, elapsedMs: number): CodedText {
|
|
4008
|
+
const params = {
|
|
4009
|
+
name: mount.name,
|
|
4010
|
+
elapsed: formatDuration(elapsedMs),
|
|
4011
|
+
endpoint: mount.endpoint,
|
|
4012
|
+
// See failureDetail: the `{source}` fallback is an accepted English fragment
|
|
4013
|
+
// under zh/ru (F-48 ledger Ruling 5).
|
|
4014
|
+
source: mount.source ?? 'the project document',
|
|
4015
|
+
}
|
|
4016
|
+
return {
|
|
4017
|
+
code: 'mount.stalledDetail',
|
|
4018
|
+
text: [
|
|
4019
|
+
`${params.name}: no tool appeared in ${params.elapsed}`,
|
|
4020
|
+
`endpoint: ${params.endpoint}`,
|
|
4021
|
+
`declared in: ${params.source}`,
|
|
4022
|
+
].join('\n'),
|
|
4023
|
+
params,
|
|
4024
|
+
}
|
|
4025
|
+
}
|
|
4026
|
+
|
|
4027
|
+
/** Row + live mount state; the mount is authoritative for `status` and `detail`. */
|
|
4028
|
+
function decorate(row: ServerRow, mount: MountedInstance | undefined): ServerRow {
|
|
4029
|
+
if (mount === undefined) return row
|
|
4030
|
+
// Drop any detail a previous pass wrote, so a mount that recovered stops
|
|
4031
|
+
// reporting a stale stall — companions included, or a recycled row would
|
|
4032
|
+
// keep a code under prose it does not belong to.
|
|
4033
|
+
const { detail: _stale, detailCode: _staleCode, detailParams: _staleParams, ...rest } = row
|
|
4034
|
+
return {
|
|
4035
|
+
...rest,
|
|
4036
|
+
status: mount.status,
|
|
4037
|
+
...(mount.detail === undefined ? {} : { detail: mount.detail }),
|
|
4038
|
+
...(mount.detailCode === undefined ? {} : { detailCode: mount.detailCode }),
|
|
4039
|
+
...(mount.detailParams === undefined ? {} : { detailParams: mount.detailParams }),
|
|
4040
|
+
...(mount.transport === undefined ? {} : { transport: mount.transport }),
|
|
4041
|
+
}
|
|
4042
|
+
}
|
|
4043
|
+
|
|
4044
|
+
/**
|
|
4045
|
+
* Which of two rows describing the same server a project-level merge keeps. The
|
|
4046
|
+
* most actionable state wins, so a session that mounted the server — or failed
|
|
4047
|
+
* to — is never hidden behind a session that has not started a turn yet.
|
|
4048
|
+
*/
|
|
4049
|
+
const STATUS_PRIORITY: Record<ServerStatus, number> = {
|
|
4050
|
+
error: 5,
|
|
4051
|
+
active: 4,
|
|
4052
|
+
connecting: 3,
|
|
4053
|
+
conflict: 2,
|
|
4054
|
+
idle: 1,
|
|
4055
|
+
disabled: 0,
|
|
4056
|
+
}
|
|
4057
|
+
|
|
4058
|
+
/**
|
|
4059
|
+
* Merge one session's rows into a project's merged list. The first session to
|
|
4060
|
+
* declare a server fixes its position (document order); the status with the
|
|
4061
|
+
* highest {@link STATUS_PRIORITY} seen so far supplies the row itself.
|
|
4062
|
+
*/
|
|
4063
|
+
function mergeRows(target: ServerRow[], rows: readonly ServerRow[]): void {
|
|
4064
|
+
for (const row of rows) {
|
|
4065
|
+
const index = target.findIndex((existing) => existing.name === row.name)
|
|
4066
|
+
if (index === -1) {
|
|
4067
|
+
target.push(row)
|
|
4068
|
+
continue
|
|
4069
|
+
}
|
|
4070
|
+
const current = target[index]
|
|
4071
|
+
if (current !== undefined && STATUS_PRIORITY[row.status] > STATUS_PRIORITY[current.status]) {
|
|
4072
|
+
target[index] = row
|
|
4073
|
+
}
|
|
4074
|
+
}
|
|
4075
|
+
}
|
|
4076
|
+
|
|
4077
|
+
/**
|
|
4078
|
+
* Identity of one reconciliation input set: the declarations, the profile
|
|
4079
|
+
* reservations, and the published state of the project's shared mounts. Equal
|
|
4080
|
+
* digests mean this session has nothing to reconcile.
|
|
4081
|
+
*
|
|
4082
|
+
* The shared mounts belong in it because a project's servers are one instance
|
|
4083
|
+
* for all of its sessions: another session's pass can mount, settle, stall or
|
|
4084
|
+
* drop one of them without touching any document, and this session's rows are a
|
|
4085
|
+
* rendering of exactly that instance.
|
|
4086
|
+
* @param entries - parsed declarations of the session's project.
|
|
4087
|
+
* @param reserved - `serverName`s a profile-level instance already owns.
|
|
4088
|
+
* @param mounts - the session's current shared mounts, live.
|
|
4089
|
+
* @param chosen - shadowed names this pass mounts, and under which name: a local
|
|
4090
|
+
* alias, or `undefined` for the contested name itself.
|
|
4091
|
+
* @returns a stable identity string.
|
|
4092
|
+
*/
|
|
4093
|
+
function digestOf(
|
|
4094
|
+
entries: ParsedEntry[],
|
|
4095
|
+
reserved: ReadonlySet<string>,
|
|
4096
|
+
mounts: ReadonlyMap<string, MountedInstance>,
|
|
4097
|
+
chosen: ReadonlyMap<string, string | undefined>,
|
|
4098
|
+
): string {
|
|
4099
|
+
const parts = entries.map(
|
|
4100
|
+
(entry) =>
|
|
4101
|
+
`${entry.name}\u0000${entry.enabled ? '1' : '0'}\u0000${entry.error ?? ''}\u0000${
|
|
4102
|
+
entry.config === undefined ? '' : fingerprint(entry.config)
|
|
4103
|
+
}`,
|
|
4104
|
+
)
|
|
4105
|
+
parts.push(`reserved:${[...reserved].sort().join(',')}`)
|
|
4106
|
+
// The local names this pass chose. They belong in the identity because a
|
|
4107
|
+
// choice the user just made moves a declaration between "conflict report" and
|
|
4108
|
+
// "mount", with no document and no mount touched yet — without them, the pass
|
|
4109
|
+
// that follows the click would find its inputs unchanged and do nothing.
|
|
4110
|
+
for (const [name, mountedAs] of [...chosen].sort(([left], [right]) => (left < right ? -1 : 1))) {
|
|
4111
|
+
// `native` is its own part rather than a `local` with an empty name: a choice
|
|
4112
|
+
// that mounts under the declared name has to move this identity exactly as a
|
|
4113
|
+
// choice that mounts under a local one does, or the pass after the click finds
|
|
4114
|
+
// its inputs unchanged and mounts nothing.
|
|
4115
|
+
parts.push(mountedAs === undefined ? `native:${name}` : `local:${name}\u0000${mountedAs}`)
|
|
4116
|
+
}
|
|
4117
|
+
for (const [name, mount] of mounts) {
|
|
4118
|
+
parts.push(
|
|
4119
|
+
`mount:${name}\u0000${mount.status}\u0000${mount.detail ?? ''}\u0000${mount.stalled ? '1' : '0'}\u0000${mount.runtimeName}`,
|
|
4120
|
+
)
|
|
4121
|
+
}
|
|
4122
|
+
return parts.join('\u0001')
|
|
4123
|
+
}
|
|
4124
|
+
|
|
4125
|
+
function fingerprint(config: unknown): string {
|
|
4126
|
+
return JSON.stringify(config)
|
|
4127
|
+
}
|
|
4128
|
+
|
|
4129
|
+
/**
|
|
4130
|
+
* The name one declaration registers under this pass: its local alias, or the
|
|
4131
|
+
* name it declared.
|
|
4132
|
+
*
|
|
4133
|
+
* @param entry - parsed declaration.
|
|
4134
|
+
* @param alias - local name the pass chose, when it chose one.
|
|
4135
|
+
* @returns the `serverName` to hand `@deepseek-ai/dsh-mcp-client`.
|
|
4136
|
+
*/
|
|
4137
|
+
function runtimeNameOf(entry: ParsedEntry, alias: string | undefined): string {
|
|
4138
|
+
return alias ?? entry.name
|
|
4139
|
+
}
|
|
4140
|
+
|
|
4141
|
+
/**
|
|
4142
|
+
* One declaration's config as it is mounted: the same body, under the name this
|
|
4143
|
+
* registration actually takes.
|
|
4144
|
+
*
|
|
4145
|
+
* A fresh object on purpose — the parsed entry is shared with every other
|
|
4146
|
+
* session and with the editor, and rewriting its `serverName` in place would
|
|
4147
|
+
* make the alias look like the declared name everywhere else.
|
|
4148
|
+
*
|
|
4149
|
+
* @param config - the parsed mcp-client config.
|
|
4150
|
+
* @param runtimeName - the `serverName` to reserve.
|
|
4151
|
+
* @returns the config to mount.
|
|
4152
|
+
*/
|
|
4153
|
+
function runtimeConfigOf(
|
|
4154
|
+
config: NonNullable<ParsedEntry['config']>,
|
|
4155
|
+
runtimeName: string,
|
|
4156
|
+
): NonNullable<ParsedEntry['config']> {
|
|
4157
|
+
if (config.serverName === runtimeName) return config
|
|
4158
|
+
return { ...config, serverName: runtimeName }
|
|
4159
|
+
}
|
|
4160
|
+
|
|
4161
|
+
/**
|
|
4162
|
+
* The one line a shadowed declaration carries.
|
|
4163
|
+
*
|
|
4164
|
+
* Two readings, and the row has to say which one it is: the profile's copy is the
|
|
4165
|
+
* one shown and this project's entry is a conflict, or the entry has a local name
|
|
4166
|
+
* to be mounted under and the choice is the question. A mounted row carries no
|
|
4167
|
+
* detail at all ({@link decorate}), so a chosen answer is explained by the
|
|
4168
|
+
* conflict report, which a mounted name still publishes.
|
|
4169
|
+
*
|
|
4170
|
+
* @param name - the contested `serverName`.
|
|
4171
|
+
* @param alias - the local name this project could give it, when it has one.
|
|
4172
|
+
* @returns the row's detail line, with its wire code and params (F-48).
|
|
4173
|
+
*/
|
|
4174
|
+
function conflictDetail(name: string, alias: string | undefined): CodedText {
|
|
4175
|
+
const base = `serverName "${name}" is already provided by a profile-level mcp-client instance`
|
|
4176
|
+
return alias === undefined
|
|
4177
|
+
? {
|
|
4178
|
+
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`,
|
|
4179
|
+
code: 'conflict.profileDetail',
|
|
4180
|
+
params: { name },
|
|
4181
|
+
}
|
|
4182
|
+
: {
|
|
4183
|
+
text: `${base} — choose this project's copy to mount it as "${alias}", or under the contested name to shadow the profile instance here`,
|
|
4184
|
+
code: 'conflict.profileAliasDetail',
|
|
4185
|
+
params: { name, alias },
|
|
4186
|
+
}
|
|
4187
|
+
}
|
|
4188
|
+
|
|
4189
|
+
async function activation(fiber: MountFiber): Promise<void> {
|
|
4190
|
+
if (typeof fiber.await === 'function') {
|
|
4191
|
+
await fiber.await()
|
|
4192
|
+
return
|
|
4193
|
+
}
|
|
4194
|
+
await Promise.resolve(fiber as unknown)
|
|
4195
|
+
}
|
|
4196
|
+
|
|
4197
|
+
function errorText(error: unknown): string {
|
|
4198
|
+
return error instanceof Error ? error.message : String(error)
|
|
4199
|
+
}
|
|
4200
|
+
|
|
4201
|
+
/**
|
|
4202
|
+
* One path the watcher stack covers and what kind it is.
|
|
4203
|
+
*
|
|
4204
|
+
* The kind comes from the config, not from the name: a document is watched as a
|
|
4205
|
+
* file — watching its whole directory would put the watcher on unrelated writes
|
|
4206
|
+
* — while a directory that holds a project document is watched (recursively when
|
|
4207
|
+
* the platform allows) so a document appearing there is seen.
|
|
4208
|
+
*/
|
|
4209
|
+
interface WatchTarget {
|
|
4210
|
+
/** Absolute path. */
|
|
4211
|
+
readonly path: string
|
|
4212
|
+
/** `true` for a directory, `false` for a document file. */
|
|
4213
|
+
readonly directory: boolean
|
|
4214
|
+
}
|
|
4215
|
+
|
|
4216
|
+
/** Same targets, in the same order — what decides a watcher rebuild. */
|
|
4217
|
+
function sameTargets(left: readonly WatchTarget[], right: readonly WatchTarget[]): boolean {
|
|
4218
|
+
return (
|
|
4219
|
+
left.length === right.length &&
|
|
4220
|
+
left.every((value, index) => value.path === right[index]?.path && value.directory === right[index]?.directory)
|
|
4221
|
+
)
|
|
4222
|
+
}
|