pi-mcp-extension 1.14.2 → 1.14.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -325,7 +325,7 @@ The log is written to `<agent dir>/logs/pi-mcp.log` (JSON Lines, one event per l
325
325
 
326
326
  - **Off by default.** Without `PI_MCP_DEBUG=1` no log file is created.
327
327
  - **Private.** The directory is `0o700` and the file is `0o600`, like the OAuth credential files.
328
- - **Bounded.** The file is rotated to `pi-mcp.log.1` at ~2 MB; a single backup is kept.
328
+ - **Bounded.** The file is rotated to `pi-mcp.log.1` at ~2 MB; a single backup is kept. Concurrent Pi processes share the log without locking: a rotation that loses that race is not an error (the entry is still appended), and re-checking the size before `rename` skips rotating when the file shrank or disappeared so a peer's freshly rotated backup is not overwritten while still rotating when a peer merely appended.
329
329
  - **Redacted.** Only allow-listed field names are recorded, and a delimiter-aware pass masks anything that looks like a credential:
330
330
  - OAuth tokens, authorization codes, and PKCE verifiers
331
331
  - API keys and other JSON or key/value secrets (`api_key`, `x-api-key`, `private_key`, `password`, `secret`, `token`, and prefixed forms such as `db_password` or `aws_secret_access_key`)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-mcp-extension",
3
- "version": "1.14.2",
3
+ "version": "1.14.3",
4
4
  "description": "Full-featured, lightweight MCP extension for the Pi coding agent: stdio, SSE & Streamable HTTP transports, OAuth 2.1 (PKCE + DCR), lazy/eager lifecycles — minimal dependencies, zero bloat.",
5
5
  "type": "module",
6
6
  "keywords": [
package/src/debug-log.ts CHANGED
@@ -20,7 +20,7 @@
20
20
  * mistake.
21
21
  */
22
22
 
23
- import { appendFile, chmod, mkdir, rename, stat, unlink } from "node:fs/promises";
23
+ import { appendFile, chmod, mkdir, rename, stat } from "node:fs/promises";
24
24
  import { join } from "node:path";
25
25
  import {
26
26
  buildLogEntry,
@@ -76,7 +76,6 @@ export interface DebugLogFs {
76
76
  stat(path: string): Promise<{ size: number }>;
77
77
  rename(oldPath: string, newPath: string): Promise<void>;
78
78
  chmod(path: string, mode: number): Promise<void>;
79
- unlink(path: string): Promise<void>;
80
79
  }
81
80
 
82
81
  export interface DebugLogDeps {
@@ -92,7 +91,6 @@ export function createDefaultDebugLogDeps(): DebugLogDeps {
92
91
  stat: (path) => stat(path),
93
92
  rename: (oldPath, newPath) => rename(oldPath, newPath),
94
93
  chmod: (path, mode) => chmod(path, mode),
95
- unlink: (path) => unlink(path),
96
94
  },
97
95
  now: () => new Date(),
98
96
  };
@@ -146,37 +144,116 @@ export class DebugLog {
146
144
  }
147
145
 
148
146
  private async _append(line: string): Promise<void> {
149
- const fs = this.deps.fs;
150
- if (!this.dirReady) {
151
- await fs.mkdir(this.dir, { recursive: true, mode: DEBUG_LOG_DIR_MODE });
152
- await fs.chmod(this.dir, DEBUG_LOG_DIR_MODE);
153
- this.dirReady = true;
154
- }
147
+ await this._ensureDir();
155
148
  await this._rotateIfNeeded(Buffer.byteLength(line, "utf8"));
156
- await fs.appendFile(this.filePath, line, { mode: DEBUG_LOG_FILE_MODE });
157
- if (!this.fileModeEnsured) {
149
+ try {
150
+ await this.deps.fs.appendFile(this.filePath, line, { mode: DEBUG_LOG_FILE_MODE });
151
+ } catch (err) {
152
+ // WHY: `ENOENT` on `appendFile` means `<agentDir>/logs` disappeared after
153
+ // it was created. Recreating the directory and retrying once keeps that
154
+ // from dropping the entry or tripping the once-per-process failure latch;
155
+ // a second failure is a real one.
156
+ if (!isErrnoException(err, "ENOENT")) throw err;
157
+ this.dirReady = false;
158
+ this.fileModeEnsured = false;
159
+ await this._ensureDir();
160
+ await this.deps.fs.appendFile(this.filePath, line, { mode: DEBUG_LOG_FILE_MODE });
161
+ }
162
+ await this._ensureFileMode();
163
+ }
164
+
165
+ private async _ensureDir(): Promise<void> {
166
+ if (this.dirReady) return;
167
+ try {
168
+ await this._createDir();
169
+ } catch (err) {
170
+ // WHY: Something removed `<agentDir>/logs` between the mkdir and the chmod
171
+ // (a peer Pi process pruning an agent dir, a sandbox reset). Recreating it
172
+ // keeps that from dropping the entry; a second failure is a real one.
173
+ if (!isErrnoException(err, "ENOENT")) throw err;
174
+ await this._createDir();
175
+ }
176
+ this.dirReady = true;
177
+ }
178
+
179
+ private async _createDir(): Promise<void> {
180
+ const fs = this.deps.fs;
181
+ await fs.mkdir(this.dir, { recursive: true, mode: DEBUG_LOG_DIR_MODE });
182
+ await fs.chmod(this.dir, DEBUG_LOG_DIR_MODE);
183
+ }
184
+
185
+ private async _ensureFileMode(): Promise<void> {
186
+ if (this.fileModeEnsured) return;
187
+ try {
158
188
  // WHY: `mode` only applies when the file is created; an existing file may
159
189
  // have looser permissions, so the mode is enforced once per logger.
160
- await fs.chmod(this.filePath, DEBUG_LOG_FILE_MODE);
190
+ await this.deps.fs.chmod(this.filePath, DEBUG_LOG_FILE_MODE);
161
191
  this.fileModeEnsured = true;
192
+ } catch (err) {
193
+ // WHY: A peer Pi process sharing this log rotated `pi-mcp.log` between the
194
+ // append and this chmod, so it already holds the line. Leaving the flag
195
+ // false re-applies the mode on the file the next write creates instead of
196
+ // reporting a logger failure for a race that lost nothing.
197
+ if (!isErrnoException(err, "ENOENT")) throw err;
162
198
  }
163
199
  }
164
200
 
165
201
  private async _rotateIfNeeded(incomingBytes: number): Promise<void> {
166
- const fs = this.deps.fs;
167
- let size = 0;
202
+ const size = await this._logSize();
203
+ if (size === null || size <= 0) return;
204
+ if (size + incomingBytes <= DEBUG_LOG_MAX_BYTES) return;
205
+ // WHY: Re-read immediately before renaming to narrow the lock-free race
206
+ // window: if the log vanished or shrank (`currentSize < size`), a peer
207
+ // process already rotated it (and possibly recreated a smaller one), so
208
+ // renaming again would overwrite the backup that peer just produced. A plain
209
+ // peer append (`currentSize >= size`) leaves the file over the cap and still
210
+ // rotates. Either way, `pi-mcp.log` is no longer the pre-rotation file, so
211
+ // `0o600` must be re-enforced after the append.
212
+ const currentSize = await this._logSize();
213
+ if (currentSize === null) return;
214
+ this.fileModeEnsured = false;
215
+ if (currentSize < size) return;
216
+ await this._rotate();
217
+ }
218
+
219
+ /** Size of the log file: `0` when it is absent, `null` when it is unknown. */
220
+ private async _logSize(): Promise<number | null> {
168
221
  try {
169
- size = (await fs.stat(this.filePath)).size;
170
- } catch {
171
- // WHY: The log file does not exist yet — there is nothing to rotate.
172
- return;
222
+ return (await this.deps.fs.stat(this.filePath)).size;
223
+ } catch (err) {
224
+ if (isErrnoException(err, "ENOENT")) {
225
+ // WHY: An absent file means the initial write has not run yet or a peer
226
+ // rotated `pi-mcp.log` away since this logger last ensured `0o600`.
227
+ this.fileModeEnsured = false;
228
+ return 0;
229
+ }
230
+ // WHY: Any other stat failure leaves the size unknown. Rotation is only an
231
+ // optimization — the caller appends anyway rather than dropping the line,
232
+ // and the cap is re-checked on the next write that can read the size.
233
+ return null;
173
234
  }
174
- if (size <= 0 || size + incomingBytes <= DEBUG_LOG_MAX_BYTES) return;
175
- await fs.unlink(this.rotatedFilePath).catch(() => {
176
- // WHY: No previous backup to remove — the rename below creates the only one.
177
- });
178
- await fs.rename(this.filePath, this.rotatedFilePath);
179
235
  }
236
+
237
+ private async _rotate(): Promise<void> {
238
+ this.fileModeEnsured = false;
239
+ try {
240
+ // WHY: One rename, no unlink: `rename` replaces the previous backup
241
+ // directly (POSIX `rename(2)`, Windows `MoveFileExW`), so there is no
242
+ // unlink-before-rename gap in which a peer process that rotated in the
243
+ // meantime loses the 2 MB of history its backup just preserved.
244
+ await this.deps.fs.rename(this.filePath, this.rotatedFilePath);
245
+ } catch (err) {
246
+ // WHY: A peer Pi process sharing this log rotated `pi-mcp.log` first, so
247
+ // there is nothing to move — its backup is the one that stays. The append
248
+ // below recreates the file and writes the incoming line into it.
249
+ if (!isErrnoException(err, "ENOENT")) throw err;
250
+ }
251
+ }
252
+ }
253
+
254
+ /** True when `err` is a Node.js errno exception carrying `code`. */
255
+ function isErrnoException(err: unknown, code: string): boolean {
256
+ return (err as NodeJS.ErrnoException | null)?.code === code;
180
257
  }
181
258
 
182
259
  // ─── Diagnostic Sink ──────────────────────────────────────────────────────────