@geohar/pi-mcp-combiner 0.24.4 → 0.24.5

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 (39) hide show
  1. package/CHANGELOG.md +76 -0
  2. package/dist/client/footer.d.ts +10 -2
  3. package/dist/client/footer.d.ts.map +1 -1
  4. package/dist/client/footer.js +15 -6
  5. package/dist/client/footer.js.map +1 -1
  6. package/dist/combiner-process.d.ts +160 -0
  7. package/dist/combiner-process.d.ts.map +1 -0
  8. package/dist/combiner-process.js +721 -0
  9. package/dist/combiner-process.js.map +1 -0
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +140 -306
  12. package/dist/index.js.map +1 -1
  13. package/dist/native/combiner-connection.d.ts +84 -0
  14. package/dist/native/combiner-connection.d.ts.map +1 -1
  15. package/dist/native/combiner-connection.js +187 -4
  16. package/dist/native/combiner-connection.js.map +1 -1
  17. package/dist/native/index.d.ts +32 -4
  18. package/dist/native/index.d.ts.map +1 -1
  19. package/dist/native/index.js +94 -6
  20. package/dist/native/index.js.map +1 -1
  21. package/dist/native/resources.d.ts +3 -0
  22. package/dist/native/resources.d.ts.map +1 -1
  23. package/dist/native/resources.js +6 -1
  24. package/dist/native/resources.js.map +1 -1
  25. package/dist/native/tool-surface.d.ts +31 -2
  26. package/dist/native/tool-surface.d.ts.map +1 -1
  27. package/dist/native/tool-surface.js +62 -18
  28. package/dist/native/tool-surface.js.map +1 -1
  29. package/dist/pi.d.ts +8 -0
  30. package/dist/pi.d.ts.map +1 -1
  31. package/package.json +2 -2
  32. package/src/client/footer.ts +16 -4
  33. package/src/combiner-process.ts +813 -0
  34. package/src/index.ts +142 -355
  35. package/src/native/combiner-connection.ts +212 -6
  36. package/src/native/index.ts +119 -18
  37. package/src/native/resources.ts +8 -1
  38. package/src/native/tool-surface.ts +80 -18
  39. package/src/pi.ts +5 -0
package/src/index.ts CHANGED
@@ -26,7 +26,6 @@
26
26
  // degrade-rather-than-die behaviour, so a user running several clients gets one answer
27
27
  // to "which combiner / which sharedserver am I on, and why".
28
28
 
29
- import { spawnSync } from "node:child_process"
30
29
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"
31
30
  import { homedir } from "node:os"
32
31
  import { basename, dirname, join } from "node:path"
@@ -40,8 +39,8 @@ import type {
40
39
  SessionStartEvent,
41
40
  CommandSpec,
42
41
  } from "./pi.js"
43
- import { resolveSharedserver } from "./sharedserver-resolve.js"
44
- import { NativeCombinerConnection, activateNativeMode } from "./native/index.js"
42
+ import { CombinerProcess, DEFAULT_PORT, env, type LogFn } from "./combiner-process.js"
43
+ import { NativeCombinerConnection, activateNativeMode, waitForRegistration } from "./native/index.js"
45
44
  // ── TOOL SURFACE ───────────────────────────────────────────────────────────────
46
45
  // The mcp router (search/describe/call on the owned connection) + the native
47
46
  // per-tool registration (pi-1.0 exposure/namespace/annotations) + interactive
@@ -54,22 +53,8 @@ import { resolveSessionConfig, type SessionConfig } from "./client/config-ladder
54
53
  import { metaToolCall, statusText as controlStatusText } from "./client/control.js"
55
54
  import { openCombinerPanel } from "./client/panel.js"
56
55
  import { syncPromptCommands } from "./client/prompts.js"
57
- import { updateFooter } from "./client/footer.js"
58
-
59
- const DEFAULT_PORT = 9741
60
- const DEFAULT_NAME = "mcp-combiner"
61
- const DEFAULT_GRACE = "30m"
62
- // The `--mcp` serve flag arrived in combiner 0.8.0; older versions serve with a bare
63
- // `--config`. That boundary is also the floor for trusting a PATH install — below it we
64
- // fetch a known-good release via uvx rather than limp along. NOT the lockstep release
65
- // version; it moves only when this extension depends on newer combiner behaviour.
66
- const MIN_COMBINER_VERSION: [number, number, number] = [0, 8, 0]
67
- // Floor-only against sharedserver's latest release: this repo consumes sharedserver
68
- // rather than shipping it. Kept equal to the OpenCode plugin's value (they resolve the
69
- // same binary the same way).
70
- const SHAREDSERVER_MIN_VERSION = "0.6.7"
71
-
72
- type LogFn = (level: "info" | "warn" | "error", message: string) => void
56
+ import { updateFooter, type RegisterProgress } from "./client/footer.js"
57
+ import { matchesKey } from "@earendil-works/pi-tui"
73
58
 
74
59
  // ── the tool-discovery directive ───────────────────────────────────
75
60
  // Appended to the system prompt so the agent knows combined tools arrive under a
@@ -96,195 +81,8 @@ const DIRECTIVE_MARKER = COMBINER_DIRECTIVE.split("\n", 1)[0] ?? ""
96
81
  // The PI_MCP_COMBINER_* namespace mirrors the Claude plugin's CLAUDE_MCP_COMBINER_* and
97
82
  // the OpenCode plugin's OPENCODE_MCP_COMBINER_*, so a user running several clients keeps
98
83
  // one namespace per client rather than options in one place and env vars in another.
99
-
100
- function env(name: string): string | undefined {
101
- const v = process.env[name]
102
- return v !== undefined && v !== "" ? v : undefined
103
- }
104
-
105
- function splitArgs(value: string | undefined): string[] {
106
- if (!value) return []
107
- return value.split(/\s+/).filter((s) => s.length > 0)
108
- }
109
-
110
- // ── combiner command resolution (ported from the OpenCode plugin) ──
111
-
112
- type Command = {
113
- cmd: string
114
- /** Structural args identifying WHAT to run. Probed with; never omitted. */
115
- args: string[]
116
- /** The user's own extra args. Appended at spawn time only — never probed with. */
117
- extra?: string[]
118
- version?: [number, number, number]
119
- }
120
-
121
- function parseVersion(text: string): [number, number, number] | undefined {
122
- const m = text.match(/(\d+)\.(\d+)\.(\d+)/)
123
- if (!m) return undefined
124
- return [Number(m[1]), Number(m[2]), Number(m[3])]
125
- }
126
-
127
- function gte(a: [number, number, number], b: [number, number, number]): boolean {
128
- for (let i = 0; i < 3; i++) {
129
- if (a[i] !== b[i]) return a[i] > b[i]
130
- }
131
- return true
132
- }
133
-
134
- /** Probe a command once for BOTH facts: is it runnable, and which version. Presence is
135
- * "spawn did not fail", NOT "exited 0" — a pre-0.8.0 combiner exits non-zero on
136
- * `--version` (the flag did not exist), which is exactly the stale install the floor
137
- * exists to catch. Probes with ONLY the structural args; the user's extras are never
138
- * folded in, so one arg the CLI rejects cannot make a healthy install look absent. */
139
- function probe(cmd: Command): { present: boolean; version?: [number, number, number] } {
140
- const r = spawnSync(cmd.cmd, [...cmd.args, "--version"], { env: process.env })
141
- if (r.error) return { present: false }
142
- if (r.status !== 0) return { present: true }
143
- return { present: true, version: parseVersion(`${r.stdout?.toString() ?? ""}${r.stderr?.toString() ?? ""}`) }
144
- }
145
-
146
- function probeUsable(cmd: Command): Command | undefined {
147
- const { version } = probe(cmd)
148
- if (!version || !gte(version, MIN_COMBINER_VERSION)) return undefined
149
- return { ...cmd, version }
150
- }
151
-
152
- /** This extension's own version, kept equal to the published PyPI mcp-combiner by
153
- * lockstep releases (scripts/bump-version.sh). Used as the uvx pin — read from the
154
- * manifest, never duplicated as a constant. */
155
- const PLUGIN_VERSION: string | undefined = (() => {
156
- try {
157
- const here = dirname(fileURLToPath(import.meta.url))
158
- const pkg = JSON.parse(readFileSync(join(here, "..", "package.json"), "utf8")) as { version?: string }
159
- return pkg.version
160
- } catch {
161
- return undefined
162
- }
163
- })()
164
-
165
- /** Resolve how to invoke the combiner, mirroring the sibling plugins' priority:
166
- * explicit env command → `mcp-combiner` on PATH (only when new enough) →
167
- * `uv run --project <checkout> python -m mcp_combiner` → a pinned release via uvx. The
168
- * uvx tail is what makes a bare install work with nothing installed by hand. */
169
- function resolveCombiner(log: LogFn): Command | undefined {
170
- const extra = splitArgs(env("PI_MCP_COMBINER_ARGS"))
171
-
172
- const command = env("PI_MCP_COMBINER_COMMAND")
173
- if (command) {
174
- return { cmd: command, args: [], extra }
175
- }
176
-
177
- const onPath: Command = { cmd: "mcp-combiner", args: [] }
178
- const pathProbe = probe(onPath)
179
- if (pathProbe.present) {
180
- if (pathProbe.version && gte(pathProbe.version, MIN_COMBINER_VERSION)) {
181
- return { ...onPath, extra, version: pathProbe.version }
182
- }
183
- log(
184
- "warn",
185
- `mcp-combiner on PATH reports ${pathProbe.version?.join(".") ?? "a pre-0.8.0 version"}, older than ` +
186
- `${MIN_COMBINER_VERSION.join(".")} — ignoring it and fetching a pinned release instead. ` +
187
- "Upgrade with: uv tool install --upgrade mcp-combiner",
188
- )
189
- }
190
-
191
- const checkout = env("PI_MCP_COMBINER_CHECKOUT")
192
- if (checkout && existsSync(checkout) && probe({ cmd: "uv", args: [] }).present) {
193
- return { cmd: "uv", args: ["run", "--project", checkout, "python", "-m", "mcp_combiner"], extra }
194
- }
195
-
196
- // Out-of-the-box path: no install required, fetch from PyPI. Pinned to this
197
- // extension's version so the pair moves in lockstep; if that exact release is
198
- // missing, fall back to latest rather than failing. The probe both validates the pin
199
- // and warms uv's cache, so the real spawn is a cache hit.
200
- if (probe({ cmd: "uvx", args: [] }).present) {
201
- if (PLUGIN_VERSION) {
202
- const pinned = probeUsable({ cmd: "uvx", args: [`mcp-combiner@${PLUGIN_VERSION}`] })
203
- if (pinned) return { ...pinned, extra }
204
- log("warn", `pinned mcp-combiner@${PLUGIN_VERSION} unavailable or too old; trying latest from PyPI`)
205
- }
206
- const latest = probeUsable({ cmd: "uvx", args: ["mcp-combiner"] })
207
- if (latest) return { ...latest, extra }
208
- }
209
-
210
- return undefined
211
- }
212
-
213
- /** True if the resolved combiner supports (needs) the `--mcp` serve flag. Unknown
214
- * version → assume NO: a version we cannot read is a pre-0.8.0 build serving on a bare
215
- * `--config`, and a bare `--config` still serves on newer releases (with a deprecation
216
- * warning), so guessing low degrades gracefully whereas guessing high does not. */
217
- function combinerNeedsMcpFlag(cmd: Command): boolean {
218
- const ver = cmd.version ?? probe({ cmd: cmd.cmd, args: cmd.args }).version
219
- return ver ? gte(ver, MIN_COMBINER_VERSION) : false
220
- }
221
-
222
- // ── servers.json resolution (mirrors the sibling plugins) ──
223
-
224
- function resolveConfig(log: LogFn): string | undefined {
225
- const explicit = env("PI_MCP_COMBINER_CONFIG")
226
- if (explicit) return explicit
227
- const user = process.env.USER ?? process.env.LOGNAME ?? ""
228
- const candidates = [
229
- join(homedir(), ".cache", "secrets", `${user}.mcpservers.json`),
230
- join(homedir(), ".config", "mcp-combiner", "servers.json"),
231
- join(homedir(), ".config", "mcp", "servers.json"),
232
- ]
233
- const found = candidates.find(existsSync)
234
- if (!found) {
235
- log(
236
- "error",
237
- "no combiner servers.json found; set $PI_MCP_COMBINER_CONFIG (probed " +
238
- "~/.cache/secrets/<user>.mcpservers.json, ~/.config/mcp-combiner/servers.json, " +
239
- "~/.config/mcp/servers.json)",
240
- )
241
- }
242
- return found
243
- }
244
-
245
- // ── sharedserver lifecycle ─────────────────────────────────────────
246
-
247
- /** Attach state for exactly one live refcount. Guards `detach()` so a
248
- * `session_shutdown("quit")` and a process-exit handler cannot double-`unuse` (which
249
- * would over-decrement sharedserver's refcount). */
250
- type Attachment = { binary: string; name: string }
251
- let attachment: Attachment | null = null
252
-
253
- /** Process-global guard — jiti loads extensions with moduleCache:false, so every
254
- * session bind (parent + each subagent child) re-instantiates this module with
255
- * fresh module state. Symbol.for survives that isolation (same trick
256
- * pi-permission-system's service.ts uses), so the signal handlers are installed
257
- * exactly once per process no matter how many sessions bind. */
258
- const CLEANUP_GUARD = Symbol.for("mcp-companion:cleanup-installed")
259
-
260
- function installProcessCleanup() {
261
- const g = globalThis as Record<symbol, boolean | undefined>
262
- if (g[CLEANUP_GUARD]) return
263
- g[CLEANUP_GUARD] = true
264
- // Belt to the session_shutdown("quit") braces: if Pi is killed hard enough that
265
- // session_shutdown never fires, still release the refcount. Idempotent via `detach`.
266
- process.on("exit", () => detach())
267
- for (const sig of ["SIGINT", "SIGTERM", "SIGHUP"] as NodeJS.Signals[]) {
268
- const handler = () => {
269
- detach()
270
- // Remove our listener before re-raising: re-killing with the handler
271
- // still installed re-delivers the signal to it forever (loop verified —
272
- // ctrl+c wedged pi instead of exiting). Gone, the re-raise falls through
273
- // to the default disposition and terminates; the idempotent "exit"
274
- // belt stays for any path that gets there.
275
- process.removeListener(sig, handler)
276
- process.kill(process.pid, sig)
277
- }
278
- process.on(sig, handler)
279
- }
280
- }
281
-
282
- function detach() {
283
- if (!attachment) return
284
- const { binary, name } = attachment
285
- attachment = null
286
- spawnSync(binary, ["unuse", name, "--pid", String(process.pid)], { stdio: "ignore", env: process.env })
287
- }
84
+ // env(), the combiner command/config/port resolution and the whole sharedserver
85
+ // lifecycle live in combiner-process.ts.
288
86
 
289
87
  // ── the extension ──────────────────────────────────────────────────
290
88
 
@@ -355,7 +153,16 @@ export default function mcpCombiner(pi: ExtensionAPI): void {
355
153
  }
356
154
 
357
155
  let connection: NativeCombinerConnection | undefined
156
+ // The combiner process, when we manage it (combiner-process.ts): connects wait
157
+ // for its first attach (`ready`), and ask it between refused retries. Host-owned
158
+ // or unmanaged combiners are someone else's: connect only.
159
+ const combinerProcess = manage && !hostOwned ? new CombinerProcess(clientLog) : undefined
160
+ // Stops CombinerProcess.watch at session_shutdown / reload teardown.
161
+ let stopCombinerWatch: (() => void) | undefined
358
162
  let nativeSurface: ReturnType<typeof activateNativeMode> | undefined
163
+ // Set once the footer exists (the `if (connection)` block below); the native
164
+ // surface, created first, reports registration progress through it.
165
+ let onToolProgress: ((done: number, total: number) => void) | undefined
359
166
  // Session-config HOLDER: everything the ladder shapes, resolved against a SESSION
360
167
  // cwd (worktree subagents / project switches get their own project layers).
361
168
  // Factory-time resolution with process.cwd() is the pre-session default; every
@@ -393,6 +200,12 @@ export default function mcpCombiner(pi: ExtensionAPI): void {
393
200
  }
394
201
  g.__piMcpCombinerDispose = []
395
202
  connection = new NativeCombinerConnection(connInputsFor(sessionCfg), clientLog)
203
+ if (combinerProcess) {
204
+ const proc = combinerProcess
205
+ const conn = connection
206
+ conn.setStartGate(proc.ready)
207
+ conn.setLivenessCheck(() => proc.onRefused())
208
+ }
396
209
  // The mcp router registers alongside the per-tool native surface (the same
397
210
  // owned connection — not a second proxy): tool_call gates such as
398
211
  // pi-permission-system and pi-subagents recognize MCP calls by the tool
@@ -409,6 +222,7 @@ export default function mcpCombiner(pi: ExtensionAPI): void {
409
222
  // session_start (post-setToken — the connection refuses to connect
410
223
  // without a grouping token); list_changed re-syncs ride resyncAll below.
411
224
  nativeSurface = activateNativeMode(pi, {
225
+ onToolProgress: (done, total) => onToolProgress?.(done, total),
412
226
  connection,
413
227
  // Getters, not snapshots: worktrees / project switches re-resolve
414
228
  // sessionCfg per session_start, and a load-time value would apply the
@@ -433,6 +247,17 @@ export default function mcpCombiner(pi: ExtensionAPI): void {
433
247
 
434
248
  if (connection) {
435
249
  const conn = connection // captured non-optional for the handlers below
250
+ // The connection keeps itself up (reconnect after a drop, background retry after
251
+ // a failed connect; combiner-connection.ts). The combiner process, when we
252
+ // manage it, reports process events: its going away triggers a reconnect, and
253
+ // the reconnect asks it (respawn within the cap, or attach to a new process).
254
+ const arm = () => {
255
+ conn.reopen()
256
+ conn.setAutoReconnect(true)
257
+ if (combinerProcess && !stopCombinerWatch)
258
+ stopCombinerWatch = combinerProcess.watch(() => conn.reconnect("the combiner process exited"))
259
+ }
260
+ arm()
436
261
  const registeredPrompts = new Set<string>()
437
262
  let footerTimer: NodeJS.Timeout | undefined
438
263
  let uiCtx: ExtensionContext["ui"] | undefined
@@ -448,12 +273,35 @@ export default function mcpCombiner(pi: ExtensionAPI): void {
448
273
  footerTimer = undefined
449
274
  uiCtx = undefined
450
275
  uiNotify = undefined
451
- void conn.reset("superseded by a newer extension instance (reload)")
276
+ stopCombinerWatch?.()
277
+ stopCombinerWatch = undefined
278
+ nativeSurface?.dispose()
279
+ void conn.close("superseded by a newer extension instance (reload)")
452
280
  })
453
281
 
282
+ // Native registration progress (undefined when no pass is registering).
283
+ let registering: RegisterProgress | undefined
284
+ let lastProgressPaint = 0
454
285
  const refreshFooter = () => {
455
286
  if (uiCtx)
456
- void updateFooter(conn, uiCtx, settings.mcpFooterKey, settings.mcpFooterStatus).catch(() => undefined)
287
+ void updateFooter(conn, uiCtx, settings.mcpFooterKey, settings.mcpFooterStatus, () => registering).catch(
288
+ () => undefined,
289
+ )
290
+ }
291
+ // Called after every registration slice. Repaint at most every 500 ms (each
292
+ // repaint fetches /health) and always on the final slice.
293
+ onToolProgress = (done, total) => {
294
+ const finished = done >= total
295
+ // A pass's last slice reports (total, total) and its end reports (0, 0):
296
+ // repaint for the first "finished" only.
297
+ const wasRegistering = registering !== undefined
298
+ registering = finished ? undefined : { done, total }
299
+ if (finished && !wasRegistering) return
300
+ const now = Date.now()
301
+ if (finished || now - lastProgressPaint >= 500) {
302
+ lastProgressPaint = now
303
+ refreshFooter()
304
+ }
457
305
  }
458
306
  const syncPrompts = () => {
459
307
  if (!settings.prompts) return
@@ -473,14 +321,9 @@ export default function mcpCombiner(pi: ExtensionAPI): void {
473
321
  conn.setHooks({
474
322
  onToolsChanged: resyncAll,
475
323
  onStateChange: (state) => {
476
- // Re-attach on (re)connect: a combiner bounce kills the instance our
477
- // sharedserver reference was attached to, and nothing else re-takes
478
- // ownership until the next session_start — an orphaned combiner then
479
- // grace-stops 30m later (sharedserver `use` is idempotent per pid, so
480
- // re-attaching on every connect is safe and cheap). Host-owned / unmanaged
481
- // combiners have nothing to attach to, and the factory returns before
482
- // `attachCombiner` is declared — calling it there is a TDZ ReferenceError.
483
- if (state === "connected" && !hostOwned && manage) attachCombiner(clientLog)
324
+ // A different combiner process now (someone restarted it)? Attach to
325
+ // it: same function, same ref (CombinerProcess.onReconnected).
326
+ if (state === "connected") void combinerProcess?.onReconnected().catch(() => undefined)
484
327
  refreshFooter()
485
328
  },
486
329
  // Stage 2: the widget hold announces its UI URL mid-call — open it.
@@ -491,6 +334,9 @@ export default function mcpCombiner(pi: ExtensionAPI): void {
491
334
 
492
335
  pi.on("session_start", (event, ctx) => {
493
336
  try {
337
+ // Re-arm auto-reconnect and the process watch if a host reused this
338
+ // instance after a session_shutdown (idempotent; pi 1.6 doesn't reuse).
339
+ arm()
494
340
  // SAFETY: capture ctx.ui ONCE, first — the getter asserts staleness,
495
341
  // the object does not; every async closure below uses the object only.
496
342
  const ctxUi = ctx.ui
@@ -563,12 +409,80 @@ export default function mcpCombiner(pi: ExtensionAPI): void {
563
409
  clientLog("error", `session setup failed: ${e instanceof Error ? e.message : String(e)}`)
564
410
  }
565
411
  })
412
+ // A turn that starts while tools are still registering (or the first connect
413
+ // is still retrying) would see only part of the catalog. pi awaits
414
+ // before_agent_start handlers and reads the live tool set afterwards, so
415
+ // waiting here puts every tool in the turn. The registration keeps yielding
416
+ // while we wait, so the UI stays live. pi has no abort for this hook today
417
+ // (Esc during the wait takes effect when it ends); ctx.signal is honoured if
418
+ // a future pi provides one.
419
+ pi.on("before_agent_start", async (_event, ctx) => {
420
+ const surface = nativeSurface
421
+ if (!surface?.busy()) return
422
+ // Still connecting: wait only for a combiner we just attached (it is
423
+ // starting up). A host-owned/unmanaged combiner that's down, or one whose
424
+ // attach failed, would only stall the turn for the whole retry budget.
425
+ const connecting = conn.state !== "connected"
426
+ if (connecting && !combinerProcess?.attached) return
427
+ const ui = ctx.ui
428
+ const notice = setTimeout(() => {
429
+ if (notify)
430
+ ui?.notify?.(
431
+ connecting
432
+ ? "mcp-combiner: waiting for the combiner to come up…"
433
+ : "mcp-combiner: waiting for MCP tools to finish registering…",
434
+ "info",
435
+ )
436
+ }, 250) // brief waits (a list_changed resync) stay silent
437
+ notice.unref()
438
+ const started = Date.now()
439
+ const outcome = await waitForRegistration(surface, {
440
+ signal: ctx.signal,
441
+ // pi has no abort for this hook: end the wait on Esc / Ctrl+C / Ctrl+D
442
+ // ourselves (pi still sees the key and cancels or quits as usual).
443
+ // A single Ctrl+C only clears the editor in pi; its second press within
444
+ // 500 ms quits, so that is what ends the wait.
445
+ onInterrupt: (interrupt) => {
446
+ let lastCtrlC = 0
447
+ return (
448
+ ui?.onTerminalInput?.((data) => {
449
+ if (matchesKey(data, "ctrl+c")) {
450
+ const now = Date.now()
451
+ if (now - lastCtrlC < 500) interrupt()
452
+ lastCtrlC = now
453
+ } else if (matchesKey(data, "escape")) interrupt()
454
+ // Ctrl+D quits only on an empty editor; with text it deletes forward.
455
+ else if (matchesKey(data, "ctrl+d") && !(ui?.getEditorText?.() ?? "")) interrupt()
456
+ return undefined
457
+ }) ?? (() => undefined)
458
+ )
459
+ },
460
+ })
461
+ clearTimeout(notice)
462
+ const waitedMs = Date.now() - started
463
+ const waited = `${(waitedMs / 1000).toFixed(1)} s`
464
+ if (outcome === "timeout") {
465
+ clientLog(
466
+ "warn",
467
+ `tool registration still running after ${waited}; the rest join from the turn's next model request`,
468
+ )
469
+ } else if (waitedMs >= 250) {
470
+ // Brief waits (a list_changed resync) stay silent, like the notice.
471
+ clientLog("info", `turn waited ${waited} for tool registration (${outcome})`)
472
+ }
473
+ })
474
+
566
475
  pi.on("session_shutdown", () => {
567
476
  if (footerTimer) {
568
477
  clearInterval(footerTimer)
569
478
  footerTimer = undefined
570
479
  }
571
- void conn.reset("session shutdown")
480
+ // Stop a registration pass in flight before pi retires this session's
481
+ // extension API (pi 1.6 creates a fresh instance for the next session).
482
+ stopCombinerWatch?.()
483
+ stopCombinerWatch = undefined
484
+ nativeSurface?.dispose()
485
+ void conn.close("session shutdown")
572
486
  })
573
487
  }
574
488
 
@@ -686,110 +600,21 @@ export default function mcpCombiner(pi: ExtensionAPI): void {
686
600
  }
687
601
 
688
602
  // ── process: launch on session_start, release on session_shutdown("quit") ──
689
- // Pi forbids starting background resources from the factory, so all of this is
690
- // deferred to session_start. session_start fires again on reload/new/resume/fork
691
- // within the same process; the `attachment` guard makes re-entry a no-op attach.
692
- const attachCombiner = (log: LogFn): void => {
693
- const binary = resolveSharedserver(
694
- {
695
- label: "mcp-combiner",
696
- minVersion: SHAREDSERVER_MIN_VERSION,
697
- installerUrl:
698
- "https://github.com/georgeharker/sharedserver/releases/latest/download/sharedserver-installer.sh",
699
- },
700
- env("SHAREDSERVER_BIN"),
701
- process.env,
702
- log,
703
- )
704
- if (!binary) {
705
- log("error", "sharedserver binary not found; set $SHAREDSERVER_BIN, or PI_MCP_COMBINER_MANAGE=false")
706
- return
707
- }
708
-
709
- const combiner = resolveCombiner(log)
710
- if (!combiner) {
711
- log(
712
- "error",
713
- "mcp-combiner could not be found or fetched; install uv and it is fetched from PyPI on demand, " +
714
- "or install mcp-combiner, or set $PI_MCP_COMBINER_COMMAND / $PI_MCP_COMBINER_CHECKOUT",
715
- )
716
- return
717
- }
718
-
719
- const cfgPath = resolveConfig(log)
720
- if (!cfgPath) return // resolveConfig already logged the specifics
721
-
722
- const name = env("PI_MCP_COMBINER_NAME") ?? DEFAULT_NAME
723
- const port = resolvePort(log)
724
- const grace = env("PI_MCP_COMBINER_GRACE") ?? DEFAULT_GRACE
725
-
726
- // Assemble: <combiner> [--mcp] --config <cfg> --port <port> [--host <host>]
727
- const serve: string[] = []
728
- const modern = combinerNeedsMcpFlag(combiner)
729
- if (modern) serve.push("--mcp")
730
- serve.push("--config", cfgPath, "--port", String(port))
731
- const host = env("PI_MCP_COMBINER_HOST")
732
- if (host) serve.push("--host", host)
733
-
734
- // Logging parity with the sibling plugins' two-file scheme: sharedserver captures
735
- // raw stdout/stderr (--log-file on `use`), and the combiner writes its own
736
- // --log-file. Both default under $XDG_STATE_HOME/mcp-combiner; "none" disables.
737
- // Combiner-side flags ride the same version gate as --mcp.
738
- const logDir = join(process.env.XDG_STATE_HOME || join(homedir(), ".local", "state"), "mcp-combiner")
739
- const pyLogFile = env("PI_MCP_COMBINER_PYLOG") ?? join(logDir, "mcp-combiner-py.log")
740
- if (modern) {
741
- if (pyLogFile !== "none") serve.push("--log-file", pyLogFile)
742
- serve.push("--log-level", env("PI_MCP_COMBINER_LOG_LEVEL") ?? "info")
743
- }
744
-
745
- const wrappedArgs = [...combiner.args, ...(combiner.extra ?? []), ...serve]
746
- const useArgs = [
747
- "use",
748
- name,
749
- "--pid",
750
- String(process.pid),
751
- "--grace-period",
752
- grace,
753
- "--metadata",
754
- `pi-${process.pid}`,
755
- ]
756
- const logFile = env("PI_MCP_COMBINER_LOG") ?? join(logDir, "mcp-combiner.log")
757
- if (logFile !== "none") {
758
- try {
759
- mkdirSync(dirname(logFile), { recursive: true })
760
- } catch {
761
- // best-effort — a failed mkdir just means sharedserver may drop the capture
762
- }
763
- useArgs.push("--log-file", logFile)
764
- }
765
- useArgs.push("--", combiner.cmd, ...wrappedArgs)
766
-
767
- installProcessCleanup()
768
- const result = spawnSync(binary, useArgs, { stdio: "pipe", env: process.env })
769
- if (result.error) {
770
- log("error", `${name}: failed to spawn sharedserver (${result.error.message})`)
771
- return
772
- }
773
- if (result.status !== 0) {
774
- const stderr = result.stderr?.toString().trim()
775
- log("error", `${name}: sharedserver use exited ${result.status}${stderr ? ` (${stderr})` : ""}`)
776
- return
777
- }
778
-
779
- attachment = { binary, name }
780
- log("info", `combiner "${name}" attached on port ${port} (${combiner.cmd} ${wrappedArgs.join(" ")})`)
781
- }
782
-
783
- pi.on("session_start", (_event, ctx) => {
784
- if (attachment) return // already attached in this process
785
- attachCombiner(makeLog(ctx, notify))
603
+ // Pi forbids starting background resources from the factory, so the attach is
604
+ // deferred to session_start. It fires again on reload/new/resume/fork within the
605
+ // same process; CombinerProcess keeps one ref per pi process, so re-entry is a
606
+ // no-op. Everything else about the process lives in combiner-process.ts.
607
+ const proc = combinerProcess
608
+ if (!proc) return // unreachable: combinerProcess exists exactly when manage && !hostOwned
609
+ pi.on("session_start", async (_event, ctx) => {
610
+ await proc.start(makeLog(ctx, notify))
786
611
  })
787
612
 
788
613
  pi.on("session_shutdown", (event: SessionShutdownEvent) => {
789
614
  // Only "quit" means the Pi process is actually leaving. reload/new/resume/fork
790
615
  // keep the process alive and a fresh session_start re-attaches — releasing the
791
616
  // refcount on those would needlessly drop (and re-take) the shared combiner.
792
- if (event.reason === "quit") detach()
617
+ if (event.reason === "quit") proc.quit()
793
618
  })
794
619
  }
795
620
 
@@ -972,41 +797,3 @@ function makeLog(ctx: ExtensionContext, notify: boolean): LogFn {
972
797
  }
973
798
  }
974
799
  }
975
-
976
- /** The port to serve on, reconciling PI_MCP_COMBINER_PORT with any explicit
977
- * $MCP_COMPANION_COMBINER_URL (which is what pi-mcp-adapter registers, so serving
978
- * anywhere else would be unreachable — the URL wins, same rule as the sibling plugins). */
979
- function resolvePort(log: LogFn): number {
980
- const raw = env("PI_MCP_COMBINER_PORT")
981
- let port = DEFAULT_PORT
982
- if (raw !== undefined) {
983
- const n = Number(raw)
984
- if (Number.isInteger(n) && n > 0) port = n
985
- else log("warn", `PI_MCP_COMBINER_PORT=${raw} is not a positive integer; using ${DEFAULT_PORT}`)
986
- }
987
- const url = env("MCP_COMPANION_COMBINER_URL")
988
- if (url && raw !== undefined) {
989
- let urlPort = Number.NaN
990
- try {
991
- urlPort = Number(new URL(url).port)
992
- } catch {
993
- // malformed URL — fall through to the no-usable-port warning below
994
- }
995
- if (!Number.isInteger(urlPort) || urlPort <= 0) {
996
- log(
997
- "warn",
998
- `MCP_COMPANION_COMBINER_URL=${url} has no explicit port; serving on ${port}. ` +
999
- `Use an explicit port in the URL (e.g. http://127.0.0.1:${port}/mcp).`,
1000
- )
1001
- } else if (urlPort !== port) {
1002
- log(
1003
- "warn",
1004
- `PI_MCP_COMBINER_PORT=${port} disagrees with MCP_COMPANION_COMBINER_URL=${url}; the URL is what ` +
1005
- `pi-mcp-adapter registers, so serving on ${port} would be unreachable — using ${urlPort}. ` +
1006
- "Set them to the same port.",
1007
- )
1008
- port = urlPort
1009
- }
1010
- }
1011
- return port
1012
- }