@soleur/opencode 3.357.9 → 3.357.11

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.
@@ -62,22 +62,32 @@ if (!process.env.PENCIL_CLI_KEY) {
62
62
  // trace. Matches the hard-fail UX of the PENCIL_CLI_KEY gate above.
63
63
 
64
64
  let McpServer, StdioServerTransport, z, nodeSpawn;
65
- let existsSync, mkdirSync, renameSync, writeFileSync;
66
- let dirname, join, homedir, tmpdir;
67
- let enrichErrorMessage, sanitizeFilename, classifyResponse, shouldSkipSave, stripAnsi;
65
+ let existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, statSync, writeFileSync;
66
+ let dirname, isAbsolute, join, resolve, homedir, tmpdir;
67
+ let enrichErrorMessage, sanitizeFilename, classifyResponse, stripAnsi;
68
+ let runGuardedSave, diskTopLevelCount, memoryTopLevelCount, DISK_UNRECOGNIZED;
69
+ let formatReplCommand, planSpawn;
68
70
 
69
71
  try {
70
72
  ({ McpServer } = await import("@modelcontextprotocol/sdk/server/mcp.js"));
71
73
  ({ StdioServerTransport } = await import("@modelcontextprotocol/sdk/server/stdio.js"));
72
74
  ({ z } = await import("zod"));
73
75
  ({ spawn: nodeSpawn } = await import("node:child_process"));
74
- ({ existsSync, mkdirSync, renameSync, writeFileSync } = await import("node:fs"));
75
- ({ dirname, join } = await import("node:path"));
76
+ ({
77
+ existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, statSync, writeFileSync,
78
+ } = await import("node:fs"));
79
+ ({ dirname, isAbsolute, join, resolve } = await import("node:path"));
76
80
  ({ homedir, tmpdir } = await import("node:os"));
77
81
  ({ enrichErrorMessage } = await import("./pencil-error-enrichment.mjs"));
78
82
  ({ sanitizeFilename } = await import("./sanitize-filename.mjs"));
79
83
  ({ classifyResponse, stripAnsi } = await import("./pencil-response-classify.mjs"));
80
- ({ shouldSkipSave } = await import("./pencil-save-gate.mjs"));
84
+ ({
85
+ runGuardedSave,
86
+ diskTopLevelCount,
87
+ memoryTopLevelCount,
88
+ DISK_UNRECOGNIZED,
89
+ } = await import("./pencil-save-gate.mjs"));
90
+ ({ formatReplCommand, planSpawn } = await import("./pencil-repl-surface.mjs"));
81
91
  } catch (err) {
82
92
  process.stderr.write(
83
93
  `[pencil-adapter] ERROR: dependency import failed: ${err?.message ?? err}\n` +
@@ -126,19 +136,57 @@ function buildPencilEnv() {
126
136
  // The classifier lives in a sibling pure module so it can be unit-tested
127
137
  // without loading the MCP SDK. Auth-failure patterns (`pencil login`,
128
138
  // `Invalid API key`, `Unauthorized`, `HTTP 401`) classify as errors so
129
- // the post-mutation save gate (see `shouldSkipSave`) skips auto-save
130
- // and avoids overwriting .pen files with 0-byte output (#2630).
139
+ // the edit tools skip the auto-save when the engine reports an error
140
+ // rather than overwrite .pen files with 0-byte output (#2630).
131
141
 
132
- // --- Node ID extraction ---
142
+ // --- Small helpers ---
133
143
 
134
- function extractNodeIds(response) {
135
- const entries = [];
136
- const pattern = /Inserted node `([A-Za-z0-9_-]+)`/g;
137
- let match;
138
- while ((match = pattern.exec(response)) !== null) {
139
- entries.push(match[1]);
144
+ // Every stderr line and tool-result fragment built from engine or model text
145
+ // goes through these: a node name or a CLI error must not forge a log line
146
+ // (control characters, U+0085/U+2028/U+2029) or carry the credential.
147
+ function oneLine(value) {
148
+ return String(value ?? "").replace(/[\u0000-\u001f\u007f\u0085\u2028\u2029]+/g, " ").trim();
149
+ }
150
+
151
+ function redactKey(value) {
152
+ const key = process.env.PENCIL_CLI_KEY;
153
+ return key && key.length >= 8 ? String(value).split(key).join("<redacted>") : String(value);
154
+ }
155
+
156
+ // Untruncated reply text. classifyResponse() caps its text at 64 KiB for the
157
+ // error-pattern scan; a capped batch_get() is not valid JSON, so anything that
158
+ // PARSES a reply (the node counts behind the save sentinel) must read this.
159
+ function rawText(raw) {
160
+ return stripAnsi(String(raw ?? "")).trim();
161
+ }
162
+
163
+ // null when the file does not exist; any other read error propagates, because
164
+ // "could not read it" is not "nothing there to protect".
165
+ function readTextOrNull(file) {
166
+ try {
167
+ return readFileSync(file, "utf8");
168
+ } catch (err) {
169
+ if (err?.code === "ENOENT") return null;
170
+ throw err;
140
171
  }
141
- return entries;
172
+ }
173
+
174
+ // The engine writes through symlinks (measured on 0.2.9) and the sentinel reads
175
+ // through them too, so a link from a project's design.pen to an unrelated file
176
+ // would turn one edit into an overwrite of that file. Only plain .pen files.
177
+ function penPath(value, label) {
178
+ const abs = resolve(value);
179
+ if (!abs.toLowerCase().endsWith(".pen")) {
180
+ throw new Error(`${label} must be a .pen file (got ${abs})`);
181
+ }
182
+ try {
183
+ if (lstatSync(abs).isSymbolicLink()) {
184
+ throw new Error(`${label} ${abs} is a symlink; refusing (the engine writes through links)`);
185
+ }
186
+ } catch (err) {
187
+ if (err?.code !== "ENOENT") throw err;
188
+ }
189
+ return abs;
142
190
  }
143
191
 
144
192
  // --- Screenshot persistence ---
@@ -149,98 +197,183 @@ function saveScreenshot(base64Data, nodeId) {
149
197
  const screenshotDir = join(dirname(penFile), "screenshots");
150
198
  mkdirSync(screenshotDir, { recursive: true });
151
199
  const timestamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
152
- const filename = `${nodeId}-${timestamp}.png`;
153
- const filePath = join(screenshotDir, filename);
200
+ const safeId = String(nodeId).replace(/[^A-Za-z0-9_-]/g, "_");
201
+ const filePath = join(screenshotDir, `${safeId}-${timestamp}.png`);
154
202
  writeFileSync(filePath, Buffer.from(base64Data, "base64"));
155
203
  return filePath;
156
204
  }
157
205
 
158
206
  // --- Binary resolution ---
159
207
 
208
+ // Returns an ABSOLUTE path or throws. The binary is run as `node <path>`, and
209
+ // `node pencil` resolves ./pencil.js against the working directory, which is the
210
+ // project the user opened: a bare name there would execute repo-supplied code
211
+ // with PENCIL_CLI_KEY in its environment.
160
212
  function findPencilBinary() {
161
213
  const localPath = join(homedir(), ".local", "node_modules", ".bin", "pencil");
162
214
  if (existsSync(localPath)) return localPath;
163
- // Fall back to PATH lookup — spawn will resolve it
164
- return "pencil";
215
+ for (const dir of (process.env.PATH ?? "").split(":")) {
216
+ if (!dir || !isAbsolute(dir)) continue;
217
+ const candidate = join(dir, "pencil");
218
+ if (existsSync(candidate)) return candidate;
219
+ }
220
+ throw new Error(
221
+ "pencil CLI not found (looked in ~/.local/node_modules/.bin and PATH); run /soleur:pencil-setup"
222
+ );
165
223
  }
166
224
 
167
225
  // --- PencilProcess class ---
168
226
 
227
+ const FS_PROBE = {
228
+ exists: (p) => existsSync(p),
229
+ size: (p) => {
230
+ try {
231
+ return statSync(p).size;
232
+ } catch {
233
+ return 0;
234
+ }
235
+ },
236
+ };
237
+
238
+ // Set when open_document could not load the file it was given. Every tool errors
239
+ // until the next successful open_document, so nothing runs (or saves) against a
240
+ // document that is not the one the caller asked for. Cleared ONLY on success.
241
+ let openFailure = null;
242
+ const OPEN_FAILED_NEXT =
243
+ "Next step: open_document a different .pen path (the failed file was not modified), or restore it from version control. Do not delete it to bypass this.";
244
+
169
245
  class PencilProcess {
170
246
  constructor() {
171
247
  this.child = null;
172
248
  this.ready = false;
173
249
  this.buffer = "";
174
250
  this.stderrBuffer = "";
251
+ // The document the session is bound to. Set when a spawn reaches its prompt,
252
+ // cleared only by clearTarget() (a failed open_document). A FAILED respawn
253
+ // leaves it alone, so the next call retries the same file instead of
254
+ // falling through to a scratch document.
175
255
  this.outputFile = null;
176
- this.inputFile = null;
177
- this.nodeIdMap = new Map();
256
+ // The file the last successful spawn passed as --in (null = started empty).
257
+ this.lastInFile = null;
258
+ this.scratchFile = null;
178
259
  this._dataHandler = null;
260
+ this._onExit = null;
261
+ }
262
+
263
+ clearTarget() {
264
+ this.outputFile = null;
265
+ this.lastInFile = null;
179
266
  }
180
267
 
181
- async spawn(outFile, inFile = null) {
268
+ // Called only from inside the command queue, so spawns are serialized.
269
+ async ensureAlive() {
270
+ if (openFailure) throw new Error(`open failed: ${openFailure}\n${OPEN_FAILED_NEXT}`);
271
+ if (this.child && this.ready) return;
272
+ if (this.child) await this.kill(); // a half-started child is never reused
273
+ if (this.outputFile) {
274
+ // Respawn: no explicit input, so planSpawn reloads the saved file and a
275
+ // template can never overwrite saved edits. Before the first save it
276
+ // falls back to the template the target was opened from.
277
+ await this.spawn(this.outputFile, null, this.lastInFile);
278
+ return;
279
+ }
280
+ // No document opened yet: a private scratch document, so tools that need
281
+ // none (get_editor_state, get_guidelines) work before open_document.
282
+ if (!this.scratchFile) {
283
+ this.scratchFile = join(mkdtempSync(join(tmpdir(), "pencil-adapter-")), "scratch.pen");
284
+ }
285
+ await this.spawn(this.scratchFile);
286
+ }
287
+
288
+ // `explicitInFile` is the caller's template (open_document `inputPath`).
289
+ async spawn(outFile, explicitInFile = null, resumeInFile = null) {
182
290
  const binary = process.env.PENCIL_BINARY || findPencilBinary();
291
+ if (process.env.PENCIL_BINARY && !isAbsolute(process.env.PENCIL_BINARY)) {
292
+ throw new Error("PENCIL_BINARY must be an absolute path");
293
+ }
294
+ const { inFile } = planSpawn({
295
+ outFile,
296
+ initialInFile: explicitInFile,
297
+ resumeInFile,
298
+ probe: FS_PROBE,
299
+ });
183
300
  const args = ["interactive", "--out", outFile];
184
301
  if (inFile) {
185
302
  args.push("--in", inFile);
186
303
  }
187
304
 
188
- this.outputFile = outFile;
189
- this.inputFile = inFile;
190
305
  this.buffer = "";
191
- this.nodeIdMap.clear();
306
+ this.stderrBuffer = "";
307
+ this.ready = false;
192
308
 
193
309
  // Spawn pencil using the adapter's own Node binary (process.execPath)
194
310
  // instead of relying on the pencil script's #!/usr/bin/env node shebang,
195
311
  // which resolves to the system Node (potentially <22) and fails with
196
312
  // ERR_REQUIRE_ESM. This guarantees the child process uses the same
197
313
  // Node version (22+) that runs the adapter.
198
- this.child = nodeSpawn(process.execPath, [binary, ...args], {
314
+ const child = nodeSpawn(process.execPath, [binary, ...args], {
199
315
  stdio: ["pipe", "pipe", "pipe"],
200
316
  env: buildPencilEnv(),
201
317
  });
318
+ this.child = child;
202
319
 
203
- // Capture child stderr for error reporting AND pipe to adapter stderr
204
- this.child.stderr.on("data", (chunk) => {
205
- this.stderrBuffer += chunk.toString();
206
- process.stderr.write(chunk);
320
+ // Everything below is bound to THIS child: the events of a killed child can
321
+ // arrive after its replacement was spawned and must not touch the new one.
322
+ child.stderr.on("data", (chunk) => {
323
+ process.stderr.write(redactKey(chunk.toString()));
324
+ if (this.child === child) this.stderrBuffer += chunk.toString();
207
325
  });
326
+ // An EPIPE between the child's death and its close event must not crash the
327
+ // adapter; the close handler reports the death.
328
+ child.stdin.on("error", () => {});
208
329
 
209
- // Crash detection
210
- this.child.on("exit", (code, signal) => {
211
- this.ready = false;
212
- this.child = null;
330
+ const gone = (code, signal, err) => {
213
331
  process.stderr.write(
214
- `[pencil-adapter] pencil process exited: code=${code} signal=${signal}\n`
332
+ `[pencil-adapter] pencil process exited: code=${code} signal=${signal}${err ? ` error=${oneLine(err.message)}` : ""}\n`
215
333
  );
216
- });
217
-
218
- this.child.on("error", (err) => {
334
+ if (this.child !== child) return;
219
335
  this.ready = false;
220
336
  this.child = null;
221
- process.stderr.write(
222
- `[pencil-adapter] pencil process error: ${err.message}\n`
223
- );
224
- });
337
+ if (this._onExit) this._onExit(code, signal, err);
338
+ };
339
+ // `close`, not `exit`: it fires after the stdio streams drained, so the
340
+ // stderr tail in the failure message is complete.
341
+ child.on("close", (code, signal) => gone(code, signal));
342
+ child.on("error", (err) => gone(null, null, err));
225
343
 
226
- // Consume welcome banner + initial prompt
227
- await this.waitForPrompt(30000);
344
+ try {
345
+ await this.waitForPrompt(30000); // banner + initial prompt
346
+ } catch (err) {
347
+ if (this.child === child) await this.kill(); // never leave a half-started child behind
348
+ throw err;
349
+ }
350
+ this.outputFile = outFile;
351
+ this.lastInFile = inFile;
228
352
  this.ready = true;
229
353
  }
230
354
 
231
355
  async kill() {
232
- if (this.child) {
233
- this.child.kill("SIGTERM");
234
- this.child = null;
235
- this.ready = false;
236
- }
356
+ const child = this.child;
357
+ this.child = null;
358
+ this.ready = false;
359
+ if (!child || child.exitCode !== null || child.signalCode !== null) return;
360
+ await new Promise((resolveKill) => {
361
+ const escalate = setTimeout(() => child.kill("SIGKILL"), 2000);
362
+ const giveUp = setTimeout(done, 4000);
363
+ function done() {
364
+ clearTimeout(escalate);
365
+ clearTimeout(giveUp);
366
+ resolveKill();
367
+ }
368
+ child.once("close", done);
369
+ child.once("error", done);
370
+ child.kill("SIGTERM");
371
+ });
237
372
  }
238
373
 
239
- async restart(outFile, inFile = null) {
240
- await this.kill();
241
- // Brief delay to let the old process clean up
242
- await new Promise((r) => setTimeout(r, 200));
243
- await this.spawn(outFile, inFile);
374
+ async restart(outFile, explicitInFile = null) {
375
+ await this.kill(); // waits for the old child to be gone
376
+ await this.spawn(outFile, explicitInFile);
244
377
  }
245
378
 
246
379
  async sendCommand(cmd) {
@@ -250,21 +383,43 @@ class PencilProcess {
250
383
  this.buffer = "";
251
384
  this.stderrBuffer = "";
252
385
  this.child.stdin.write(cmd + "\n");
253
- const raw = await this.waitForPrompt(30000);
386
+ let raw;
387
+ try {
388
+ raw = await this.waitForPrompt(30000);
389
+ } catch (err) {
390
+ // A timed-out reply would otherwise be attributed to the NEXT command.
391
+ if (this.child) {
392
+ await this.kill();
393
+ throw new Error(
394
+ `${err.message}; pencil was stopped and restarts from ${this.outputFile ?? "a scratch document"} on the next call (anything not yet saved is lost)`
395
+ );
396
+ }
397
+ throw err;
398
+ }
254
399
  // If stdout response is empty but stderr has content, use stderr
400
+ // Every reply leaves here, so one redaction covers every sink that follows.
255
401
  if (!raw && this.stderrBuffer) {
256
- return this.stderrBuffer;
402
+ return redactKey(this.stderrBuffer);
257
403
  }
258
- return raw;
404
+ return redactKey(raw);
259
405
  }
260
406
 
261
407
  waitForPrompt(timeoutMs = 30000) {
262
- return new Promise((resolve, reject) => {
263
- const timeout = setTimeout(() => {
264
- if (this._dataHandler && this.child) {
265
- this.child.stdout.removeListener("data", this._dataHandler);
266
- }
408
+ return new Promise((resolvePrompt, reject) => {
409
+ const child = this.child;
410
+ if (!child) {
411
+ reject(new Error("[pencil-adapter] No child process to listen to"));
412
+ return;
413
+ }
414
+ const duringCommand = this.ready;
415
+ const cleanup = () => {
416
+ clearTimeout(timeout);
417
+ child.stdout.removeListener("data", this._dataHandler);
267
418
  this._dataHandler = null;
419
+ this._onExit = null;
420
+ };
421
+ const timeout = setTimeout(() => {
422
+ cleanup();
268
423
  reject(
269
424
  new Error(
270
425
  `[pencil-adapter] Timed out waiting for prompt after ${timeoutMs}ms`
@@ -272,6 +427,25 @@ class PencilProcess {
272
427
  );
273
428
  }, timeoutMs);
274
429
 
430
+ // A child that exits before its prompt (bad --in file, auth failure) or
431
+ // mid-command fails the wait immediately with its stderr tail, not after 30 s.
432
+ this._onExit = (code, signal, err) => {
433
+ cleanup();
434
+ const tail = redactKey(this.stderrBuffer)
435
+ .trim()
436
+ .split("\n")
437
+ .slice(-10)
438
+ .map(oneLine)
439
+ .filter(Boolean)
440
+ .join(" | ");
441
+ reject(
442
+ new Error(
443
+ `[pencil-adapter] pencil exited ${duringCommand ? "during a command (its effect is unknown)" : "before it was ready"} (code=${code} signal=${signal}${err ? ` error=${oneLine(err.message)}` : ""})` +
444
+ (tail ? `: ${tail}` : "")
445
+ )
446
+ );
447
+ };
448
+
275
449
  this._dataHandler = (chunk) => {
276
450
  this.buffer += chunk.toString();
277
451
  const stripped = stripAnsi(this.buffer);
@@ -280,12 +454,7 @@ class PencilProcess {
280
454
  const startsWithPrompt = stripped.startsWith("pencil > ");
281
455
 
282
456
  if (promptIdx !== -1 || startsWithPrompt) {
283
- clearTimeout(timeout);
284
- if (this.child) {
285
- this.child.stdout.removeListener("data", this._dataHandler);
286
- }
287
- this._dataHandler = null;
288
-
457
+ cleanup();
289
458
  let response;
290
459
  if (promptIdx !== -1) {
291
460
  response = stripped.substring(0, promptIdx);
@@ -293,16 +462,11 @@ class PencilProcess {
293
462
  // Buffer starts with prompt — empty response (initial prompt)
294
463
  response = "";
295
464
  }
296
- resolve(response.trim());
465
+ resolvePrompt(response.trim());
297
466
  }
298
467
  };
299
468
 
300
- if (this.child) {
301
- this.child.stdout.on("data", this._dataHandler);
302
- } else {
303
- clearTimeout(timeout);
304
- reject(new Error("[pencil-adapter] No child process to listen to"));
305
- }
469
+ child.stdout.on("data", this._dataHandler);
306
470
  });
307
471
  }
308
472
  }
@@ -317,8 +481,18 @@ class CommandQueue {
317
481
  }
318
482
 
319
483
  async enqueue(command) {
320
- return new Promise((resolve, reject) => {
321
- this.queue.push({ command, resolve, reject });
484
+ return this.runExclusive((send) => send(command));
485
+ }
486
+
487
+ // Run `fn` as ONE queue job: no other queued command, and no restart, can
488
+ // land while it runs. `fn` receives `send(cmd)`, which talks to the process
489
+ // directly (enqueueing from inside a job would wait on itself). The process is
490
+ // (re)started here, inside the serialized section, so two callers can never
491
+ // both spawn. Used for the save sentinel (probe + save), for an edit together
492
+ // with its auto-save, and for open_document's kill-and-respawn.
493
+ async runExclusive(fn, { ensure = true } = {}) {
494
+ return new Promise((resolveJob, reject) => {
495
+ this.queue.push({ job: fn, ensure, resolve: resolveJob, reject });
322
496
  if (!this.running) this._drain();
323
497
  });
324
498
  }
@@ -326,69 +500,57 @@ class CommandQueue {
326
500
  async _drain() {
327
501
  this.running = true;
328
502
  while (this.queue.length > 0) {
329
- const { command, resolve: res, reject: rej } = this.queue.shift();
503
+ const item = this.queue.shift();
330
504
  try {
331
- // Auto-restart if process died
332
- if (!this.process.ready && !this.process.child) {
333
- if (this.process.outputFile) {
334
- await this.process.spawn(
335
- this.process.outputFile,
336
- this.process.inputFile
337
- );
338
- } else {
339
- throw new Error(
340
- "Pencil process not running and no file to restart with"
341
- );
342
- }
343
- }
344
- const result = await this.process.sendCommand(command);
345
- res(result);
505
+ if (item.ensure) await this.process.ensureAlive();
506
+ item.resolve(await item.job((cmd) => this.process.sendCommand(cmd)));
346
507
  } catch (err) {
347
- rej(err);
508
+ item.reject(err);
348
509
  }
349
510
  }
350
511
  this.running = false;
351
512
  }
352
513
  }
353
514
 
354
- // --- REPL command formatting ---
355
-
356
- function formatReplCommand(toolName, params) {
357
- if (!params || Object.keys(params).length === 0) {
358
- return `${toolName}()`;
359
- }
360
- if (toolName === "batch_design") {
361
- return `batch_design({ operations: ${JSON.stringify(params.operations)} })`;
362
- }
363
- return `${toolName}(${JSON.stringify(params)})`;
364
- }
365
-
366
- // --- Lazy spawn helper ---
367
-
368
515
  const pencilProcess = new PencilProcess();
369
516
  const commandQueue = new CommandQueue(pencilProcess);
370
517
 
371
- // Tracks the classification of the most recent REPL mutation so open_document's
372
- // pre-restart save() can skip when the prior mutation errored. See
373
- // `shouldSkipSave` and the #2630 regression.
374
- let lastMutationClassification = null;
375
-
376
- async function ensureProcess() {
377
- if (!pencilProcess.ready && !pencilProcess.child) {
378
- if (pencilProcess.outputFile) {
379
- await pencilProcess.spawn(
380
- pencilProcess.outputFile,
381
- pencilProcess.inputFile
382
- );
383
- } else {
384
- // No document opened yet — use a temp file
385
- const tempFile = join(
386
- tmpdir(),
387
- `pencil-adapter-${process.pid}.pen`
388
- );
389
- await pencilProcess.spawn(tempFile);
518
+ process.on("exit", () => {
519
+ if (pencilProcess.scratchFile) {
520
+ try {
521
+ rmSync(dirname(pencilProcess.scratchFile), { recursive: true, force: true });
522
+ } catch {
523
+ // best effort
390
524
  }
391
525
  }
526
+ });
527
+
528
+ // --- Guarded save (the ONLY place the REPL `save` command is emitted) ---
529
+ //
530
+ // Must run inside an exclusive queue job (`send` is that job's channel): read the
531
+ // file on disk, probe the in-memory document, decide, then save, with nothing able
532
+ // to interleave. An empty document is never written over a file that holds nodes,
533
+ // and nothing is written over a file that is not a recognizable .pen (#11143; see
534
+ // pencil-save-gate.mjs). Callers: an edit's auto-save and the explicit `save` tool.
535
+
536
+ async function guardedSave(send, source) {
537
+ const file = pencilProcess.outputFile;
538
+ return runGuardedSave({
539
+ file,
540
+ source,
541
+ readDisk: async () => readTextOrNull(file),
542
+ probeMemory: async () => {
543
+ const raw = await send(formatReplCommand("batch_get", {}));
544
+ const verdict = classifyResponse(raw);
545
+ if (verdict.isError) throw new Error(oneLine(verdict.text).slice(0, 200));
546
+ return rawText(raw);
547
+ },
548
+ send: async () => send(formatReplCommand("save", {})),
549
+ });
550
+ }
551
+
552
+ function errorResult(text) {
553
+ return { content: [{ type: "text", text }], isError: true };
392
554
  }
393
555
 
394
556
  // --- MCP Server setup ---
@@ -398,50 +560,99 @@ const server = new McpServer({
398
560
  version: "0.0.1",
399
561
  });
400
562
 
563
+ // Every tool goes through here: an open-failed adapter refuses everything but
564
+ // open_document, and any thrown error (a REPL contract violation, a dead
565
+ // process, a timeout) becomes an isError result with the replacement hints.
566
+ function registerTool(name, schema, handler, { allowWhenOpenFailed = false, description } = {}) {
567
+ const callback = async (params) => {
568
+ if (openFailure && !allowWhenOpenFailed) {
569
+ return errorResult(
570
+ `open failed: ${openFailure}\nNo tool runs until open_document succeeds on a valid .pen file. ${OPEN_FAILED_NEXT}`
571
+ );
572
+ }
573
+ try {
574
+ return await handler(params ?? {});
575
+ } catch (err) {
576
+ return errorResult(enrichErrorMessage(redactKey(String(err?.message ?? err))));
577
+ }
578
+ };
579
+ if (description) server.tool(name, description, schema, callback);
580
+ else server.tool(name, schema, callback);
581
+ }
582
+
401
583
  // --- Read-only tool handler factory ---
402
584
 
403
- function registerReadOnlyTool(name, schema, handler) {
404
- server.tool(name, schema, async (params) => {
405
- await ensureProcess();
585
+ function registerReadOnlyTool(name, schema, options) {
586
+ registerTool(name, schema, async (params) => {
406
587
  const cmd = formatReplCommand(name, params);
407
588
  const raw = await commandQueue.enqueue(cmd);
408
589
  const { text, isError } = classifyResponse(raw);
409
- if (handler) {
410
- return handler(text, isError);
411
- }
412
- return { content: [{ type: "text", text }], isError };
413
- });
590
+ return {
591
+ content: [{ type: "text", text: isError ? enrichErrorMessage(text) : text }],
592
+ isError,
593
+ };
594
+ }, options);
414
595
  }
415
596
 
416
597
  // --- Mutating tool handler factory ---
417
598
 
418
- function registerMutatingTool(name, schema, postHandler) {
419
- server.tool(name, schema, async (params) => {
420
- await ensureProcess();
599
+ function registerMutatingTool(name, schema, options) {
600
+ registerTool(name, schema, async (params) => {
421
601
  const cmd = formatReplCommand(name, params);
422
- const raw = await commandQueue.enqueue(cmd);
423
- const classification = classifyResponse(raw);
424
- lastMutationClassification = classification;
425
- const { text, isError } = classification;
426
- if (isError) {
427
- // Surface the error AND skip the auto-save that used to clobber
428
- // .pen files with 0-byte output. See `shouldSkipSave`.
429
- process.stderr.write(
430
- `[pencil-adapter] SKIPPED save (${name} errored): ${text.slice(0, 200)}\n`
431
- );
432
- return { content: [{ type: "text", text: enrichErrorMessage(text) }], isError: true };
433
- }
434
- if (postHandler) {
435
- postHandler(text);
436
- }
437
- // Auto-save after mutating operations — gated by `shouldSkipSave` so a
438
- // failed mutation does not trigger a save that overwrites valid .pen
439
- // content with empty or stale state.
440
- if (!shouldSkipSave(classification)) {
441
- await commandQueue.enqueue("save()");
442
- }
443
- return { content: [{ type: "text", text }] };
444
- });
602
+ // ONE exclusive job: the edit and its save cannot be separated by a crash
603
+ // respawn, a queued open_document or another command, so a success reply
604
+ // means the edit was applied AND persisted (or the reply says otherwise).
605
+ return commandQueue.runExclusive(async (send) => {
606
+ const classification = classifyResponse(await send(cmd));
607
+ const { text, isError } = classification;
608
+ if (isError) {
609
+ // Surface the error AND skip the save: a failed edit must not trigger a
610
+ // write that replaces valid .pen content with empty or stale state.
611
+ process.stderr.write(
612
+ `[pencil-adapter] SKIPPED save (${name} errored): ${oneLine(text).slice(0, 200)}\n`
613
+ );
614
+ return errorResult(enrichErrorMessage(text));
615
+ }
616
+ let saved;
617
+ try {
618
+ saved = await guardedSave(send, "auto-save");
619
+ } catch (err) {
620
+ const reason = oneLine(redactKey(err?.message ?? err));
621
+ process.stderr.write(`[pencil-adapter] save did not complete after ${name}: ${reason}\n`);
622
+ return errorResult(
623
+ `The edit was applied in memory but the save did not complete (${reason}); it is not persisted.`
624
+ );
625
+ }
626
+ if (saved.refused) {
627
+ process.stderr.write(`[pencil-adapter] ${oneLine(saved.message.split("\n")[0])} (${saved.reason})\n`);
628
+ return errorResult(`${saved.message}\n\nEngine response to the edit:\n${text}`);
629
+ }
630
+ const after = classifyResponse(saved.raw);
631
+ if (after.isError) {
632
+ process.stderr.write(`[pencil-adapter] save failed after ${name}: ${oneLine(after.text).slice(0, 200)}\n`);
633
+ return errorResult(`Edit applied but the save failed: ${enrichErrorMessage(after.text)}`);
634
+ }
635
+ return { content: [{ type: "text", text }] };
636
+ });
637
+ }, options);
638
+ }
639
+
640
+ // Tools @pencil.dev/cli 0.2.9 removed. They stay registered so Desktop-style
641
+ // callers get a replacement hint (pencil-error-enrichment.mjs) instead of a bare
642
+ // "tool not found"; formatReplCommand throws `Unknown tool:` for them, so nothing
643
+ // reaches the engine and nothing is saved. The schema is empty on purpose: any
644
+ // arguments the caller sends must reach the hint, not an SDK validation error.
645
+ // Retire with #11156.
646
+ function registerRemovedTool(name) {
647
+ registerTool(
648
+ name,
649
+ {},
650
+ async () => {
651
+ formatReplCommand(name, {});
652
+ throw new Error(`Unknown tool: ${name}`);
653
+ },
654
+ { description: `Not available in the headless adapter. ${enrichErrorMessage(`Unknown tool: ${name}`)}` }
655
+ );
445
656
  }
446
657
 
447
658
  // --- Read-only tools ---
@@ -450,33 +661,37 @@ registerReadOnlyTool("batch_get", {
450
661
  patterns: z.array(z.record(z.string(), z.unknown())).optional(),
451
662
  nodeIds: z.array(z.string()).optional(),
452
663
  readDepth: z.number().optional(),
664
+ parentId: z.string().optional(),
665
+ searchDepth: z.number().optional(),
666
+ resolveInstances: z.boolean().optional(),
667
+ resolveVariables: z.boolean().optional(),
668
+ includePathGeometry: z.boolean().optional(),
453
669
  });
454
670
 
455
- registerReadOnlyTool("get_editor_state", {
456
- include_schema: z.boolean(),
457
- });
671
+ registerReadOnlyTool(
672
+ "get_editor_state",
673
+ {
674
+ include_schema: z.boolean(),
675
+ },
676
+ {
677
+ description:
678
+ "Editor state of the open document. Pass { include_schema: true } once to get the full batch_design operation grammar.",
679
+ }
680
+ );
458
681
 
459
682
  registerReadOnlyTool("get_guidelines", {
460
- topic: z.enum([
461
- "code",
462
- "table",
463
- "tailwind",
464
- "landing-page",
465
- "design-system",
466
- "slides",
467
- "mobile-app",
468
- "web-app",
469
- ]),
683
+ category: z.string().optional(),
684
+ name: z.string().optional(),
685
+ params: z.record(z.string(), z.unknown()).optional(),
470
686
  });
471
687
 
472
688
  // get_screenshot — special handling for base64 image data + auto-save to disk
473
- server.tool("get_screenshot", { nodeId: z.string() }, async ({ nodeId }) => {
474
- await ensureProcess();
689
+ registerTool("get_screenshot", { nodeId: z.string() }, async ({ nodeId }) => {
475
690
  const cmd = formatReplCommand("get_screenshot", { nodeId });
476
691
  const raw = await commandQueue.enqueue(cmd);
477
692
  const { text, isError } = classifyResponse(raw);
478
693
  if (isError) {
479
- return { content: [{ type: "text", text }], isError: true };
694
+ return errorResult(enrichErrorMessage(text));
480
695
  }
481
696
 
482
697
  // Try parsing as JSON — pencil returns {"image":"<base64>","mimeType":"image/png"}
@@ -503,36 +718,31 @@ server.tool("get_screenshot", { nodeId: z.string() }, async ({ nodeId }) => {
503
718
  return { content: [{ type: "text", text }] };
504
719
  }
505
720
 
506
- // Auto-save screenshot to disk
507
- const savedPath = saveScreenshot(base64Data, nodeId);
721
+ // Auto-save screenshot to disk; a disk failure must not discard the image
722
+ let savedPath = null;
723
+ let saveNote = null;
724
+ try {
725
+ savedPath = saveScreenshot(base64Data, nodeId);
726
+ } catch (err) {
727
+ saveNote = `Screenshot not saved to disk: ${oneLine(err?.message ?? err)}`;
728
+ process.stderr.write(`[pencil-adapter] ${saveNote}\n`);
729
+ }
508
730
  const content = [{ type: "image", data: base64Data, mimeType }];
509
731
  if (savedPath) {
510
732
  content.push({ type: "text", text: `Screenshot saved: ${savedPath}` });
733
+ } else if (saveNote) {
734
+ content.push({ type: "text", text: saveNote });
511
735
  }
512
736
  return { content };
513
737
  });
514
738
 
515
- registerReadOnlyTool("get_style_guide", {
516
- name: z.string().optional(),
517
- tags: z.array(z.string()).optional(),
518
- });
519
-
520
- registerReadOnlyTool("get_style_guide_tags", {});
739
+ registerRemovedTool("get_style_guide");
740
+ registerRemovedTool("get_style_guide_tags");
521
741
 
522
742
  registerReadOnlyTool("get_variables", {});
523
743
 
524
- registerReadOnlyTool("find_empty_space_on_canvas", {
525
- direction: z.enum(["top", "right", "bottom", "left"]),
526
- height: z.number(),
527
- width: z.number(),
528
- padding: z.number(),
529
- nodeId: z.string().optional(),
530
- });
531
-
532
- registerReadOnlyTool("search_all_unique_properties", {
533
- parents: z.array(z.string()),
534
- properties: z.array(z.string()),
535
- });
744
+ registerRemovedTool("find_empty_space_on_canvas");
745
+ registerRemovedTool("search_all_unique_properties");
536
746
 
537
747
  registerReadOnlyTool("snapshot_layout", {
538
748
  parentId: z.string().optional(),
@@ -541,7 +751,7 @@ registerReadOnlyTool("snapshot_layout", {
541
751
  });
542
752
 
543
753
  // export_nodes — custom handler to rename exported files using node names
544
- server.tool(
754
+ registerTool(
545
755
  "export_nodes",
546
756
  {
547
757
  nodeIds: z.array(z.string()),
@@ -551,7 +761,6 @@ server.tool(
551
761
  quality: z.number().optional(),
552
762
  },
553
763
  async ({ nodeIds, outputDir, format, scale, quality }) => {
554
- await ensureProcess();
555
764
  const ext = format || "png";
556
765
 
557
766
  // Step 1: Try to get node names via batch_get
@@ -559,8 +768,7 @@ server.tool(
559
768
  try {
560
769
  const batchCmd = formatReplCommand("batch_get", { nodeIds });
561
770
  const batchRaw = await commandQueue.enqueue(batchCmd);
562
- const { text: batchText } = classifyResponse(batchRaw);
563
- const parsed = JSON.parse(batchText);
771
+ const parsed = JSON.parse(rawText(batchRaw));
564
772
  if (parsed.nodes && Array.isArray(parsed.nodes)) {
565
773
  for (const node of parsed.nodes) {
566
774
  if (node.id && node.name) {
@@ -569,7 +777,7 @@ server.tool(
569
777
  }
570
778
  }
571
779
  } catch (err) {
572
- process.stderr.write(`[pencil-adapter] batch_get for node names failed: ${err.message}\n`);
780
+ process.stderr.write(`[pencil-adapter] batch_get for node names failed: ${oneLine(err.message)}\n`);
573
781
  }
574
782
 
575
783
  // Step 2: Run the original export_nodes command
@@ -577,7 +785,7 @@ server.tool(
577
785
  const raw = await commandQueue.enqueue(cmd);
578
786
  const { text, isError } = classifyResponse(raw);
579
787
  if (isError) {
580
- return { content: [{ type: "text", text }], isError: true };
788
+ return errorResult(enrichErrorMessage(text));
581
789
  }
582
790
 
583
791
  // Step 3: Rename exported files from nodeId to sanitized name
@@ -585,17 +793,23 @@ server.tool(
585
793
  for (const nodeId of nodeIds) {
586
794
  const nodeName = nameMap.get(nodeId);
587
795
  const sanitized = nodeName ? sanitizeFilename(nodeName) : "";
588
- if (!sanitized) {
796
+ if (!sanitized || !/^[A-Za-z0-9_-]+$/.test(nodeId)) {
589
797
  renamedFiles.push(`${nodeId}.${ext}`);
590
798
  continue;
591
799
  }
592
800
  const oldPath = join(outputDir, `${nodeId}.${ext}`);
593
801
  const newPath = join(outputDir, `${sanitized}.${ext}`);
802
+ if (existsSync(newPath)) {
803
+ // renameSync would silently replace an unrelated file of that name
804
+ process.stderr.write(`[pencil-adapter] rename skipped: ${oneLine(newPath)} already exists\n`);
805
+ renamedFiles.push(`${nodeId}.${ext}`);
806
+ continue;
807
+ }
594
808
  try {
595
809
  renameSync(oldPath, newPath);
596
810
  renamedFiles.push(`${sanitized}.${ext}`);
597
811
  } catch (err) {
598
- process.stderr.write(`[pencil-adapter] rename ${oldPath} -> ${newPath} failed: ${err.message}\n`);
812
+ process.stderr.write(`[pencil-adapter] rename ${oneLine(oldPath)} -> ${oneLine(newPath)} failed: ${oneLine(err.message)}\n`);
599
813
  renamedFiles.push(`${nodeId}.${ext}`);
600
814
  }
601
815
  }
@@ -607,120 +821,108 @@ server.tool(
607
821
 
608
822
  // --- Mutating tools (auto-save after) ---
609
823
 
610
- registerMutatingTool(
611
- "batch_design",
612
- { operations: z.string() },
613
- (text) => {
614
- // Extract and track node IDs
615
- const nodeIds = extractNodeIds(text);
616
- for (const id of nodeIds) {
617
- pencilProcess.nodeIdMap.set(id, id);
618
- }
619
- }
620
- );
621
-
622
- registerMutatingTool("replace_all_matching_properties", {
623
- parents: z.array(z.string()),
624
- properties: z.record(z.string(), z.unknown()),
824
+ registerMutatingTool("batch_design", { operations: z.string() }, {
825
+ description:
826
+ "Run a Pencil operation script (Insert, Update, Copy, Replace, Move, Delete, Generate, with short aliases I, U, C, R, M, D, G). " +
827
+ "The field is `operations` (the engine's own name for it is `input`). Full grammar: call get_editor_state({ include_schema: true }) once. " +
828
+ "The document is saved after every successful call; a refused save is reported as an error.",
625
829
  });
626
830
 
627
- // set_variables — auto-coerce bare values into {type, value} objects
628
- server.tool(
629
- "set_variables",
630
- {
631
- variables: z.record(z.string(), z.unknown()),
632
- replace: z.boolean().optional(),
633
- },
634
- async ({ variables, replace }) => {
635
- await ensureProcess();
636
- // Coerce bare values: "#hex" → {type:"color"}, number → {type:"number"}, string → {type:"string"}
637
- const coerced = {};
638
- for (const [key, val] of Object.entries(variables)) {
639
- if (val && typeof val === "object" && val.type && val.value !== undefined) {
640
- coerced[key] = val; // already typed
641
- } else if (typeof val === "string" && /^#[0-9a-fA-F]{3,8}$/.test(val)) {
642
- coerced[key] = { type: "color", value: val };
643
- } else if (typeof val === "number") {
644
- coerced[key] = { type: "number", value: val };
645
- } else if (typeof val === "string") {
646
- coerced[key] = { type: "string", value: val };
647
- } else {
648
- coerced[key] = val; // pass through unknown shapes
649
- }
650
- }
651
- const params = { variables: coerced };
652
- if (replace !== undefined) params.replace = replace;
653
- const cmd = formatReplCommand("set_variables", params);
654
- const raw = await commandQueue.enqueue(cmd);
655
- const classification = classifyResponse(raw);
656
- lastMutationClassification = classification;
657
- const { text, isError } = classification;
658
- if (isError) {
659
- let enriched = text;
660
- if (/does not have a valid definition/i.test(text)) {
661
- enriched += '\nExpected: { "type": "color" | "string" | "number", "value": <value> }';
662
- } else if (/invalid type property/i.test(text)) {
663
- enriched += "\nValid types: color, string, number";
664
- }
665
- process.stderr.write(
666
- `[pencil-adapter] SKIPPED save (set_variables errored): ${text.slice(0, 200)}\n`
667
- );
668
- return { content: [{ type: "text", text: enriched }], isError: true };
669
- }
670
- if (!shouldSkipSave(classification)) {
671
- await commandQueue.enqueue("save()");
672
- }
673
- return { content: [{ type: "text", text }] };
674
- }
675
- );
831
+ registerRemovedTool("replace_all_matching_properties");
832
+ registerRemovedTool("set_variables");
676
833
 
677
834
  // --- Meta tools ---
678
835
 
679
- server.tool(
836
+ registerTool(
680
837
  "open_document",
681
838
  {
682
839
  filePath: z.string(),
683
840
  inputPath: z.string().optional(),
684
841
  },
685
842
  async ({ filePath, inputPath }) => {
686
- // Save current document first if process is running — but skip when the
687
- // preceding mutation errored (would overwrite good content with 0 bytes).
688
- if (pencilProcess.ready && !shouldSkipSave(lastMutationClassification)) {
689
- try {
690
- await commandQueue.enqueue("save()");
691
- } catch {
692
- // Process may have died — proceed with restart
693
- }
694
- } else if (pencilProcess.ready && shouldSkipSave(lastMutationClassification)) {
695
- process.stderr.write(
696
- "[pencil-adapter] SKIPPED pre-restart save (prior mutation errored)\n"
697
- );
698
- }
699
- await pencilProcess.restart(filePath, inputPath);
700
- // Reset classification — new document means prior error is no longer relevant.
701
- lastMutationClassification = null;
702
- return {
703
- content: [{ type: "text", text: `Opened ${filePath}` }],
704
- };
843
+ // Absolute .pen paths, never a symlink: the child process and the save
844
+ // sentinel must agree on which file is meant, and the engine writes through
845
+ // links. A refusal here changes no session state.
846
+ const outFile = penPath(filePath, "filePath");
847
+ const inFile = inputPath ? penPath(inputPath, "inputPath") : null;
848
+
849
+ // The kill-and-respawn runs inside the same exclusive section as the saves,
850
+ // so no queued command or save can land between the old document going away
851
+ // and the new one loading. There is no pre-switch save: every successful edit
852
+ // is saved in the same job (registerMutatingTool), so it could only persist
853
+ // state the sentinel would refuse.
854
+ return commandQueue.runExclusive(
855
+ async (send) => {
856
+ if (inFile && inFile !== outFile && diskTopLevelCount(readTextOrNull(outFile)) !== null) {
857
+ return errorResult(
858
+ `Refusing to open: ${outFile} already holds a document and inputPath ${inFile} would replace it on the first save. ` +
859
+ `Open ${outFile} without inputPath, or open a new .pen path.`
860
+ );
861
+ }
862
+ try {
863
+ await pencilProcess.restart(outFile, inFile);
864
+ const loadedFrom = pencilProcess.lastInFile;
865
+ const memoryCount = memoryTopLevelCount(
866
+ rawText(await send(formatReplCommand("batch_get", {})))
867
+ );
868
+ let note = "";
869
+ if (loadedFrom) {
870
+ const diskCount = diskTopLevelCount(readTextOrNull(loadedFrom));
871
+ if (diskCount === DISK_UNRECOGNIZED) {
872
+ throw new Error(
873
+ `${loadedFrom} exists but is not a recognizable .pen document (the engine loads such a file as empty); it was not modified`
874
+ );
875
+ }
876
+ if (typeof diskCount === "number" && diskCount > 0 && !(memoryCount > 0)) {
877
+ throw new Error(
878
+ `${loadedFrom} holds ${diskCount} top-level node(s) on disk but loaded ${memoryCount === null ? "unreadable" : "empty"}; it was not modified`
879
+ );
880
+ }
881
+ if (diskCount === 0) {
882
+ note = ` (${loadedFrom} is an empty document; if you expected content, check version control)`;
883
+ }
884
+ }
885
+ openFailure = null;
886
+ return {
887
+ content: [
888
+ {
889
+ type: "text",
890
+ text: `Opened ${outFile} (${memoryCount === null ? "unknown" : memoryCount} top-level node(s) loaded)${note}`,
891
+ },
892
+ ],
893
+ };
894
+ } catch (err) {
895
+ openFailure = oneLine(redactKey(err?.message ?? err));
896
+ pencilProcess.clearTarget();
897
+ await pencilProcess.kill();
898
+ process.stderr.write(`[pencil-adapter] open failed: ${openFailure}\n`);
899
+ return errorResult(
900
+ `open failed: ${openFailure}\nNo other tool runs until open_document succeeds. ${OPEN_FAILED_NEXT}`
901
+ );
902
+ }
903
+ },
904
+ { ensure: false }
905
+ );
906
+ },
907
+ {
908
+ allowWhenOpenFailed: true,
909
+ description:
910
+ "Open (or create) a .pen document. Reports how many top-level nodes loaded. A failure leaves the file untouched and refuses every other tool until open_document succeeds; recover by opening a different path.",
705
911
  }
706
912
  );
707
913
 
708
- server.tool("save", {}, async () => {
709
- await ensureProcess();
710
- // Explicit save requests are NOT gated — the caller has asked for save
711
- // and the adapter must surface its actual result. But when a prior
712
- // mutation classified as an error, log a stderr note so the sequence
713
- // (failed mutation → explicit save) is visible in the MCP log. Matches
714
- // the observability posture for gated auto-saves in registerMutatingTool.
715
- if (shouldSkipSave(lastMutationClassification)) {
716
- process.stderr.write(
717
- "[pencil-adapter] NOTE: explicit save() after preceding errored mutation " +
718
- "— running at caller's request, but the saved file may not reflect intended state.\n"
719
- );
914
+ registerTool("save", {}, async () => {
915
+ // Explicit saves are subject to the same empty-overwrite sentinel as the
916
+ // auto-save, inside one exclusive job.
917
+ const saved = await commandQueue.runExclusive((send) => guardedSave(send, "save"));
918
+ if (saved.refused) {
919
+ process.stderr.write(`[pencil-adapter] ${oneLine(saved.message.split("\n")[0])} (${saved.reason})\n`);
920
+ return errorResult(saved.message);
720
921
  }
721
- const raw = await commandQueue.enqueue("save()");
722
- const { text, isError } = classifyResponse(raw);
723
- return { content: [{ type: "text", text }], isError };
922
+ const { text, isError } = classifyResponse(saved.raw);
923
+ return isError
924
+ ? errorResult(enrichErrorMessage(text))
925
+ : { content: [{ type: "text", text }] };
724
926
  });
725
927
 
726
928
  // --- Start server ---