pi-mcp-extension 1.11.6 → 1.11.7

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-mcp-extension",
3
- "version": "1.11.6",
3
+ "version": "1.11.7",
4
4
  "description": "MCP (Model Context Protocol) client extension for the Pi coding agent — connect Pi to any MCP server",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -335,6 +335,26 @@ export class ConnectionCoordinator {
335
335
  turn.release();
336
336
  }
337
337
 
338
+ private async _startEagerServer(
339
+ name: string,
340
+ cfg: ServerConfig,
341
+ ctx: ExtensionContext,
342
+ authRequiredServers: Set<string>,
343
+ ): Promise<void> {
344
+ try {
345
+ await this.deps.manager.startServer(name, ctx.cwd);
346
+ } catch (err) {
347
+ if (err instanceof AuthRequiredError && cfg.auth && ctx.hasUI) {
348
+ authRequiredServers.add(name);
349
+ return;
350
+ }
351
+ // WHY: A cancelled start means the user stopped the server (/mcp:stop) or the
352
+ // session is tearing down; _notifyStartupFailure ignores AuthCancelledError so
353
+ // it is not reported as a bogus start failure.
354
+ this._notifyStartupFailure(name, ctx, err);
355
+ }
356
+ }
357
+
338
358
  async startEagerServers(
339
359
  serversToStart: Array<[string, ServerConfig]>,
340
360
  ctx: ExtensionContext,
@@ -344,21 +364,7 @@ export class ConnectionCoordinator {
344
364
 
345
365
  // Start all eager servers concurrently
346
366
  await Promise.allSettled(
347
- serversToStart.map(async ([name, cfg]) => {
348
- try {
349
- await this.deps.manager.startServer(name, ctx.cwd);
350
- } catch (err) {
351
- // WHY: A cancelled start means the user stopped the server (/mcp:stop) or the
352
- // session is tearing down; reporting it as a start failure would be a bogus error.
353
- if (err instanceof AuthCancelledError) return;
354
- if (err instanceof AuthRequiredError && cfg.auth && ctx.hasUI) {
355
- authRequiredServers.add(name);
356
- return;
357
- }
358
- const msg = formatErrorMessage(err);
359
- ctx.ui.notify(`pi-mcp: Failed to start ${name} — ${msg}`, "error");
360
- }
361
- }),
367
+ serversToStart.map(([name, cfg]) => this._startEagerServer(name, cfg, ctx, authRequiredServers)),
362
368
  );
363
369
 
364
370
  // WHY: Reconcile the footer hint once every eager start has settled — a declined
@@ -21,17 +21,33 @@ const execFileAsync = promisify(execFile);
21
21
 
22
22
  export interface LineSplitter {
23
23
  write(chunk: Buffer): void;
24
+ /** Emit the decoded remainder without finalising the decoder (teardown paths). */
25
+ flush(): void;
26
+ /** Finalise the decoder (real EOF) and emit whatever is left. Idempotent. */
24
27
  end(): void;
25
28
  }
26
29
 
27
30
  /**
28
- * Create a pure UTF-8 `StringDecoder`-based line splitter with idempotent `end()`.
31
+ * Create a pure UTF-8 `StringDecoder`-based line splitter with an idempotent `end()`.
32
+ *
33
+ * `flush()` and `end()` differ on purpose: `flush()` emits what has already been decoded and
34
+ * leaves an incomplete UTF-8 sequence buffered inside the decoder, while `end()` is terminal
35
+ * and replaces such a sequence with U+FFFD. Teardown uses `flush()` because bytes can still
36
+ * arrive after a forced close, and finalising the decoder first would turn a character split
37
+ * across that boundary into replacement characters.
29
38
  */
30
39
  export function createLineSplitter(onLine: (line: string) => void): LineSplitter {
31
40
  const decoder = new StringDecoder("utf8");
32
41
  let remainder = "";
33
42
  let flushed = false;
34
43
 
44
+ const emitRemainder = (): void => {
45
+ if (!remainder) return;
46
+ const trailing = remainder;
47
+ remainder = "";
48
+ onLine(trailing);
49
+ };
50
+
35
51
  return {
36
52
  write(chunk: Buffer): void {
37
53
  flushed = false;
@@ -42,15 +58,14 @@ export function createLineSplitter(onLine: (line: string) => void): LineSplitter
42
58
  onLine(rawLine);
43
59
  }
44
60
  },
61
+ flush(): void {
62
+ emitRemainder();
63
+ },
45
64
  end(): void {
46
65
  if (flushed) return;
47
66
  flushed = true;
48
67
  remainder += decoder.end();
49
- if (remainder) {
50
- const trailing = remainder;
51
- remainder = "";
52
- onLine(trailing);
53
- }
68
+ emitRemainder();
54
69
  },
55
70
  };
56
71
  }
@@ -60,6 +75,16 @@ export function createLineSplitter(onLine: (line: string) => void): LineSplitter
60
75
  /** Grace window for an exited child's pipes to drain naturally before force-destroying them. */
61
76
  const PIPE_DRAIN_GRACE_MS = 100;
62
77
 
78
+ /**
79
+ * How long a closed transport's stderr stream must stay quiet before its unterminated remainder
80
+ * is emitted.
81
+ *
82
+ * WHY: nothing ends the SDK's stderr `PassThrough` after close, so the last line has to be
83
+ * released by us; waiting for silence instead of flushing each chunk keeps a line whole when its
84
+ * bytes arrive across several ticks, and still surfaces the last one promptly.
85
+ */
86
+ export const POST_CLOSE_FLUSH_DELAY_MS = 100;
87
+
63
88
  interface StdioChildRecord {
64
89
  process: ChildProcess;
65
90
  closed: boolean;
@@ -76,6 +101,81 @@ interface StdioChildRecord {
76
101
  */
77
102
  const childRecords = new WeakMap<object, StdioChildRecord>();
78
103
 
104
+ /** A transport whose child stderr can be wired and whose `close()` can be wrapped. */
105
+ interface StderrCarrier {
106
+ stderr?: unknown;
107
+ close(): Promise<void>;
108
+ }
109
+
110
+ /**
111
+ * Split a stdio transport's stderr into lines and make them survive `close()`.
112
+ *
113
+ * Returns the provisional flush that teardown paths call before destroying the pipes, or
114
+ * `null` when the transport has no stderr stream to read.
115
+ *
116
+ * WHY: `StdioClientTransport.close()` never ends its stderr `PassThrough` — it only waits
117
+ * (bounded) for the child's `'close'` event — and a descendant that inherited the stderr write
118
+ * end keeps that event from firing. A line written without a trailing newline would then stay
119
+ * in the splitter's remainder forever. Flushing when close settles, and again after
120
+ * `POST_CLOSE_FLUSH_DELAY_MS` of silence for any chunks that arrive afterwards (nothing will
121
+ * emit `'end'` to do it), keeps the child's last words.
122
+ * Both flushes are provisional: they must not finalise the decoder, because the bytes of a
123
+ * character can be split across the close boundary; only the stream's own `'end'`/`'close'`
124
+ * finalises it.
125
+ */
126
+ export function instrumentStderr(
127
+ transport: StderrCarrier,
128
+ onLine: (line: string) => void,
129
+ ): (() => void) | null {
130
+ const stream = transport.stderr as NodeJS.EventEmitter | null | undefined;
131
+ if (!stream || typeof stream.on !== "function") return null;
132
+
133
+ const splitter = createLineSplitter(onLine);
134
+ let closed = false;
135
+ let idleFlush: NodeJS.Timeout | null = null;
136
+ const cancelIdleFlush = (): void => {
137
+ if (idleFlush) {
138
+ clearTimeout(idleFlush);
139
+ idleFlush = null;
140
+ }
141
+ };
142
+ const flush = (): void => {
143
+ cancelIdleFlush();
144
+ splitter.flush();
145
+ };
146
+ // WHY: after close settles nothing emits 'end', so a remainder nobody else will flush has to be
147
+ // released — but a single chunk boundary is not the end of a line. Waiting for the stream to go
148
+ // quiet keeps a line whose chunks straddle several ticks whole, while still surfacing the last
149
+ // unterminated one within POST_CLOSE_FLUSH_DELAY_MS.
150
+ const scheduleIdleFlush = (): void => {
151
+ cancelIdleFlush();
152
+ idleFlush = setTimeout(() => {
153
+ idleFlush = null;
154
+ splitter.flush();
155
+ }, POST_CLOSE_FLUSH_DELAY_MS);
156
+ idleFlush.unref();
157
+ };
158
+
159
+ stream.on("data", (chunk: Buffer) => {
160
+ splitter.write(chunk);
161
+ if (closed) scheduleIdleFlush();
162
+ });
163
+ const onStreamEnd = (): void => {
164
+ cancelIdleFlush();
165
+ splitter.end();
166
+ };
167
+ stream.on("end", onStreamEnd);
168
+ stream.on("close", onStreamEnd);
169
+
170
+ const origClose = transport.close.bind(transport);
171
+ transport.close = (): Promise<void> =>
172
+ origClose().finally(() => {
173
+ closed = true;
174
+ flush();
175
+ });
176
+ return flush;
177
+ }
178
+
79
179
  export interface InstrumentStdioTransportOptions {
80
180
  onPid(pid: number): void;
81
181
  onStderrLine(line: string): void;
@@ -83,8 +183,7 @@ export interface InstrumentStdioTransportOptions {
83
183
 
84
184
  /**
85
185
  * Wrap a `StdioClientTransport` to capture its child PID as soon as it spawns,
86
- * memoize `close()` across duplicate calls, and wire `stderr` through
87
- * `createLineSplitter`.
186
+ * memoize `close()` across duplicate calls, and wire `stderr` through `instrumentStderr`.
88
187
  */
89
188
  export function instrumentStdioTransport(
90
189
  transport: StdioClientTransport,
@@ -96,7 +195,9 @@ export function instrumentStdioTransport(
96
195
  const spawnedProcess = (): ChildProcess | undefined =>
97
196
  (transport as unknown as { _process?: ChildProcess })._process;
98
197
 
99
- let flushStderr: (() => void) | null = null;
198
+ // Wire stderr first: `instrumentStderr` wraps `close()` with the flush, and the memoization
199
+ // below has to sit on top of that wrapper.
200
+ const flushStderr = instrumentStderr(transport, onStderrLine);
100
201
 
101
202
  const recordProcess = (proc: ChildProcess | undefined): void => {
102
203
  if (!proc?.pid) return;
@@ -138,19 +239,6 @@ export function instrumentStdioTransport(
138
239
  }
139
240
  return closePromise;
140
241
  };
141
-
142
- if (transport.stderr) {
143
- const splitter = createLineSplitter(onStderrLine);
144
- transport.stderr.on("data", (chunk: Buffer) => {
145
- splitter.write(chunk);
146
- });
147
- const flush = (): void => {
148
- splitter.end();
149
- };
150
- flushStderr = flush;
151
- transport.stderr.on("end", flush);
152
- transport.stderr.on("close", flush);
153
- }
154
242
  }
155
243
 
156
244
  /**
@@ -18,7 +18,7 @@ import type { ServerConfig } from "./config.js";
18
18
  import { McpOAuthProvider } from "./oauth-provider.js";
19
19
  import { isAuthorizationHeader, stripAuthorizationHeader } from "./auth-challenge.js";
20
20
  import { reportDiagnostic } from "./debug-log.js";
21
- import { createLineSplitter } from "./stdio-process.js";
21
+ import { instrumentStderr } from "./stdio-process.js";
22
22
  import { sanitizeTerminalText } from "./terminal-text.js";
23
23
 
24
24
  function resolveEnv(extra?: Record<string, string>): Record<string, string> {
@@ -55,20 +55,18 @@ function createOAuthProvider(
55
55
  });
56
56
  }
57
57
 
58
+ /**
59
+ * Route a `createTransport(..., onStderr)` caller's stderr through the shared instrumentation.
60
+ *
61
+ * WHY: this used to keep its own line splitter that only flushed on the stream's 'end'/'close',
62
+ * so on this path a partial line written before a close was dropped — the same defect
63
+ * `instrumentStderr` fixes for `ServerManager` (#206).
64
+ */
58
65
  function wireStdioStderr(transport: StdioClientTransport, onStderr: (line: string) => void): void {
59
- if (!transport.stderr) return;
60
- const splitter = createLineSplitter((rawLine) => {
66
+ instrumentStderr(transport, (rawLine) => {
61
67
  const clean = sanitizeTerminalText(rawLine);
62
68
  if (clean) onStderr(clean);
63
69
  });
64
- transport.stderr.on("data", (chunk: Buffer) => {
65
- splitter.write(chunk);
66
- });
67
- const flush = (): void => {
68
- splitter.end();
69
- };
70
- transport.stderr.on("end", flush);
71
- transport.stderr.on("close", flush);
72
70
  }
73
71
 
74
72
  /** Expand a leading `~` / `~/` / `~\` to the home directory, the way Pi resolves a config `cwd`. */