@chroxy/server 0.10.0 → 0.11.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.
Files changed (160) hide show
  1. package/CONFIG.md +411 -14
  2. package/hooks/permission-hook.sh +253 -3
  3. package/package.json +8 -15
  4. package/sidecar/node_modules/.package-lock.json +29 -0
  5. package/sidecar/node_modules/ws/LICENSE +20 -0
  6. package/sidecar/node_modules/ws/README.md +548 -0
  7. package/sidecar/node_modules/ws/browser.js +8 -0
  8. package/sidecar/node_modules/ws/index.js +22 -0
  9. package/sidecar/node_modules/ws/lib/buffer-util.js +131 -0
  10. package/sidecar/node_modules/ws/lib/constants.js +19 -0
  11. package/sidecar/node_modules/ws/lib/event-target.js +292 -0
  12. package/sidecar/node_modules/ws/lib/extension.js +203 -0
  13. package/sidecar/node_modules/ws/lib/limiter.js +55 -0
  14. package/sidecar/node_modules/ws/lib/permessage-deflate.js +528 -0
  15. package/sidecar/node_modules/ws/lib/receiver.js +706 -0
  16. package/sidecar/node_modules/ws/lib/sender.js +602 -0
  17. package/sidecar/node_modules/ws/lib/stream.js +161 -0
  18. package/sidecar/node_modules/ws/lib/subprotocol.js +62 -0
  19. package/sidecar/node_modules/ws/lib/validation.js +152 -0
  20. package/sidecar/node_modules/ws/lib/websocket-server.js +554 -0
  21. package/sidecar/node_modules/ws/lib/websocket.js +1393 -0
  22. package/sidecar/node_modules/ws/package.json +70 -0
  23. package/sidecar/node_modules/ws/wrapper.mjs +21 -0
  24. package/src/base-session.js +151 -6
  25. package/src/billing-budget.js +5 -1
  26. package/src/binary-provenance-trust.js +95 -0
  27. package/src/built-in-tools/file-ops.js +5 -4
  28. package/src/byok-mcp-client.js +1061 -13
  29. package/src/byok-mcp-config.js +1201 -4
  30. package/src/byok-mcp-fleet.js +374 -29
  31. package/src/byok-mcp-oauth-store.js +327 -0
  32. package/src/byok-mcp-oauth.js +635 -0
  33. package/src/byok-mcp-trust.js +254 -37
  34. package/src/byok-session.js +789 -13
  35. package/src/byok-tool-executor.js +20 -13
  36. package/src/checkpoint-manager.js +33 -6
  37. package/src/chroxy-host-metadata.js +122 -0
  38. package/src/claude-stream-parser.js +56 -0
  39. package/src/claude-tui/pty-driver.js +54 -14
  40. package/src/claude-tui-session.js +106 -7
  41. package/src/cli/config-cmd.js +2 -2
  42. package/src/cli/deploy-cmd.js +1 -1
  43. package/src/cli/init-cmd.js +1 -1
  44. package/src/cli/providers-cmd.js +3 -3
  45. package/src/cli/schedule-cmd.js +775 -0
  46. package/src/cli/server-cmd.js +16 -1
  47. package/src/cli/service-cmd.js +39 -19
  48. package/src/cli/shared.js +7 -4
  49. package/src/cli/tokens-cmd.js +213 -0
  50. package/src/cli/tunnel-cmd.js +1 -1
  51. package/src/cli-session.js +66 -10
  52. package/src/cli.js +4 -0
  53. package/src/codex-app-server-session.js +671 -39
  54. package/src/codex-session.js +121 -18
  55. package/src/config.js +453 -27
  56. package/src/control-room/integrations.js +16 -10
  57. package/src/control-room/skills-inventory.js +6 -1
  58. package/src/control-room/survey.js +32 -0
  59. package/src/credential-store.js +256 -10
  60. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +1 -0
  61. package/src/diagnostics.js +3 -0
  62. package/src/docker-sdk-session.js +16 -1
  63. package/src/docker-session.js +9 -0
  64. package/src/doctor.js +19 -8
  65. package/src/environments/backends/docker.js +8 -0
  66. package/src/environments/backends/k8s.js +9 -0
  67. package/src/event-ingest.js +19 -1
  68. package/src/event-normalizer.js +354 -19
  69. package/src/external-session-registry.js +0 -0
  70. package/src/gemini-session.js +19 -2
  71. package/src/github-webhook.js +188 -4
  72. package/src/handler-utils.js +42 -8
  73. package/src/handlers/checkpoint-handlers.js +126 -19
  74. package/src/handlers/control-room-handlers.js +48 -18
  75. package/src/handlers/conversation-handlers.js +127 -2
  76. package/src/handlers/credential-handlers.js +43 -2
  77. package/src/handlers/file-handlers.js +47 -3
  78. package/src/handlers/github-webhook-handlers.js +204 -0
  79. package/src/handlers/input-handlers.js +4 -0
  80. package/src/handlers/orchestration-handlers.js +238 -0
  81. package/src/handlers/scheduler-handlers.js +510 -0
  82. package/src/handlers/session-handlers.js +10 -2
  83. package/src/handlers/settings-handlers.js +510 -11
  84. package/src/handlers/token-handlers.js +11 -2
  85. package/src/http-routes.js +159 -0
  86. package/src/jsonl-reader.js +60 -6
  87. package/src/jsonl-subprocess-session.js +35 -6
  88. package/src/keychain.js +159 -12
  89. package/src/logger.js +182 -19
  90. package/src/notification-prefs.js +88 -6
  91. package/src/notifications/discord-webhook-sink.js +30 -1
  92. package/src/orchestration/build-manager.js +56 -0
  93. package/src/orchestration/decision-contract.js +245 -0
  94. package/src/orchestration/git-ops.js +347 -0
  95. package/src/orchestration/orchestration-manager.js +1295 -0
  96. package/src/orchestration/permission-gate.js +109 -0
  97. package/src/orchestration/role-prompts.js +136 -0
  98. package/src/orchestration/run-budget.js +81 -0
  99. package/src/orchestration/run-ledger.js +487 -0
  100. package/src/orchestration/run-model.js +205 -0
  101. package/src/orchestration/run-record.js +336 -0
  102. package/src/orchestration/run-report.js +194 -0
  103. package/src/orchestration/to-wire.js +201 -0
  104. package/src/orchestration/turn-driver.js +398 -0
  105. package/src/pairing.js +146 -1
  106. package/src/permission-audit.js +79 -3
  107. package/src/permission-floor.js +455 -0
  108. package/src/permission-manager.js +492 -40
  109. package/src/permission-resolver.js +55 -7
  110. package/src/permission-rule-store.js +411 -0
  111. package/src/platform.js +367 -23
  112. package/src/providers.js +21 -2
  113. package/src/schedule-parser.js +311 -0
  114. package/src/scheduled-task-store.js +653 -0
  115. package/src/scheduler.js +1029 -0
  116. package/src/sdk-session.js +338 -5
  117. package/src/server-cli/server-orchestrator.js +23 -0
  118. package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
  119. package/src/server-cli.js +238 -26
  120. package/src/server-identity.js +28 -4
  121. package/src/service.js +291 -33
  122. package/src/session-manager.js +417 -25
  123. package/src/session-message-history.js +27 -21
  124. package/src/session-title.js +168 -0
  125. package/src/session-token-store.js +60 -35
  126. package/src/skills-usage.js +20 -2
  127. package/src/statusline.js +584 -0
  128. package/src/subagent-counter.js +9 -1
  129. package/src/supervisor.js +77 -27
  130. package/src/token-manager.js +39 -9
  131. package/src/transcript-tasks.js +41 -6
  132. package/src/tunnel/cloudflare.js +115 -8
  133. package/src/tunnel/index.js +4 -1
  134. package/src/tunnel-check.js +1 -1
  135. package/src/turn-tracker.js +0 -0
  136. package/src/usage-normalize.js +118 -0
  137. package/src/user-shell-session.js +98 -32
  138. package/src/utils/componentwise-resolver.js +205 -0
  139. package/src/utils/composite-key.js +45 -0
  140. package/src/utils/iso-datetime.js +51 -0
  141. package/src/utils/preflight.js +140 -28
  142. package/src/utils/spawn-env.js +8 -2
  143. package/src/utils/verify-binary.js +276 -0
  144. package/src/utils/verify-provenance.js +241 -0
  145. package/src/utils/wire-counters.js +48 -0
  146. package/src/worktree-gc.js +4 -1
  147. package/src/ws-file-ops/browser.js +42 -11
  148. package/src/ws-file-ops/common.js +68 -1
  149. package/src/ws-file-ops/git.js +221 -3
  150. package/src/ws-file-ops/index.js +5 -0
  151. package/src/ws-file-ops/memory.js +358 -0
  152. package/src/ws-file-ops/reader.js +124 -0
  153. package/src/ws-forwarding.js +44 -16
  154. package/src/ws-handler-context.js +19 -0
  155. package/src/ws-history.js +84 -11
  156. package/src/ws-message-handlers.js +6 -0
  157. package/src/ws-outbound-schemas.js +207 -0
  158. package/src/ws-permissions.js +285 -4
  159. package/src/ws-schemas.js +1 -0
  160. package/src/ws-server.js +301 -17
@@ -11,7 +11,7 @@
11
11
  * the next turn's tool list.
12
12
  */
13
13
 
14
- import { MCPClient, MCP_STATES, DEFAULT_TOOL_CALL_TIMEOUT_MS } from './byok-mcp-client.js'
14
+ import { createMcpClient, MCP_STATES, DEFAULT_TOOL_CALL_TIMEOUT_MS } from './byok-mcp-client.js'
15
15
  import {
16
16
  loadTrustStore,
17
17
  recordTrust,
@@ -45,6 +45,30 @@ function mcpToolName(serverName, toolName) {
45
45
  return `${MCP_TOOL_PREFIX}${serverName}__${toolName}`
46
46
  }
47
47
 
48
+ // #6823: prompts share the tools' `mcp__<server>__<name>` namespace so the
49
+ // slash-command surface (`/mcp__server__prompt`) and the tool router use one
50
+ // parser (parseMcpToolName). Same shape, distinct call — keep a named alias so
51
+ // the intent reads clearly at the call site.
52
+ const mcpPromptName = mcpToolName
53
+
54
+ // #6824: map an MCPClient's internal lifecycle state to the wire `status`
55
+ // string the `mcp_servers` broadcast carries. Kept aligned with the sdk/cli
56
+ // convention (dashboard/mobile only treat `connected` as the live/green dot;
57
+ // everything else renders muted). A parked (disabled) server has NO client, so
58
+ // this is only ever called for enabled ones — the disabled status is applied
59
+ // by `getServerStatuses()` directly.
60
+ export function mcpStateToStatus(state) {
61
+ switch (state) {
62
+ case MCP_STATES.READY:
63
+ return 'connected'
64
+ case MCP_STATES.DEAD:
65
+ return 'failed'
66
+ default:
67
+ // IDLE / STARTING / RESTARTING — spawned but not yet handshaken.
68
+ return 'connecting'
69
+ }
70
+ }
71
+
48
72
  export class MCPFleet {
49
73
  constructor(configs, opts = {}) {
50
74
  // #4457: build a per-client trust gate when a PermissionManager is
@@ -52,7 +76,9 @@ export class MCPFleet {
52
76
  // user friction for tuples already trusted in a prior session); on
53
77
  // a miss it asks the PermissionManager — emitting a prompt visible to
54
78
  // the dashboard / mobile permission UI — and persists allow decisions
55
- // to the store so the prompt only fires once per (name, command, args[0]).
79
+ // to the store so the prompt only fires once per spawn-determining config
80
+ // (#7001: name + command + the FULL args + env, digested — see
81
+ // byok-mcp-trust.js; the pre-#7001 key covered only args[0]).
56
82
  //
57
83
  // No PermissionManager → no gate → spawn behaves exactly as in #4077.
58
84
  // This keeps the lifecycle module testable in isolation; integration
@@ -74,38 +100,281 @@ export class MCPFleet {
74
100
  Number.isFinite(opts.startCapMs) && opts.startCapMs > 0
75
101
  ? opts.startCapMs
76
102
  : DEFAULT_FLEET_START_CAP_MS
77
- this._clients = configs.map((cfg) => {
78
- const clientOpts = { ...opts }
79
- if (permissionManager) {
80
- clientOpts.trustGate = async () => {
81
- // #4460: serialise the load→prompt→recordTrust sequence across
82
- // all fleet clients that share this trust-store path. Without
83
- // the lock, two concurrent gates can both observe an empty
84
- // store, both prompt, both call recordTrust — and the last
85
- // writer's snapshot (read at step 1, missing the other's
86
- // entry) clobbers the first allow. The lock also surfaces
87
- // prompts one at a time, which the dashboard / mobile UI
88
- // already assumes (one modal at a time).
89
- return withTrustStoreLock(resolvedTrustPath, async () => {
90
- const store = loadTrustStore(resolvedTrustPath, { log: opts.log })
91
- if (isTrusted(store, cfg)) return true
92
- const allowed = await permissionManager.requestMcpTrust({
93
- name: cfg.name,
94
- command: cfg.command,
95
- args: cfg.args,
96
- envKeys: Object.keys(cfg.env || {}).sort(),
97
- })
98
- if (allowed) recordTrust(cfg, resolvedTrustPath)
99
- return allowed
100
- })
101
- }
103
+ // #6824: retain the raw config list + the wiring inputs so a re-enable can
104
+ // rebuild a client from scratch (a destroyed MCPClient can't be revived —
105
+ // start() throws once `_destroyed`). `getServerStatuses()` also iterates
106
+ // `_configs` so it can report parked servers the live `_clients` array no
107
+ // longer holds.
108
+ this._configs = configs
109
+ this._opts = opts
110
+ this._permissionManager = permissionManager
111
+ this._resolvedTrustPath = resolvedTrustPath
112
+ // #6824: per-session parked (disabled) server names. Seeded from the
113
+ // caller's persisted set (byok-session forwards the restored
114
+ // `disabledMcpServers`), filtered to names that are actually configured so
115
+ // a stale entry for a removed server can't wedge. Parked servers get NO
116
+ // client on construction — they contribute zero tools and report status
117
+ // 'disabled' until re-enabled.
118
+ const configuredNames = new Set(configs.map((c) => c.name))
119
+ this._disabled = new Set(
120
+ (Array.isArray(opts.disabledServers) ? opts.disabledServers : [])
121
+ .filter((name) => configuredNames.has(name)),
122
+ )
123
+ // #6824: per-server in-flight toggle latch — names whose park/unpark is
124
+ // currently awaiting (destroy grace / restart handshake). A second toggle
125
+ // for the same server arriving mid-flight is churn and is ignored (see
126
+ // setEnabled) rather than interleaving destroy/start on one client.
127
+ this._toggling = new Set()
128
+ this._clients = configs
129
+ .filter((cfg) => !this._disabled.has(cfg.name))
130
+ .map((cfg) => this._makeClient(cfg))
131
+ }
132
+
133
+ /**
134
+ * #6824: build one MCPClient for a config, wiring the trust gate exactly as
135
+ * the constructor did inline pre-#6824. Extracted so the re-enable path
136
+ * (`setEnabled(name, true)`) rebuilds a client with an IDENTICAL gate — an
137
+ * already-trusted spawn config reconnects silently; an
138
+ * untrusted one still prompts, so re-enabling can never bypass trust.
139
+ */
140
+ _makeClient(cfg) {
141
+ const clientOpts = { ...this._opts }
142
+ if (this._permissionManager) {
143
+ clientOpts.trustGate = async () => {
144
+ // #4460: serialise the load→prompt→recordTrust sequence across
145
+ // all fleet clients that share this trust-store path. Without
146
+ // the lock, two concurrent gates can both observe an empty
147
+ // store, both prompt, both call recordTrust — and the last
148
+ // writer's snapshot (read at step 1, missing the other's
149
+ // entry) clobbers the first allow. The lock also surfaces
150
+ // prompts one at a time, which the dashboard / mobile UI
151
+ // already assumes (one modal at a time).
152
+ return withTrustStoreLock(this._resolvedTrustPath, async () => {
153
+ const store = loadTrustStore(this._resolvedTrustPath, { log: this._opts.log })
154
+ if (isTrusted(store, cfg)) return true
155
+ // #6821: a remote server has no command/args — prompt on
156
+ // (name, url) + header KEY names. Header VALUES (tokens) never
157
+ // reach the permission payload, the trust store, or any log.
158
+ const isRemote = typeof cfg.url === 'string' && cfg.url.length > 0
159
+ const trustReq = isRemote
160
+ ? { name: cfg.name, url: cfg.url, headerKeys: Object.keys(cfg.headers || {}).sort() }
161
+ : { name: cfg.name, command: cfg.command, args: cfg.args, envKeys: Object.keys(cfg.env || {}).sort() }
162
+ const allowed = await this._permissionManager.requestMcpTrust(trustReq)
163
+ if (allowed) recordTrust(cfg, this._resolvedTrustPath)
164
+ return allowed
165
+ })
102
166
  }
103
- return new MCPClient(cfg, clientOpts)
104
- })
167
+ }
168
+ return createMcpClient(cfg, clientOpts)
105
169
  }
106
170
 
107
171
  get clients() { return this._clients }
108
172
 
173
+ /**
174
+ * #6824: read-only view of the parked (disabled) server names. Byok-session
175
+ * reads this to persist the set into session state so a respawn honours it.
176
+ */
177
+ get disabledServers() { return [...this._disabled].sort() }
178
+
179
+ /**
180
+ * #6824: status snapshot for EVERY configured server — the payload the
181
+ * `mcp_servers` broadcast carries. Parked servers report status 'disabled'
182
+ * with `enabled: false`; live ones map their MCPClient state. `canToggle`
183
+ * is true for all (the whole BYOK fleet is toggleable) so the client can
184
+ * gate its per-row switch on a single field.
185
+ */
186
+ getServerStatuses() {
187
+ return this._configs.map((cfg) => {
188
+ if (this._disabled.has(cfg.name)) {
189
+ return { name: cfg.name, status: 'disabled', enabled: false, canToggle: true }
190
+ }
191
+ const client = this._clients.find((c) => c.name === cfg.name)
192
+ // #6822: a remote server awaiting OAuth reports `oauth-required` + the
193
+ // browser authorization URL (never a token/secret), so the client can
194
+ // render an "Authorize" affordance instead of a bare failure.
195
+ if (client && client.needsAuthorization) {
196
+ const entry = { name: cfg.name, status: 'oauth-required', enabled: true, canToggle: true }
197
+ if (client.authorizationUrl) entry.authUrl = client.authorizationUrl
198
+ return entry
199
+ }
200
+ const status = client ? mcpStateToStatus(client.state) : 'connecting'
201
+ return { name: cfg.name, status, enabled: true, canToggle: true }
202
+ })
203
+ }
204
+
205
+ /**
206
+ * #6822: submit a pasted OAuth authorization code for a configured remote MCP
207
+ * server, redeeming it at the daemon and reconnecting authenticated. Returns
208
+ * `{ found, ok?, status?, error? }` — `found: false` when `name` is not a
209
+ * configured server; `ok: false` with a value-free `error` on a redemption
210
+ * failure. On success the fleet re-emits nothing itself (byok-session re-emits
211
+ * `mcp_servers` after the call so all clients converge).
212
+ */
213
+ async submitAuthCode(name, code) {
214
+ const client = this._clients.find((c) => c.name === name)
215
+ if (!client) return { found: false }
216
+ if (typeof client.completeAuthorization !== 'function') {
217
+ return { found: true, ok: false, error: 'This MCP server does not use OAuth authorization.' }
218
+ }
219
+ try {
220
+ await client.completeAuthorization(code)
221
+ const status = client.needsAuthorization ? 'oauth-required' : mcpStateToStatus(client.state)
222
+ return { found: true, ok: true, status }
223
+ } catch (err) {
224
+ return { found: true, ok: false, error: err?.message || String(err) }
225
+ }
226
+ }
227
+
228
+ /**
229
+ * #6824: park or unpark a single configured server without tearing down the
230
+ * rest of the fleet.
231
+ *
232
+ * - disable: destroy the server's MCPClient (SIGTERM→SIGKILL grace) and
233
+ * add it to `_disabled`. Its tools/prompts/resources drop from the next
234
+ * turn's aggregates immediately; it never respawns while parked.
235
+ * - enable: remove it from `_disabled`, rebuild a fresh client through the
236
+ * SAME trust gate, and start it (bounded by the client's own
237
+ * restart budget). Already-trusted servers reconnect with no prompt.
238
+ *
239
+ * Idempotent: toggling to the current state is a no-op (`changed: false`).
240
+ * Returns `{ found, changed, status }` — `found: false` when `name` is not a
241
+ * configured server (caller surfaces a clean error rather than silently
242
+ * creating a phantom entry).
243
+ */
244
+ async setEnabled(name, enabled) {
245
+ const cfg = this._configs.find((c) => c.name === name)
246
+ if (!cfg) return { found: false, changed: false, status: null }
247
+
248
+ // #6824 review follow-up: churn guard. If a park/unpark for THIS server is
249
+ // already awaiting, ignore the new toggle (changed: false) — interleaving a
250
+ // start into an in-flight destroy (or vice versa) on one client is the only
251
+ // way this API can corrupt fleet state. The in-flight op's completion
252
+ // re-emit is the authoritative state the client converges to.
253
+ if (this._toggling.has(name)) {
254
+ const client = this._clients.find((c) => c.name === name)
255
+ const status = this._disabled.has(name)
256
+ ? 'disabled'
257
+ : (client ? mcpStateToStatus(client.state) : 'connecting')
258
+ return { found: true, changed: false, status }
259
+ }
260
+
261
+ const currentlyDisabled = this._disabled.has(name)
262
+ // Target state already holds → no-op.
263
+ if (enabled && !currentlyDisabled) {
264
+ const client = this._clients.find((c) => c.name === name)
265
+ return { found: true, changed: false, status: client ? mcpStateToStatus(client.state) : 'connecting' }
266
+ }
267
+ if (!enabled && currentlyDisabled) {
268
+ return { found: true, changed: false, status: 'disabled' }
269
+ }
270
+
271
+ this._toggling.add(name)
272
+ try {
273
+ if (!enabled) {
274
+ // Disable: destroy the live client, mark parked.
275
+ this._disabled.add(name)
276
+ const idx = this._clients.findIndex((c) => c.name === name)
277
+ if (idx !== -1) {
278
+ const [client] = this._clients.splice(idx, 1)
279
+ try {
280
+ await client.destroy()
281
+ } catch (err) {
282
+ ;(this._opts.log || console).warn?.(`MCP fleet: destroy of ${name} on disable threw: ${err?.message || err}`)
283
+ }
284
+ }
285
+ return { found: true, changed: true, status: 'disabled' }
286
+ }
287
+
288
+ // Enable: unpark + rebuild + start through the same trust gate.
289
+ this._disabled.delete(name)
290
+ const client = this._makeClient(cfg)
291
+ this._clients.push(client)
292
+ try {
293
+ await client.start()
294
+ } catch (err) {
295
+ // A failed start leaves the client in DEAD (contributes zero tools) —
296
+ // mirror fleet.start()'s non-fatal handling. Keep it in `_clients` so its
297
+ // 'failed' status still surfaces on the next snapshot.
298
+ ;(this._opts.log || console).warn?.(`MCP fleet: start of ${name} on enable threw: ${err?.message || err}`)
299
+ }
300
+ return { found: true, changed: true, status: mcpStateToStatus(client.state) }
301
+ } finally {
302
+ this._toggling.delete(name)
303
+ }
304
+ }
305
+
306
+ /**
307
+ * #6974: attach a NEWLY CONFIGURED server to the live fleet and connect it,
308
+ * without restarting the session or disturbing any other client.
309
+ *
310
+ * The client is built through `_makeClient`, so it goes through the IDENTICAL
311
+ * first-use trust gate as any other server: a config that is not trusted in
312
+ * FULL (name + command + every arg + env — #7001) still raises a
313
+ * `requestMcpTrust` prompt before anything is spawned. This is the backstop, not
314
+ * the primary gate: on the WS add path `ClaudeByokSession.addMcpServer` has
315
+ * already taken the decision BEFORE persisting, so an allowed add finds itself
316
+ * trusted here and does not prompt twice, and a denied one never reaches this
317
+ * method. The backstop still matters for a config that was persisted some other
318
+ * way (hand-edited `~/.claude.json`) or whose trust record was tampered with.
319
+ *
320
+ * A failed start is non-fatal and mirrors `start()` / `setEnabled(name, true)`:
321
+ * the client stays in `_clients` in a DEAD state so its 'failed' status
322
+ * surfaces on the next snapshot, rather than vanishing and looking unconfigured.
323
+ *
324
+ * Returns `{ added, status }` — `added: false` when a server of that name is
325
+ * already in the fleet (the caller has already refused the config write, so
326
+ * this is the belt to that braces).
327
+ */
328
+ async addServer(cfg) {
329
+ if (!cfg || typeof cfg.name !== 'string' || cfg.name.length === 0) {
330
+ return { added: false, status: null }
331
+ }
332
+ if (this._configs.some((c) => c.name === cfg.name)) {
333
+ return { added: false, status: null }
334
+ }
335
+ this._configs.push(cfg)
336
+ // A brand-new server is never parked: an explicit add is an explicit
337
+ // "I want this on". Clear any stale parked entry left by a same-named
338
+ // server that was removed earlier in this session.
339
+ this._disabled.delete(cfg.name)
340
+ const client = this._makeClient(cfg)
341
+ this._clients.push(client)
342
+ try {
343
+ await client.start()
344
+ } catch (err) {
345
+ ;(this._opts.log || console).warn?.(`MCP fleet: start of ${cfg.name} on add threw: ${err?.message || err}`)
346
+ }
347
+ return { added: true, status: mcpStateToStatus(client.state) }
348
+ }
349
+
350
+ /**
351
+ * #6974: detach a server from the live fleet and tear its client down.
352
+ *
353
+ * Unlike `setEnabled(name, false)` (which PARKS a still-configured server so
354
+ * it can be unparked later), this drops the server from `_configs` entirely —
355
+ * it leaves the `getServerStatuses()` snapshot altogether, matching a config
356
+ * removal. The parked-set entry is cleared too, so the name does not linger in
357
+ * the persisted `disabledMcpServers` set as a ghost.
358
+ *
359
+ * Returns `{ removed }` — `removed: false` when the name was not configured.
360
+ */
361
+ async removeServer(name) {
362
+ const idx = this._configs.findIndex((c) => c.name === name)
363
+ if (idx === -1) return { removed: false }
364
+ this._configs.splice(idx, 1)
365
+ this._disabled.delete(name)
366
+ const clientIdx = this._clients.findIndex((c) => c.name === name)
367
+ if (clientIdx !== -1) {
368
+ const [client] = this._clients.splice(clientIdx, 1)
369
+ try {
370
+ await client.destroy()
371
+ } catch (err) {
372
+ ;(this._opts.log || console).warn?.(`MCP fleet: destroy of ${name} on remove threw: ${err?.message || err}`)
373
+ }
374
+ }
375
+ return { removed: true }
376
+ }
377
+
109
378
  /**
110
379
  * Spawn every client and resolve when either (a) every client has reached
111
380
  * a stable state (READY or DEAD), or (b) the wall-clock cap fires —
@@ -164,6 +433,82 @@ export class MCPFleet {
164
433
  return out
165
434
  }
166
435
 
436
+ /**
437
+ * #6823: aggregate MCP prompts across READY servers, namespaced
438
+ * `mcp__<server>__<prompt>` so they slot into the slash-command surface next
439
+ * to built-ins. Dead servers contribute zero (state gate), matching `tools`.
440
+ * Each entry keeps the server's `description` + `arguments` (for prompts/get
441
+ * argument mapping) plus the internal `_mcpServer` / `_mcpOriginalName`
442
+ * routing markers.
443
+ */
444
+ get prompts() {
445
+ const out = []
446
+ for (const client of this._clients) {
447
+ if (client.state !== MCP_STATES.READY) continue
448
+ for (const prompt of client.prompts) {
449
+ out.push({
450
+ ...prompt,
451
+ name: mcpPromptName(client.name, prompt.name),
452
+ _mcpServer: client.name,
453
+ _mcpOriginalName: prompt.name,
454
+ })
455
+ }
456
+ }
457
+ return out
458
+ }
459
+
460
+ /**
461
+ * #6823: aggregate MCP resources across READY servers. Resources are
462
+ * identified by `uri` (not name), so routing a read back to the owning server
463
+ * needs the `_mcpServer` marker rather than a namespaced name. Kept flat +
464
+ * read-only for the dashboard `@`-picker.
465
+ */
466
+ get resources() {
467
+ const out = []
468
+ for (const client of this._clients) {
469
+ if (client.state !== MCP_STATES.READY) continue
470
+ for (const resource of client.resources) {
471
+ out.push({
472
+ ...resource,
473
+ _mcpServer: client.name,
474
+ })
475
+ }
476
+ }
477
+ return out
478
+ }
479
+
480
+ /**
481
+ * #6823: fetch one prompt's messages by its namespaced `mcp__<server>__<name>`
482
+ * name. Parses + routes exactly like callTool. Throws on a malformed name, an
483
+ * unknown server, or a non-READY client; JSON-RPC errors (e.g. a missing
484
+ * required argument) propagate from the client.
485
+ */
486
+ async getPrompt(prefixedName, args, timeoutMs = DEFAULT_TOOL_CALL_TIMEOUT_MS) {
487
+ const parsed = parseMcpToolName(prefixedName)
488
+ if (!parsed) throw new Error(`malformed MCP prompt name: ${prefixedName}`)
489
+ const client = this._clients.find((c) => c.name === parsed.serverName)
490
+ if (!client) throw new Error(`MCP server not found: ${parsed.serverName}`)
491
+ if (client.state !== MCP_STATES.READY) {
492
+ throw new Error(`MCP server ${parsed.serverName} not ready (state=${client.state})`)
493
+ }
494
+ // parseMcpToolName names the second segment `toolName`; here it's the prompt.
495
+ return client.getPrompt(parsed.toolName, args, timeoutMs)
496
+ }
497
+
498
+ /**
499
+ * #6823: read one resource's contents. Routed by (server, uri) — the server
500
+ * comes from the aggregated resource entry's `_mcpServer` marker, the uri is
501
+ * the server's own identifier.
502
+ */
503
+ async readResource(serverName, uri, timeoutMs = DEFAULT_TOOL_CALL_TIMEOUT_MS) {
504
+ const client = this._clients.find((c) => c.name === serverName)
505
+ if (!client) throw new Error(`MCP server not found: ${serverName}`)
506
+ if (client.state !== MCP_STATES.READY) {
507
+ throw new Error(`MCP server ${serverName} not ready (state=${client.state})`)
508
+ }
509
+ return client.readResource(uri, timeoutMs)
510
+ }
511
+
167
512
  /**
168
513
  * Anthropic-shaped tool definitions for messages.stream({ tools }).
169
514
  *