@soleur/opencode 3.359.18 → 3.360.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,72 +1,141 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- // pencil-mcp-adapter.mjs — MCP server bridging Claude Code to pencil interactive REPL
4
- // Architecture: Claude Code ←(MCP stdio)→ this adapter ←(stdin/stdout REPL)→ pencil interactive
3
+ // pencil-mcp-adapter.mjs — MCP server bridging Claude Code to the pen.dev interactive REPL
4
+ // Architecture: Claude Code <-(MCP stdio)-> this adapter <-(stdin/stdout REPL)-> `pen interactive`
5
+ // (@pen.dev/cli 0.3.13, pinned in check_deps.sh and scripts/pen-cli/).
5
6
  //
6
- // The Node-version gate, argv defense, and PENCIL_CLI_KEY hard-fail run BEFORE
7
- // any module imports so a broken registration exits with a clear adapter-authored
8
- // error instead of ERR_MODULE_NOT_FOUND from the MCP SDK. All imports are dynamic
9
- // (`await import`) for the same reason — static imports resolve during module
10
- // parsing, before any top-level statement runs. Rule:
11
- // cq-pencil-mcp-silent-drop-diagnosis-checklist.
12
-
13
- // --- Node version gate ---
14
-
15
- const [major, minor] = process.version.slice(1).split(".").map(Number);
16
- if (major < 22 || (major === 22 && minor < 9)) {
17
- process.stderr.write(
18
- `[pencil-adapter] Node >= 22.9.0 required, got ${process.version}\n`
19
- );
20
- process.exit(1);
7
+ // The agent-facing `mcp__pencil__*` tool names are stable (hooks and prose are keyed on
8
+ // them); each live tool is translated onto the engine's REPL (`execute`, `get_app_state`,
9
+ // `read_skill`, `save`) through pencil-repl-surface.mjs, and tools the engine cannot honour
10
+ // are registered as removed-tool stubs with an actionable hint (pencil-error-enrichment.mjs).
11
+ //
12
+ // The Node-version gate, argv defense, and the credential hard-fail run BEFORE any module
13
+ // imports so a broken registration exits with a clear adapter-authored error instead of
14
+ // ERR_MODULE_NOT_FOUND from the MCP SDK. All imports are dynamic (`await import`) for the
15
+ // same reason — static imports resolve during module parsing, before any top-level
16
+ // statement runs. Rule: ex-cq-pencil-mcp-silent-drop-diagnosis-checklist.
17
+ //
18
+ // Binary trust (the child holds the credential): the pen CLI is resolved only under the
19
+ // installing user's own prefix, and an override travels in this process's ARGV
20
+ // (`--pencil-binary=<abs>`, set by the user-approved MCP registration), never in an
21
+ // environment variable a project settings file could set. See findPenBinary / trustedOverride.
22
+
23
+ // --- Node version gate (numeric: a string compare orders 22.9.0 after 22.19.0) ---
24
+ // NODE_FLOOR is an inline copy of pencil-repl-surface.mjs's (this gate runs before any
25
+ // import can); pencil-repl-surface.test.ts pins it, that module and check_deps.sh together.
26
+
27
+ const NODE_FLOOR = [22, 19, 0];
28
+ {
29
+ const have = process.version.slice(1).split(".").map((n) => parseInt(n, 10) || 0);
30
+ let below = false;
31
+ for (let i = 0; i < 3; i++) {
32
+ if (have[i] !== NODE_FLOOR[i]) {
33
+ below = have[i] < NODE_FLOOR[i];
34
+ break;
35
+ }
36
+ }
37
+ if (below) {
38
+ process.stderr.write(
39
+ `[pencil-adapter] ERROR: Node >= ${NODE_FLOOR.join(".")} required (@pen.dev/cli needs it), got ${process.version}.\n` +
40
+ "[pencil-adapter] Run `/soleur:pencil-setup` (it runs `check_deps.sh --auto`; in a Soleur checkout: `bash plugins/soleur/skills/pencil-setup/scripts/check_deps.sh --auto`) to find or install a supported Node, then re-register.\n"
41
+ );
42
+ process.exit(1);
43
+ }
21
44
  }
22
45
 
23
46
  // --- Defense-in-depth: parse -e KEY=VALUE from argv ---
24
- // If `claude mcp add` passes -e flags as args instead of env vars
25
- // (e.g., -e placed after -- separator), inject them into process.env.
26
-
47
+ // If `claude mcp add` passes -e flags as args instead of env vars (e.g., -e placed after
48
+ // the -- separator), inject the credential into process.env. Only the two credential
49
+ // names are honoured; argv is visible to other local users, so a key that arrives this
50
+ // way is called out (value-free).
51
+
52
+ let keyFromArgv = false;
53
+ // `--pencil-binary=<absolute path>`: the only way to point the adapter at another engine
54
+ // binary (stub tests, the live probe). Validated at spawn time by trustedOverride().
55
+ let PENCIL_BINARY_ARG = null;
27
56
  for (let i = 2; i < process.argv.length; i++) {
57
+ if (process.argv[i].startsWith("--pencil-binary=")) {
58
+ PENCIL_BINARY_ARG = process.argv[i].slice("--pencil-binary=".length) || null;
59
+ continue;
60
+ }
28
61
  if (process.argv[i] === "-e" && i + 1 < process.argv.length) {
29
62
  const eqIdx = process.argv[i + 1].indexOf("=");
30
63
  if (eqIdx > 0) {
31
- const key = process.argv[i + 1].slice(0, eqIdx);
64
+ const name = process.argv[i + 1].slice(0, eqIdx);
32
65
  const val = process.argv[i + 1].slice(eqIdx + 1);
33
- if (!process.env[key]) {
34
- process.env[key] = val;
66
+ if (name === "PEN_CLI_KEY" || name === "PENCIL_CLI_KEY") {
67
+ if (!(process.env[name] ?? "").trim()) {
68
+ process.env[name] = val;
69
+ keyFromArgv = true;
70
+ }
71
+ } else {
72
+ process.stderr.write(
73
+ `[pencil-adapter] ignoring -e ${name.replace(/[^A-Za-z0-9_]/g, "?").slice(0, 40)}: only PEN_CLI_KEY and PENCIL_CLI_KEY are accepted\n`
74
+ );
35
75
  }
36
76
  }
37
77
  i++; // skip the value arg
38
78
  }
39
79
  }
80
+ if (PENCIL_BINARY_ARG === null && (process.env.PENCIL_BINARY ?? "") !== "") {
81
+ process.stderr.write(
82
+ "[pencil-adapter] WARN: the PENCIL_BINARY environment variable is ignored (a project settings file can set it). " +
83
+ "To run another engine binary, register the adapter with --pencil-binary=<absolute path> in its arguments.\n"
84
+ );
85
+ }
86
+ if (keyFromArgv) {
87
+ process.stderr.write(
88
+ "[pencil-adapter] WARN: the credential arrived on argv (-e), and argv is visible to other local users. " +
89
+ "Register with -e BEFORE -- so it travels in the environment instead.\n"
90
+ );
91
+ }
92
+
93
+ // --- Credential: resolved ONCE, then removed from process.env ---
94
+ // PEN_CLI_KEY wins; PENCIL_CLI_KEY is the deprecated fallback (same value, still works).
95
+ // An empty or whitespace-only value counts as unset. Runs BEFORE the MCP SDK import so
96
+ // the exit message is adapter-authored. A missing key used to be a stderr warning that
97
+ // let the adapter boot and every REPL mutation return an auth error the auto-save ran
98
+ // over — producing 0-byte .pen files the caller mistook for success (#2630).
40
99
 
41
- // --- PENCIL_CLI_KEY hard-fail ---
42
- // Runs BEFORE MCP SDK import so the exit message is adapter-authored, not a
43
- // raw ERR_MODULE_NOT_FOUND. Previously this was a stderr WARNING that let the
44
- // adapter boot and every REPL mutation return an auth error the auto-save ran
45
- // over — producing 0-byte .pen files the caller mistook for successful stubs
46
- // (#2630).
100
+ const API_KEY = (process.env.PEN_CLI_KEY ?? "").trim() || (process.env.PENCIL_CLI_KEY ?? "").trim();
101
+ const KEY_FROM_FALLBACK = !(process.env.PEN_CLI_KEY ?? "").trim() && API_KEY !== "";
102
+ delete process.env.PEN_CLI_KEY;
103
+ delete process.env.PENCIL_CLI_KEY;
47
104
 
48
- if (!process.env.PENCIL_CLI_KEY) {
105
+ if (!API_KEY) {
49
106
  process.stderr.write(
50
- "[pencil-adapter] ERROR: PENCIL_CLI_KEY not set. Refusing to start.\n" +
51
- "[pencil-adapter] If you used `claude mcp add`, ensure -e appears BEFORE --\n" +
52
- "[pencil-adapter] Run `/soleur:pencil-setup` to re-register with a valid key.\n"
107
+ "[pencil-adapter] ERROR: PEN_CLI_KEY not set. Refusing to start.\n" +
108
+ "[pencil-adapter] (PENCIL_CLI_KEY is accepted as a deprecated fallback; an empty value counts as unset.)\n" +
109
+ "[pencil-adapter] If you used `claude mcp add`, ensure -e appears BEFORE --\n" +
110
+ "[pencil-adapter] Run `/soleur:pencil-setup` to re-register with a valid key.\n"
53
111
  );
54
112
  process.exit(1);
55
113
  }
114
+ if (KEY_FROM_FALLBACK) {
115
+ process.stderr.write(
116
+ "[pencil-adapter] WARN: PENCIL_CLI_KEY is deprecated; register the same value as PEN_CLI_KEY. Using it for now.\n"
117
+ );
118
+ }
56
119
 
57
120
  // --- Dynamic imports (deferred so the gates above run first) ---
58
121
  //
59
- // Wrapped in try/catch so a missing `node_modules/@modelcontextprotocol/sdk`
60
- // (e.g., after a drifted install that copied the adapter but not its deps)
61
- // surfaces as an adapter-authored error rather than an unhandledRejection
62
- // trace. Matches the hard-fail UX of the PENCIL_CLI_KEY gate above.
122
+ // Wrapped in try/catch so a missing `node_modules/@modelcontextprotocol/sdk` (e.g., after
123
+ // a drifted install that copied the adapter but not its deps) surfaces as an
124
+ // adapter-authored error rather than an unhandledRejection trace.
63
125
 
64
126
  let McpServer, StdioServerTransport, z, nodeSpawn;
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;
127
+ let existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync;
128
+ let openSync, closeSync, fstatSync, readSync, fsConstants;
129
+ let basename, dirname, isAbsolute, join, resolve, sep;
130
+ let homedir, tmpdir, userInfo;
131
+ let enrichErrorMessage, removedToolHint, REMOVED_TOOL_NAMES, RAW_CALL_STEERING, sanitizeFilename, classifyResponse, stripAnsi, createAnsiStripper;
132
+ let runGuardedSave, diskTopLevelCount, memoryTopLevelCount, fingerprintState, savedReplyPath, hash8;
133
+ let loadFidelityFailure, notPersistedMessage, recreatedNote, isDefiniteSaveFailure, saveFailureLine;
134
+ let formatReplCommand, planSpawn, REPL_PROMPT;
135
+ let buildBatchDesignCommand, buildScreenshotCommand, buildExportCommand, buildVariablesCommand;
136
+ let buildEditorStateCommand, buildReadSkillCommand, newCountNonce, buildCountCommand;
137
+ let validateNodeIds, validateExportFormat, validateScale, validateQuality, validateOutputDir, EXPORT_FORMATS;
138
+ let redactionForms, redactText, createRollingRedactor, heldPrefixLength;
70
139
 
71
140
  try {
72
141
  ({ McpServer } = await import("@modelcontextprotocol/sdk/server/mcp.js"));
@@ -74,106 +143,157 @@ try {
74
143
  ({ z } = await import("zod"));
75
144
  ({ spawn: nodeSpawn } = await import("node:child_process"));
76
145
  ({
77
- existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, statSync, writeFileSync,
146
+ existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync,
147
+ openSync, closeSync, fstatSync, readSync, constants: fsConstants,
78
148
  } = await import("node:fs"));
79
- ({ dirname, isAbsolute, join, resolve } = await import("node:path"));
80
- ({ homedir, tmpdir } = await import("node:os"));
81
- ({ enrichErrorMessage } = await import("./pencil-error-enrichment.mjs"));
149
+ ({ basename, dirname, isAbsolute, join, resolve, sep } = await import("node:path"));
150
+ ({ homedir, tmpdir, userInfo } = await import("node:os"));
151
+ ({ enrichErrorMessage, removedToolHint, REMOVED_TOOL_NAMES, RAW_CALL_STEERING } = await import("./pencil-error-enrichment.mjs"));
82
152
  ({ sanitizeFilename } = await import("./sanitize-filename.mjs"));
83
- ({ classifyResponse, stripAnsi } = await import("./pencil-response-classify.mjs"));
153
+ ({ classifyResponse, stripAnsi, createAnsiStripper } = await import("./pencil-response-classify.mjs"));
84
154
  ({
85
155
  runGuardedSave,
86
156
  diskTopLevelCount,
87
157
  memoryTopLevelCount,
88
- DISK_UNRECOGNIZED,
158
+ fingerprintState,
159
+ savedReplyPath,
160
+ hash8,
161
+ loadFidelityFailure,
162
+ notPersistedMessage,
163
+ recreatedNote,
164
+ isDefiniteSaveFailure,
165
+ saveFailureLine,
89
166
  } = await import("./pencil-save-gate.mjs"));
90
- ({ formatReplCommand, planSpawn } = await import("./pencil-repl-surface.mjs"));
167
+ ({
168
+ formatReplCommand,
169
+ planSpawn,
170
+ REPL_PROMPT,
171
+ buildBatchDesignCommand,
172
+ buildScreenshotCommand,
173
+ buildExportCommand,
174
+ buildVariablesCommand,
175
+ buildEditorStateCommand,
176
+ buildReadSkillCommand,
177
+ newCountNonce,
178
+ buildCountCommand,
179
+ validateNodeIds,
180
+ validateExportFormat,
181
+ validateScale,
182
+ validateQuality,
183
+ validateOutputDir,
184
+ EXPORT_FORMATS,
185
+ redactionForms,
186
+ redactText,
187
+ createRollingRedactor,
188
+ heldPrefixLength,
189
+ } = await import("./pencil-repl-surface.mjs"));
91
190
  } catch (err) {
92
191
  process.stderr.write(
93
192
  `[pencil-adapter] ERROR: dependency import failed: ${err?.message ?? err}\n` +
94
193
  "[pencil-adapter] The installed adapter at ~/.local/share/pencil-adapter may be\n" +
95
- "[pencil-adapter] missing node_modules or out of sync with repo. Re-run:\n" +
96
- "[pencil-adapter] bash plugins/soleur/skills/pencil-setup/scripts/copy_adapter.sh\n" +
97
- "[pencil-adapter] or re-run /soleur:pencil-setup to refresh the install.\n"
194
+ "[pencil-adapter] missing node_modules or out of sync. Run /soleur:pencil-setup to refresh the install\n" +
195
+ "[pencil-adapter] (in a Soleur checkout: bash plugins/soleur/skills/pencil-setup/scripts/copy_adapter.sh).\n"
98
196
  );
99
197
  process.exit(1);
100
198
  }
101
199
 
102
- // --- Env allowlist ---
103
-
104
- function buildPencilEnv() {
105
- const allowed = [
106
- "HOME",
107
- "PATH",
108
- "NODE_ENV",
109
- "LANG",
110
- "TERM",
111
- "USER",
112
- "SHELL",
113
- "TMPDIR",
114
- "PENCIL_CLI_KEY",
115
- ];
116
- const env = {};
117
- for (const key of allowed) {
118
- if (process.env[key] !== undefined) {
119
- env[key] = process.env[key];
120
- }
121
- }
122
- // Prepend the adapter's own Node directory to PATH so that pencil's
123
- // `#!/usr/bin/env node` shebang resolves to the same Node version (22+)
124
- // that runs the adapter, not an incompatible system Node.
125
- const nodeDir = dirname(process.execPath);
126
- if (env.PATH) {
127
- env.PATH = `${nodeDir}:${env.PATH}`;
128
- } else {
129
- env.PATH = nodeDir;
130
- }
131
- return env;
132
- }
133
-
134
- // `stripAnsi` and `classifyResponse` are imported from
135
- // `pencil-response-classify.mjs` (see the dynamic-import block above).
136
- // The classifier lives in a sibling pure module so it can be unit-tested
137
- // without loading the MCP SDK. Auth-failure patterns (`pencil login`,
138
- // `Invalid API key`, `Unauthorized`, `HTTP 401`) classify as errors so
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).
141
-
142
200
  // --- Small helpers ---
143
201
 
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.
202
+ // Every stderr line and tool-result fragment built from engine or model text goes through
203
+ // these: a node name or a CLI error must not forge a log line (control characters,
204
+ // U+0085/U+2028/U+2029) or carry the credential.
147
205
  function oneLine(value) {
148
206
  return String(value ?? "").replace(/[\u0000-\u001f\u007f\u0085\u2028\u2029]+/g, " ").trim();
149
207
  }
150
208
 
209
+ const REDACT_FORMS = redactionForms(API_KEY);
210
+
211
+ // Raw, trimmed, JSON-escaped, URL-encoded and base64 spellings of the credential.
151
212
  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);
213
+ return redactText(String(value ?? ""), REDACT_FORMS);
154
214
  }
155
215
 
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.
216
+ // Untruncated reply text. classifyResponse() caps its text at 64 KiB for the error-pattern
217
+ // scan; anything that PARSES a reply (the count line, the screenshot JSON) reads this.
159
218
  function rawText(raw) {
160
219
  return stripAnsi(String(raw ?? "")).trim();
161
220
  }
162
221
 
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) {
222
+ // Every wait and escalation in one place (milliseconds).
223
+ const TIMEOUTS = {
224
+ spawnPromptMs: 30000, // banner + first prompt of a new engine
225
+ replyMs: 30000, // one command's reply
226
+ promptQuietMs: 50, // the prompt must end the buffer, and stderr must stay quiet, this long
227
+ stderrSettleMs: 500, // at most this long waiting for late stderr after the prompt
228
+ killTermMs: 2000, // SIGTERM -> SIGKILL
229
+ killGiveUpMs: 4000, // stop waiting for a child that will not die
230
+ };
231
+
232
+ const MAX_PEN_BYTES = 64 * 1024 * 1024; // larger files are refused (read whole for the baseline hash)
233
+ const STDERR_BUFFER_CAP = 1 << 20;
234
+
235
+ // The bytes of `file`, or null when it does not exist. Opened O_RDONLY|O_NOFOLLOW (a
236
+ // symlink swapped in after open_document is an error, not a read through the link) and
237
+ // O_NONBLOCK (a FIFO opens instead of hanging), then fstat'd on the descriptor: a
238
+ // regular file of at most 64 MiB. Every other error propagates, because "could not read
239
+ // it" is not "nothing there to protect".
240
+ function readBytesOrNull(file) {
241
+ let fd;
166
242
  try {
167
- return readFileSync(file, "utf8");
243
+ fd = openSync(file, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW | fsConstants.O_NONBLOCK);
168
244
  } catch (err) {
169
245
  if (err?.code === "ENOENT") return null;
170
246
  throw err;
171
247
  }
248
+ try {
249
+ const st = fstatSync(fd);
250
+ if (!st.isFile()) throw Object.assign(new Error(`${file} is not a regular file`), { code: "ENOTFILE" });
251
+ if (st.size > MAX_PEN_BYTES) throw Object.assign(new Error(`${file} is larger than 64 MiB`), { code: "E2BIG" });
252
+ const buf = Buffer.allocUnsafe(st.size);
253
+ let off = 0;
254
+ while (off < st.size) {
255
+ const n = readSync(fd, buf, off, st.size - off, off);
256
+ if (n === 0) break;
257
+ off += n;
258
+ }
259
+ return buf.subarray(0, off);
260
+ } finally {
261
+ closeSync(fd);
262
+ }
263
+ }
264
+
265
+ // Separator-bounded containment: `p` equals `base` or sits under it ("/a/bc" is not in "/a/b").
266
+ function isInside(base, p) {
267
+ return p === base || p.startsWith(base.endsWith(sep) ? base : base + sep);
268
+ }
269
+
270
+ // realpath of the deepest EXISTING ancestor plus the missing tail.
271
+ function nearestRealpath(p) {
272
+ let cur = resolve(p);
273
+ const rest = [];
274
+ for (;;) {
275
+ try {
276
+ return join(realpathSync(cur), ...rest.reverse());
277
+ } catch (err) {
278
+ if (err?.code !== "ENOENT" && err?.code !== "ENOTDIR") throw err;
279
+ const parent = dirname(cur);
280
+ if (parent === cur) throw err;
281
+ rest.push(basename(cur));
282
+ cur = parent;
283
+ }
284
+ }
285
+ }
286
+
287
+ // One canonical spelling of a file path: realpath of its directory plus its basename. The
288
+ // baseline, the fresh read, the engine's --out and the `Saved <path>` comparison all use it.
289
+ function canonicalFile(p) {
290
+ return join(nearestRealpath(dirname(p)), basename(p));
172
291
  }
173
292
 
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.
293
+ // The engine is ASSUMED to write through symlinks (never observed either way on
294
+ // @pen.dev/cli), and the sentinel's reads would follow them too, so a link from a project's
295
+ // design.pen to an unrelated file could turn one edit into an overwrite of that file. Only
296
+ // plain .pen files; the returned path is canonical.
177
297
  function penPath(value, label) {
178
298
  const abs = resolve(value);
179
299
  if (!abs.toLowerCase().endsWith(".pen")) {
@@ -181,47 +301,454 @@ function penPath(value, label) {
181
301
  }
182
302
  try {
183
303
  if (lstatSync(abs).isSymbolicLink()) {
184
- throw new Error(`${label} ${abs} is a symlink; refusing (the engine writes through links)`);
304
+ throw new Error(`${label} ${abs} is a symlink; refusing (a link could redirect the write to another file)`);
185
305
  }
186
306
  } catch (err) {
187
307
  if (err?.code !== "ENOENT") throw err;
188
308
  }
189
- return abs;
309
+ return canonicalFile(abs);
310
+ }
311
+
312
+ // --- Contained output directories (exports and screenshots) ---
313
+ //
314
+ // Allowed roots: the realpath of process.cwd() and of the open document's directory,
315
+ // minus "/" and $HOME themselves. The requested directory must sit inside a root on a
316
+ // separator boundary; below the root every existing component is lstat'd and a symlink
317
+ // is refused; missing components are created one at a time and re-checked. A symlink
318
+ // ABOVE the root (a /tmp-style alias of it) is followed only when it leads into the root.
319
+
320
+ function allowedRoots() {
321
+ let home = null;
322
+ try {
323
+ home = realpathSync(homedir());
324
+ } catch {
325
+ // no home: nothing extra to exclude
326
+ }
327
+ const roots = [];
328
+ const add = (p) => {
329
+ if (!p) return;
330
+ let real;
331
+ try {
332
+ real = realpathSync(p);
333
+ } catch {
334
+ return;
335
+ }
336
+ if (real === sep || real === home || roots.includes(real)) return;
337
+ roots.push(real);
338
+ };
339
+ add(process.cwd());
340
+ if (pencilProcess.outputFile) add(dirname(pencilProcess.outputFile));
341
+ return roots;
342
+ }
343
+
344
+ function tryContain(abs, root) {
345
+ const outside = (msg) => ({ ok: false, kind: "outside", msg });
346
+ const parts = abs.split(sep).filter(Boolean);
347
+ let cur = sep;
348
+ const missing = [];
349
+ for (let i = 0; i < parts.length; i++) {
350
+ const next = join(cur, parts[i]);
351
+ let st;
352
+ try {
353
+ st = lstatSync(next);
354
+ } catch (err) {
355
+ if (err?.code === "ENOENT") {
356
+ missing.push(...parts.slice(i));
357
+ break;
358
+ }
359
+ return outside(String(err?.code ?? err));
360
+ }
361
+ if (st.isSymbolicLink()) {
362
+ if (isInside(root, next)) return { ok: false, kind: "symlink", msg: `${next} is a symlink` };
363
+ let resolved;
364
+ try {
365
+ resolved = realpathSync(next);
366
+ } catch {
367
+ return outside(`${next} is a dangling link`);
368
+ }
369
+ if (!(isInside(root, resolved) || isInside(resolved, root))) return outside(`${next} leads outside`);
370
+ cur = resolved;
371
+ continue;
372
+ }
373
+ if (!st.isDirectory()) return outside(`${next} is not a directory`);
374
+ cur = next;
375
+ }
376
+ const target = join(cur, ...missing);
377
+ if (!isInside(root, target)) return outside(`${target} is not inside ${root}`);
378
+ let at = cur;
379
+ for (const part of missing) {
380
+ at = join(at, part);
381
+ try {
382
+ mkdirSync(at);
383
+ } catch (err) {
384
+ if (err?.code !== "EEXIST") return outside(String(err?.code ?? err));
385
+ }
386
+ const st = lstatSync(at);
387
+ if (st.isSymbolicLink() || !st.isDirectory()) return { ok: false, kind: "symlink", msg: `${at} is not a plain directory` };
388
+ }
389
+ return { ok: true, dir: target };
390
+ }
391
+
392
+ function containedDir(requested) {
393
+ const abs = resolve(requested);
394
+ const roots = allowedRoots();
395
+ const failures = [];
396
+ for (const root of roots) {
397
+ const r = tryContain(abs, root);
398
+ if (r.ok) return r.dir;
399
+ failures.push(r);
400
+ }
401
+ const link = failures.find((f) => f.kind === "symlink");
402
+ if (link) throw new Error(`outputDir ${abs} refused: ${oneLine(link.msg)} (symlinked components are not followed)`);
403
+ throw new Error(
404
+ `outputDir ${abs} is outside the allowed directories (${roots.length ? roots.join(", ") : "none: the working directory is / or $HOME and no document is open"}); choose a directory inside the project or next to the open .pen file`
405
+ );
190
406
  }
191
407
 
192
408
  // --- Screenshot persistence ---
193
409
 
194
- function saveScreenshot(base64Data, nodeId) {
410
+ const SHOT_EXT = { "image/png": "png", "image/jpeg": "jpg", "image/webp": "webp" };
411
+
412
+ function saveScreenshot(base64Data, mimeType, nodeId) {
195
413
  const penFile = pencilProcess.outputFile;
196
414
  if (!penFile) return null;
197
- const screenshotDir = join(dirname(penFile), "screenshots");
198
- mkdirSync(screenshotDir, { recursive: true });
415
+ const dir = containedDir(join(dirname(penFile), "screenshots"));
199
416
  const timestamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
200
- const safeId = String(nodeId).replace(/[^A-Za-z0-9_-]/g, "_");
201
- const filePath = join(screenshotDir, `${safeId}-${timestamp}.png`);
202
- writeFileSync(filePath, Buffer.from(base64Data, "base64"));
203
- return filePath;
417
+ const base = `${sanitizeFilename(String(nodeId)) || "node"}-${timestamp}`;
418
+ const bytes = Buffer.from(base64Data, "base64");
419
+ for (let n = 0; n < 5; n++) {
420
+ const filePath = join(dir, `${base}${n ? `-${n}` : ""}.${SHOT_EXT[mimeType] ?? "png"}`);
421
+ try {
422
+ writeFileSync(filePath, bytes, { flag: "wx" });
423
+ return filePath;
424
+ } catch (err) {
425
+ if (err?.code !== "EEXIST") throw err;
426
+ }
427
+ }
428
+ throw new Error("could not pick an unused screenshot file name");
204
429
  }
205
430
 
206
431
  // --- Binary resolution ---
432
+ //
433
+ // The credential goes to exactly one program, so the program is identified before it is
434
+ // spawned. Resolved only inside <home>/.local/share/pen-cli (the lockfile-pinned prefix
435
+ // check_deps.sh installs): the package's name must be @pen.dev/cli, its declared bin.pen
436
+ // target must be a regular file inside the package directory, and the realpath of
437
+ // .bin/pen must EQUAL that target. No PATH walk, never the `pencil` name. The caller spawns
438
+ // the returned REALPATH with `node`, so a link swapped before a respawn is not followed. A
439
+ // version other than the pin only warns.
440
+ //
441
+ // Where the prefix lives is a trust decision too (a settings env block can redirect $HOME):
442
+ // candidates are the passwd home first, then $HOME when it differs (a container whose HOME
443
+ // is not the passwd home keeps working). A candidate is used only when its package
444
+ // directory is outside the working directory and CLAUDE_PROJECT_DIR (a project cannot
445
+ // supply the binary), owned by this user and not group- or world-writable.
446
+ const PEN_CLI_PIN = "0.3.13";
447
+ // What the customer is told to run. The repo-relative path is a dev note: a customer's
448
+ // project has no plugins/ directory, but /soleur:pencil-setup runs the same script.
449
+ const CHECK_DEPS_CMD = "bash plugins/soleur/skills/pencil-setup/scripts/check_deps.sh --auto";
450
+ const REPAIR_HINT = `run /soleur:pencil-setup (it runs \`check_deps.sh --auto\`; in a Soleur checkout: \`${CHECK_DEPS_CMD}\`)`;
451
+
452
+ // realpath of the working directory and of CLAUDE_PROJECT_DIR. `exemptHome` (the realpath of
453
+ // the PASSWD home, which no environment variable can redirect) drops any root that contains
454
+ // it: a root at or above the user's own home would exclude every default install and is the
455
+ // user's tree, not a project that could plant a binary. Pass null for the $HOME candidate:
456
+ // a project's settings env block can set HOME inside the project, so no root is ever
457
+ // skipped for it.
458
+ function projectRoots(exemptHome) {
459
+ const roots = [];
460
+ for (const p of [process.cwd(), process.env.CLAUDE_PROJECT_DIR]) {
461
+ if (!p) continue;
462
+ let real;
463
+ try {
464
+ real = realpathSync(p);
465
+ } catch {
466
+ continue;
467
+ }
468
+ if (real === sep || (exemptHome && isInside(real, exemptHome)) || roots.includes(real)) continue;
469
+ roots.push(real);
470
+ }
471
+ return roots;
472
+ }
473
+
474
+ function findPenBinary() {
475
+ const candidates = [];
476
+ try {
477
+ const home = userInfo().homedir;
478
+ if (home) candidates.push({ label: "passwd", home });
479
+ } catch {
480
+ // no passwd entry: $HOME is the only candidate
481
+ }
482
+ const envHome = process.env.HOME;
483
+ if (envHome && !candidates.some((c) => c.home === envHome)) candidates.push({ label: "HOME", home: envHome });
484
+
485
+ // One candidate: the verdict is { declared, pkg } or { why, installed } (installed: the
486
+ // package directory exists but is not trusted or not a valid install).
487
+ const inspect = (home, exempt) => {
488
+ const prefix = join(home, ".local", "share", "pen-cli");
489
+ let pkgDir;
490
+ try {
491
+ pkgDir = realpathSync(join(prefix, "node_modules", "@pen.dev", "cli"));
492
+ } catch {
493
+ return { installed: false, why: "@pen.dev/cli is not installed under ~/.local/share/pen-cli" };
494
+ }
495
+ let exemptHome = null;
496
+ if (exempt) {
497
+ try {
498
+ exemptHome = realpathSync(home);
499
+ } catch {
500
+ // keep null: nothing extra to exempt
501
+ }
502
+ }
503
+ if (projectRoots(exemptHome).some((root) => isInside(root, pkgDir))) {
504
+ return { installed: true, why: "the package directory is inside the working directory or the project directory" };
505
+ }
506
+ let st;
507
+ try {
508
+ st = statSync(pkgDir);
509
+ } catch {
510
+ return { installed: true, why: "the package directory cannot be inspected" };
511
+ }
512
+ if (typeof process.getuid === "function" && st.uid !== process.getuid()) {
513
+ return { installed: true, why: "the package directory is not owned by the current user" };
514
+ }
515
+ if ((st.mode & 0o022) !== 0) {
516
+ return {
517
+ installed: true,
518
+ // the LITERAL path: $HOME can come from a project's env block, and this text is read by the agent
519
+ why: "the package directory is group- or world-writable; run `chmod -R go-w ~/.local/share/pen-cli/node_modules` (an npm ci under umask 002 leaves it so)",
520
+ };
521
+ }
522
+ let pkg;
523
+ try {
524
+ pkg = JSON.parse(readFileSync(join(pkgDir, "package.json"), "utf8"));
525
+ } catch {
526
+ return { installed: true, why: "its package.json is unreadable" };
527
+ }
528
+ if (pkg?.name !== "@pen.dev/cli") return { installed: true, why: "the package name is not @pen.dev/cli" };
529
+ const declaredRel = pkg?.bin && typeof pkg.bin === "object" ? pkg.bin.pen : undefined;
530
+ if (typeof declaredRel !== "string" || declaredRel === "") return { installed: true, why: "the package declares no pen bin" };
531
+ let declared;
532
+ try {
533
+ declared = realpathSync(resolve(pkgDir, declaredRel));
534
+ } catch {
535
+ return { installed: true, why: "the declared pen bin is missing" };
536
+ }
537
+ if (!isInside(pkgDir, declared)) return { installed: true, why: "the declared pen bin resolves outside the package directory" };
538
+ try {
539
+ if (!statSync(declared).isFile()) return { installed: true, why: "the declared pen bin is not a regular file" };
540
+ } catch {
541
+ return { installed: true, why: "the declared pen bin cannot be inspected" };
542
+ }
543
+ let linked;
544
+ try {
545
+ linked = realpathSync(join(prefix, "node_modules", ".bin", "pen"));
546
+ } catch {
547
+ return { installed: true, why: ".bin/pen is missing" };
548
+ }
549
+ if (linked !== declared) return { installed: true, why: ".bin/pen does not point at the package's declared pen bin" };
550
+ return { declared, pkg };
551
+ };
207
552
 
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.
212
- function findPencilBinary() {
213
- const localPath = join(homedir(), ".local", "node_modules", ".bin", "pencil");
214
- if (existsSync(localPath)) return localPath;
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;
553
+ const whys = [];
554
+ for (const candidate of candidates) {
555
+ const verdict = inspect(candidate.home, candidate.label === "passwd");
556
+ if (!verdict.declared) {
557
+ whys.push(verdict);
558
+ continue;
559
+ }
560
+ if (candidate.label === "HOME") {
561
+ process.stderr.write("[pencil-adapter] using the pen CLI under $HOME (it differs from the passwd home directory)\n");
562
+ }
563
+ if (verdict.pkg.version !== PEN_CLI_PIN) {
564
+ process.stderr.write(
565
+ `[pencil-adapter] WARN: @pen.dev/cli version ${oneLine(verdict.pkg.version)} differs from the pin ${PEN_CLI_PIN}; ${REPAIR_HINT} to re-install the pinned version\n`
566
+ );
567
+ }
568
+ return { binary: verdict.declared, home: candidate.home };
219
569
  }
570
+ const why = (whys.find((v) => v.installed) ?? whys[0])?.why ?? "no home directory could be determined";
220
571
  throw new Error(
221
- "pencil CLI not found (looked in ~/.local/node_modules/.bin and PATH); run /soleur:pencil-setup"
572
+ `pen CLI not found or not trusted (${why}); ${REPAIR_HINT} to install @pen.dev/cli@${PEN_CLI_PIN}`
222
573
  );
223
574
  }
224
575
 
576
+ // `--pencil-binary=<abs>` (argv, set by the user-approved registration): still run with the
577
+ // credential, so it must be an absolute path to a regular file owned by this user that
578
+ // nobody else can write and that is not inside the working directory or the project
579
+ // directory. Each use writes a value-free stderr line.
580
+ function trustedOverride(path) {
581
+ if (!isAbsolute(path)) throw new Error("--pencil-binary must be an absolute path");
582
+ let st;
583
+ try {
584
+ st = lstatSync(path);
585
+ } catch (err) {
586
+ throw new Error(`--pencil-binary cannot be used: ${err?.code ?? "unreadable"}`);
587
+ }
588
+ if (st.isSymbolicLink()) throw new Error("--pencil-binary must not be a symlink");
589
+ if (!st.isFile()) throw new Error("--pencil-binary must be a regular file");
590
+ if (typeof process.getuid === "function" && st.uid !== process.getuid()) {
591
+ throw new Error("--pencil-binary must be owned by the current user");
592
+ }
593
+ if ((st.mode & 0o022) !== 0) throw new Error("--pencil-binary must not be group- or world-writable");
594
+ const real = realpathSync(path);
595
+ let passwdHome = null;
596
+ try {
597
+ passwdHome = realpathSync(userInfo().homedir);
598
+ } catch {
599
+ // keep null
600
+ }
601
+ if (projectRoots(passwdHome).some((root) => isInside(root, real))) {
602
+ throw new Error("--pencil-binary must not be inside the working directory or the project directory");
603
+ }
604
+ process.stderr.write("[pencil-adapter] --pencil-binary override in use (the default pen binary was not resolved)\n");
605
+ return real;
606
+ }
607
+
608
+ // { binary, home }: the binary to run and the home directory the child engine gets as HOME
609
+ // (the home findPenBinary resolved it under; an override: see overrideChildHome).
610
+ function resolveBinary() {
611
+ if (PENCIL_BINARY_ARG) return { binary: trustedOverride(PENCIL_BINARY_ARG), home: overrideChildHome() };
612
+ return findPenBinary();
613
+ }
614
+
615
+ // The home an override-launched engine gets: the passwd home (no environment variable can
616
+ // redirect it), unless $HOME is outside the working directory and CLAUDE_PROJECT_DIR (a
617
+ // container whose HOME is not the passwd home). A $HOME inside the project, which a project's
618
+ // settings env block can set, is never handed to the engine; with no passwd entry the child
619
+ // gets no HOME at all.
620
+ function overrideChildHome() {
621
+ let passwd = null;
622
+ try {
623
+ passwd = userInfo().homedir || null;
624
+ } catch {
625
+ // no passwd entry
626
+ }
627
+ const envHome = process.env.HOME;
628
+ if (envHome) {
629
+ try {
630
+ const real = realpathSync(envHome);
631
+ if (!projectRoots(null).some((root) => isInside(root, real))) return envHome;
632
+ } catch {
633
+ // an unresolvable HOME is not trusted
634
+ }
635
+ }
636
+ return passwd;
637
+ }
638
+
639
+ // --- Child process environment ---
640
+
641
+ // The child gets an allowlisted environment, HOME from the binary resolution, plus the
642
+ // credential under ONE name. Empty and
643
+ // relative PATH entries are dropped (they would resolve against the project the user
644
+ // opened); the adapter's own Node directory goes first so the engine's shebang resolves to
645
+ // the Node (22.19+) that runs the adapter.
646
+ function buildPencilEnv(home) {
647
+ const allowed = ["NODE_ENV", "LANG", "TERM", "USER", "SHELL", "TMPDIR"];
648
+ const env = {};
649
+ for (const key of allowed) {
650
+ if (process.env[key] !== undefined) {
651
+ env[key] = process.env[key];
652
+ }
653
+ }
654
+ // HOME is the one findPenBinary trusted, not whatever $HOME says now: the engine keeps its
655
+ // login state and caches there.
656
+ if (home) env.HOME = home;
657
+ const dirs = [dirname(process.execPath), ...(process.env.PATH ?? "").split(":").filter((p) => p && isAbsolute(p))];
658
+ env.PATH = [...new Set(dirs)].join(":");
659
+ env.PEN_CLI_KEY = API_KEY;
660
+ return env;
661
+ }
662
+
663
+ // The engine opens things relative to its cwd (and its ancestors): hand it a private,
664
+ // empty directory instead of the project the user opened. It only ever receives absolute
665
+ // paths. Removed at exit.
666
+ let CHILD_CWD = null;
667
+ function childCwd() {
668
+ if (!CHILD_CWD) CHILD_CWD = mkdtempSync(join(tmpdir(), "pen-adapter-cwd-"));
669
+ return CHILD_CWD;
670
+ }
671
+
672
+ // --- The save baseline (#11168) ---
673
+ //
674
+ // What this session last loaded or last saved, as a tagged state (see pencil-save-gate.mjs).
675
+ // The state lives in a #-private field so the only ways to change it are the four methods
676
+ // below, each with ONE call site: capture + commit in spawn(), adopt in guardedSave(),
677
+ // clear in clearTarget().
678
+ class SaveBaseline {
679
+ #state = { tag: "none" };
680
+
681
+ // Read the file into { state, bytes }: bytes is a Buffer, null (the file does not
682
+ // exist) or undefined (unreadable). Never throws: a failed read is an `unknown` state
683
+ // with the errno, and says so on stderr.
684
+ capture(file) {
685
+ try {
686
+ const bytes = readBytesOrNull(file);
687
+ return { state: fingerprintState(bytes), bytes };
688
+ } catch (err) {
689
+ const detail = String(err?.code ?? err?.message ?? err);
690
+ process.stderr.write(
691
+ `[pencil-adapter] baseline capture failed for ${oneLine(redactKey(file))} (${oneLine(redactKey(detail))}); baseline=unknown\n`
692
+ );
693
+ return { state: { tag: "unknown", cause: "capture-failed", detail }, bytes: undefined };
694
+ }
695
+ }
696
+
697
+ commit(state) {
698
+ this.#state = state;
699
+ }
700
+
701
+ adopt(state) {
702
+ this.#state = state;
703
+ }
704
+
705
+ clear() {
706
+ this.#state = { tag: "none" };
707
+ }
708
+
709
+ get() {
710
+ return this.#state;
711
+ }
712
+ }
713
+
714
+ const baseline = new SaveBaseline();
715
+
716
+ // Set by a stale refusal (or a respawn that found the file changed or gone) and cleared
717
+ // ONLY by a successful open_document: until then every save is refused, and a crash
718
+ // respawn does not recapture the baseline (a respawn must not turn a refusal into a silent
719
+ // re-baseline).
720
+ let refusalPending = false;
721
+ // Why the refusal is armed, beyond "the file is behind the session" (false): "failed-write"
722
+ // (a failed save changed the file), "restart" (it was already armed, or edits were unpersisted
723
+ // at a respawn), or the cause that armed it at a respawn ("external-change" | "file-missing").
724
+ // The FIRST cause is kept: a later restart never overwrites it.
725
+ let restartedWhileArmed = false;
726
+ // True from the moment an edit's outcome is a refusal or a NOT PERSISTED result until a
727
+ // confirmed save or a successful open_document: exports and screenshots made meanwhile are
728
+ // rendered from memory, not from the file.
729
+ let unpersistedEdits = false;
730
+
731
+ // `cause` says why it is armed beyond "the file is behind the session" (false): "failed-write"
732
+ // (a save failed and the file changed during the write: the memory copy is the only complete
733
+ // one) or, from a respawn, "external-change" | "file-missing" | "restart". The FIRST cause is
734
+ // kept while armed.
735
+ function armRefusal(file, cause = false) {
736
+ // an armed refusal means edits are (or may be) unpersisted, so renders from memory are marked
737
+ unpersistedEdits = true;
738
+ if (refusalPending === true) return;
739
+ refusalPending = true;
740
+ restartedWhileArmed = cause;
741
+ process.stderr.write(`[pencil-adapter] refusalPending=true ${oneLine(redactKey(file))}${cause ? ` cause=${cause}` : ""}\n`);
742
+ }
743
+
744
+ function clearRefusal(file) {
745
+ const was = refusalPending === true;
746
+ refusalPending = false;
747
+ restartedWhileArmed = false;
748
+ unpersistedEdits = false;
749
+ if (was) process.stderr.write(`[pencil-adapter] refusalPending=false ${oneLine(redactKey(file))} (open_document ok)\n`);
750
+ }
751
+
225
752
  // --- PencilProcess class ---
226
753
 
227
754
  const FS_PROBE = {
@@ -229,18 +756,22 @@ const FS_PROBE = {
229
756
  size: (p) => {
230
757
  try {
231
758
  return statSync(p).size;
232
- } catch {
759
+ } catch (err) {
760
+ // 0 sends planSpawn to its no-input branch; the errno is the only trace of why
761
+ process.stderr.write(`[pencil-adapter] could not stat ${oneLine(redactKey(p))} (${err?.code ?? "error"}); treating it as empty for --in\n`);
233
762
  return 0;
234
763
  }
235
764
  },
236
765
  };
237
766
 
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.
767
+ // Set when open_document could not load the file it was given. Every tool errors until the
768
+ // next successful open_document, so nothing runs (or saves) against a document that is not
769
+ // the one the caller asked for. Cleared ONLY on success.
241
770
  let openFailure = null;
242
771
  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.";
772
+ "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. The original file is untouched; it can still be edited in Pencil Desktop.";
773
+
774
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
244
775
 
245
776
  class PencilProcess {
246
777
  constructor() {
@@ -248,49 +779,65 @@ class PencilProcess {
248
779
  this.ready = false;
249
780
  this.buffer = "";
250
781
  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.
782
+ this.lastStderrAt = 0;
783
+ // True when the last reply carried an error on STDERR (the engine's only error channel).
784
+ this.lastStderrError = false;
785
+ // The document the session is bound to. Set when a spawn reaches its prompt, cleared
786
+ // only by clearTarget() (a failed open_document). A FAILED respawn leaves it alone, so
787
+ // the next call retries the same file instead of falling through to a scratch document.
255
788
  this.outputFile = null;
256
789
  // The file the last successful spawn passed as --in (null = started empty).
257
790
  this.lastInFile = null;
791
+ // diskTopLevelCount of the bytes of --in as read BEFORE the last spawn (null: no --in)
792
+ this.lastLoadDiskCount = null;
258
793
  this.scratchFile = null;
259
- this._dataHandler = null;
794
+ this._waiter = null;
260
795
  this._onExit = null;
796
+ this._redactor = null;
261
797
  }
262
798
 
263
799
  clearTarget() {
264
800
  this.outputFile = null;
265
801
  this.lastInFile = null;
802
+ this.lastLoadDiskCount = null;
803
+ baseline.clear();
266
804
  }
267
805
 
268
806
  // Called only from inside the command queue, so spawns are serialized.
269
807
  async ensureAlive() {
270
808
  if (openFailure) throw new Error(`open failed: ${openFailure}\n${OPEN_FAILED_NEXT}`);
271
809
  if (this.child && this.ready) return;
272
- if (this.child) await this.kill(); // a half-started child is never reused
810
+ if (this.child) await this.kill(); // a half-started (or desynchronised) child is never reused
273
811
  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);
812
+ // Respawn: no explicit input, so planSpawn reloads the saved file and a template can
813
+ // never overwrite saved edits. Before the first save it falls back to the template
814
+ // the target was opened from.
815
+ let recapture = true;
816
+ if (refusalPending === true) {
817
+ recapture = false;
818
+ if (restartedWhileArmed === false) restartedWhileArmed = "restart";
819
+ process.stderr.write("[pencil-adapter] respawn: refusalPending still armed, baseline not recaptured\n");
820
+ } else if (baseline.get().tag === "unknown") {
821
+ recapture = false;
822
+ process.stderr.write("[pencil-adapter] respawn: baseline unknown, not recaptured (open_document to re-baseline)\n");
823
+ }
824
+ await this.spawn(this.outputFile, null, this.lastInFile, { recapture, respawn: true });
278
825
  return;
279
826
  }
280
- // No document opened yet: a private scratch document, so tools that need
281
- // none (get_editor_state, get_guidelines) work before open_document.
827
+ // No document opened yet: a private scratch document, so tools that need none
828
+ // (get_editor_state, read_skill) work before open_document.
282
829
  if (!this.scratchFile) {
283
- this.scratchFile = join(mkdtempSync(join(tmpdir(), "pencil-adapter-")), "scratch.pen");
830
+ this.scratchFile = join(realpathSync(mkdtempSync(join(tmpdir(), "pencil-adapter-"))), "scratch.pen");
284
831
  }
285
832
  await this.spawn(this.scratchFile);
286
833
  }
287
834
 
288
- // `explicitInFile` is the caller's template (open_document `inputPath`).
289
- async spawn(outFile, explicitInFile = null, resumeInFile = null) {
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
- }
835
+ // `explicitInFile` is the caller's template (open_document `inputPath`). `respawn` marks
836
+ // the crash/timeout reload of the bound document: it compares what is on disk now with
837
+ // the session's baseline (ruling: arm the refusal when the file changed or vanished) and
838
+ // checks load fidelity here, because no open_document runs after it.
839
+ async spawn(outFile, explicitInFile = null, resumeInFile = null, { recapture = true, respawn = false } = {}) {
840
+ const { binary, home: engineHome } = resolveBinary();
294
841
  const { inFile } = planSpawn({
295
842
  outFile,
296
843
  initialInFile: explicitInFile,
@@ -302,54 +849,143 @@ class PencilProcess {
302
849
  args.push("--in", inFile);
303
850
  }
304
851
 
852
+ // What this session starts from, read from --out BEFORE the engine exists. A change
853
+ // between here and the first save (including while the engine loads) is a change the
854
+ // session did not see, so the first save refuses. Committed only once the prompt arrives.
855
+ const captured = baseline.capture(outFile);
856
+ // The bytes of the document the engine is about to load, read before it starts: the
857
+ // top-level count the load must reproduce (the file itself when it is --in).
858
+ let loadedDiskCount = null;
859
+ if (inFile) {
860
+ let inBytes = captured.bytes;
861
+ let unreadable = captured.state.tag === "unknown" ? captured.state.detail : null;
862
+ if (inFile !== outFile) {
863
+ try {
864
+ inBytes = readBytesOrNull(inFile);
865
+ } catch (err) {
866
+ inBytes = undefined;
867
+ unreadable = String(err?.code ?? err?.message ?? err);
868
+ }
869
+ }
870
+ if (inBytes === undefined) {
871
+ throw new Error(`${inFile} could not be read before loading it (${oneLine(unreadable ?? "unreadable")}); it was not modified`);
872
+ }
873
+ loadedDiskCount = diskTopLevelCount(inBytes);
874
+ }
875
+ // A respawn onto a changed or vanished file is decided now, applied at the prompt.
876
+ let armCause = null;
877
+ const previous = baseline.get();
878
+ if (respawn && recapture && previous.tag === "hash") {
879
+ if (captured.state.tag === "missing") armCause = "file-missing";
880
+ else if (captured.state.tag === "hash" && captured.state.hash !== previous.hash) armCause = "external-change";
881
+ }
882
+ // Edits that were never persisted (a refused, failed, unconfirmed or incomplete save) died
883
+ // with the old engine: the file looks unchanged, and adopting it would let the next
884
+ // save pass as if nothing was lost. The baseline stays the old one.
885
+ if (respawn && recapture && armCause === null && unpersistedEdits) armCause = "restart";
886
+
305
887
  this.buffer = "";
306
888
  this.stderrBuffer = "";
889
+ this.stderrHeld = "";
890
+ this.lastStderrAt = 0;
307
891
  this.ready = false;
308
892
 
309
- // Spawn pencil using the adapter's own Node binary (process.execPath)
310
- // instead of relying on the pencil script's #!/usr/bin/env node shebang,
311
- // which resolves to the system Node (potentially <22) and fails with
312
- // ERR_REQUIRE_ESM. This guarantees the child process uses the same
313
- // Node version (22+) that runs the adapter.
893
+ // Spawn the engine using the adapter's own Node binary (process.execPath) and the
894
+ // REALPATH resolved above, so the child runs the same Node (22.19+) that runs the
895
+ // adapter and a link swapped since resolution is not followed.
314
896
  const child = nodeSpawn(process.execPath, [binary, ...args], {
315
897
  stdio: ["pipe", "pipe", "pipe"],
316
- env: buildPencilEnv(),
898
+ env: buildPencilEnv(engineHome),
899
+ cwd: childCwd(),
317
900
  });
318
901
  this.child = child;
902
+ const redactor = createRollingRedactor(REDACT_FORMS);
903
+ const ansi = createAnsiStripper();
904
+ this._redactor = redactor;
319
905
 
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.
906
+ // Everything below is bound to THIS child: the events of a killed child can arrive
907
+ // after its replacement was spawned and must not touch the new one.
908
+ child.stdout.on("data", (chunk) => this._onStdout(child, chunk.toString()));
322
909
  child.stderr.on("data", (chunk) => {
323
- process.stderr.write(redactKey(chunk.toString()));
324
- if (this.child === child) this.stderrBuffer += chunk.toString();
910
+ const text = chunk.toString();
911
+ // Escape sequences go BEFORE the redactor: a credential interleaved with them would
912
+ // otherwise reach the log with the sequences between its characters.
913
+ const safe = redactor.push(ansi.push(text));
914
+ if (safe) process.stderr.write(safe);
915
+ if (this.child === child) {
916
+ // Stripped, THEN redacted, BEFORE it is stored or trimmed: a spelling interleaved with
917
+ // escape sequences, or straddling the trim point (or a chunk boundary: the whole
918
+ // buffer is re-scanned), is already replaced, so the kept tail never starts with half
919
+ // a credential. A spelling still being assembled at the very end stays whole in the
920
+ // buffer until its second half arrives (heldTailOf keeps it out of every result).
921
+ this.stderrBuffer = redactKey(stripAnsi(this.stderrBuffer + text));
922
+ if (this.stderrBuffer.length > STDERR_BUFFER_CAP) {
923
+ // trim at a line start where there is one
924
+ const tail = this.stderrBuffer.slice(-(STDERR_BUFFER_CAP >> 1));
925
+ const nl = tail.indexOf("\n");
926
+ this.stderrBuffer = nl === -1 ? tail : tail.slice(nl + 1);
927
+ }
928
+ this.lastStderrAt = Date.now();
929
+ }
325
930
  });
326
- // An EPIPE between the child's death and its close event must not crash the
327
- // adapter; the close handler reports the death.
931
+ // An EPIPE between the child's death and its close event must not crash the adapter;
932
+ // the close handler reports the death.
328
933
  child.stdin.on("error", () => {});
329
934
 
330
935
  const gone = (code, signal, err) => {
936
+ // the rolling redactor is flushed here, when the stream has ended, and nowhere else
937
+ const rest = redactor.flush();
938
+ if (rest) process.stderr.write(rest);
331
939
  process.stderr.write(
332
- `[pencil-adapter] pencil process exited: code=${code} signal=${signal}${err ? ` error=${oneLine(err.message)}` : ""}\n`
940
+ `[pencil-adapter] pen process exited: code=${code} signal=${signal}${err ? ` error=${oneLine(err.message)}` : ""}\n`
333
941
  );
334
942
  if (this.child !== child) return;
335
943
  this.ready = false;
336
944
  this.child = null;
337
945
  if (this._onExit) this._onExit(code, signal, err);
338
946
  };
339
- // `close`, not `exit`: it fires after the stdio streams drained, so the
340
- // stderr tail in the failure message is complete.
947
+ // `close`, not `exit`: it fires after the stdio streams drained, so the stderr tail in
948
+ // the failure message is complete.
341
949
  child.on("close", (code, signal) => gone(code, signal));
342
950
  child.on("error", (err) => gone(null, null, err));
343
951
 
344
952
  try {
345
- await this.waitForPrompt(30000); // banner + initial prompt
953
+ await this.waitForPrompt(TIMEOUTS.spawnPromptMs); // banner + initial prompt
346
954
  } catch (err) {
347
955
  if (this.child === child) await this.kill(); // never leave a half-started child behind
348
956
  throw err;
349
957
  }
958
+ if (armCause) {
959
+ // the baseline stays the OLD one: the engine loaded content (or nothing) this session never saw
960
+ armRefusal(outFile, armCause);
961
+ const what =
962
+ armCause === "file-missing"
963
+ ? "file is gone behind a restarted session"
964
+ : armCause === "external-change"
965
+ ? "file changed on disk behind a restarted session"
966
+ : "edits were not persisted when the engine restarted";
967
+ process.stderr.write(
968
+ `[pencil-adapter] respawn: ${what} (cause=${armCause}) baseline=${hash8(previous.hash)} disk=${hash8(captured.state.hash)}; refusalPending armed\n`
969
+ );
970
+ } else if (recapture) {
971
+ baseline.commit(captured.state);
972
+ }
350
973
  this.outputFile = outFile;
351
974
  this.lastInFile = inFile;
975
+ this.lastLoadDiskCount = loadedDiskCount;
352
976
  this.ready = true;
977
+ if (respawn) {
978
+ // no open_document runs after a respawn, so the load is verified here
979
+ const nonce = newCountNonce();
980
+ const memoryCount = memoryTopLevelCount(rawText(await this.sendCommand(buildCountCommand(nonce))), nonce);
981
+ const failure = loadFidelityFailure({ file: inFile ?? outFile, diskCount: loadedDiskCount, memoryCount });
982
+ if (failure) {
983
+ openFailure = oneLine(redactKey(failure));
984
+ process.stderr.write(`[pencil-adapter] respawn load check failed: ${openFailure}\n`);
985
+ await this.kill();
986
+ throw new Error(`open failed: ${openFailure}\n${OPEN_FAILED_NEXT}`);
987
+ }
988
+ }
353
989
  }
354
990
 
355
991
  async kill() {
@@ -358,8 +994,8 @@ class PencilProcess {
358
994
  this.ready = false;
359
995
  if (!child || child.exitCode !== null || child.signalCode !== null) return;
360
996
  await new Promise((resolveKill) => {
361
- const escalate = setTimeout(() => child.kill("SIGKILL"), 2000);
362
- const giveUp = setTimeout(done, 4000);
997
+ const escalate = setTimeout(() => child.kill("SIGKILL"), TIMEOUTS.killTermMs);
998
+ const giveUp = setTimeout(done, TIMEOUTS.killGiveUpMs);
363
999
  function done() {
364
1000
  clearTimeout(escalate);
365
1001
  clearTimeout(giveUp);
@@ -376,35 +1012,81 @@ class PencilProcess {
376
1012
  await this.spawn(outFile, explicitInFile);
377
1013
  }
378
1014
 
1015
+ // Stdout bytes with no reply being awaited are a desync (a forged or late tail): the
1016
+ // child is not trusted to be at its prompt any more, so it is replaced from the saved
1017
+ // file on the next call.
1018
+ _onStdout(child, text) {
1019
+ if (this.child !== child) return;
1020
+ if (this._waiter) {
1021
+ this._waiter.feed(text);
1022
+ return;
1023
+ }
1024
+ if (this.ready) {
1025
+ this.ready = false;
1026
+ process.stderr.write(
1027
+ "[pencil-adapter] desync: bytes arrived after the prompt with no command in flight; restarting pen from the saved file on the next call\n"
1028
+ );
1029
+ }
1030
+ }
1031
+
379
1032
  async sendCommand(cmd) {
380
1033
  if (!this.child || !this.ready) {
381
- throw new Error("Pencil process is not running");
1034
+ throw new Error("pen process is not running");
382
1035
  }
383
1036
  this.buffer = "";
384
1037
  this.stderrBuffer = "";
1038
+ this.lastStderrAt = 0;
385
1039
  this.child.stdin.write(cmd + "\n");
386
1040
  let raw;
387
1041
  try {
388
- raw = await this.waitForPrompt(30000);
1042
+ raw = await this.waitForPrompt(TIMEOUTS.replyMs);
1043
+ // Errors travel on STDERR and may land a moment after the prompt: wait for it to go quiet.
1044
+ const t0 = Date.now();
1045
+ while (this.lastStderrAt && Date.now() - this.lastStderrAt < TIMEOUTS.promptQuietMs && Date.now() - t0 < TIMEOUTS.stderrSettleMs) {
1046
+ await sleep(TIMEOUTS.promptQuietMs - (Date.now() - this.lastStderrAt) + 1);
1047
+ }
389
1048
  } catch (err) {
390
1049
  // A timed-out reply would otherwise be attributed to the NEXT command.
391
1050
  if (this.child) {
392
1051
  await this.kill();
393
1052
  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)`
1053
+ `${err.message}; pen was stopped and restarts from ${this.outputFile ?? "a scratch document"} on the next call (anything not yet saved is lost)`
395
1054
  );
396
1055
  }
397
1056
  throw err;
398
1057
  }
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.
401
- if (!raw && this.stderrBuffer) {
402
- return redactKey(this.stderrBuffer);
1058
+ // (the rolling redactor behind the adapter's own stderr log is NOT flushed here: a
1059
+ // spelling split across the end of one reply and the start of the next must still be
1060
+ // caught THERE, so it is flushed when the child's streams close. That protection is for
1061
+ // the log sink only: a tool result carries one reply's stderr, which is buffered per
1062
+ // command.) The buffer is already redacted; redacting the reply text too covers every
1063
+ // sink that follows.
1064
+ const errText = this.takeReleasableStderr().trim();
1065
+ const out = redactKey(raw);
1066
+ // stderr holds the engine's failures (`Error:`, `[ERROR]`, `Save failed:`, `Unknown tool:`).
1067
+ // When it carries one it goes first, so the whole text is scanned; stderr that holds only
1068
+ // warnings is already in the adapter's own stderr log and stays out of the reply.
1069
+ this.lastStderrError = errText !== "" && classifyResponse(errText).isError;
1070
+ if (this.lastStderrError) return out ? `${errText}\n${out}` : errText;
1071
+ return out;
1072
+ }
1073
+
1074
+ // This reply's redacted stderr, minus the unfinished credential prefix at its very end
1075
+ // (kept in `stderrHeld` and joined to the NEXT reply's stderr: if that completes the
1076
+ // credential, the whole spelling is replaced; if not, the held part is dropped, never shown).
1077
+ takeReleasableStderr() {
1078
+ let text = stripAnsi(this.stderrBuffer);
1079
+ if (this.stderrHeld) {
1080
+ const joined = this.stderrHeld + text;
1081
+ const redacted = redactKey(joined);
1082
+ if (redacted !== joined) text = redacted;
403
1083
  }
404
- return redactKey(raw);
1084
+ const held = heldPrefixLength(text, REDACT_FORMS);
1085
+ this.stderrHeld = held > 0 ? text.slice(text.length - held) : "";
1086
+ return held > 0 ? text.slice(0, text.length - held) : text;
405
1087
  }
406
1088
 
407
- waitForPrompt(timeoutMs = 30000) {
1089
+ waitForPrompt(timeoutMs = TIMEOUTS.replyMs) {
408
1090
  return new Promise((resolvePrompt, reject) => {
409
1091
  const child = this.child;
410
1092
  if (!child) {
@@ -412,26 +1094,23 @@ class PencilProcess {
412
1094
  return;
413
1095
  }
414
1096
  const duringCommand = this.ready;
1097
+ let quiet = null;
415
1098
  const cleanup = () => {
416
1099
  clearTimeout(timeout);
417
- child.stdout.removeListener("data", this._dataHandler);
418
- this._dataHandler = null;
1100
+ if (quiet) clearTimeout(quiet);
1101
+ this._waiter = null;
419
1102
  this._onExit = null;
420
1103
  };
421
1104
  const timeout = setTimeout(() => {
422
1105
  cleanup();
423
- reject(
424
- new Error(
425
- `[pencil-adapter] Timed out waiting for prompt after ${timeoutMs}ms`
426
- )
427
- );
1106
+ reject(new Error(`[pencil-adapter] Timed out waiting for prompt after ${timeoutMs}ms`));
428
1107
  }, timeoutMs);
429
1108
 
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.
1109
+ // A child that exits before its prompt (bad --in file, auth failure) or mid-command
1110
+ // fails the wait immediately with its stderr tail, not after 30 s.
432
1111
  this._onExit = (code, signal, err) => {
433
1112
  cleanup();
434
- const tail = redactKey(this.stderrBuffer)
1113
+ const tail = this.takeReleasableStderr()
435
1114
  .trim()
436
1115
  .split("\n")
437
1116
  .slice(-10)
@@ -440,33 +1119,30 @@ class PencilProcess {
440
1119
  .join(" | ");
441
1120
  reject(
442
1121
  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)}` : ""})` +
1122
+ `[pencil-adapter] pen exited ${duringCommand ? "during a command (its effect is unknown)" : "before it was ready"} (code=${code} signal=${signal}${err ? ` error=${oneLine(err.message)}` : ""})` +
444
1123
  (tail ? `: ${tail}` : "")
445
1124
  )
446
1125
  );
447
1126
  };
448
1127
 
449
- this._dataHandler = (chunk) => {
450
- this.buffer += chunk.toString();
451
- const stripped = stripAnsi(this.buffer);
452
- // Detect prompt: "pencil > " at start or after newline
453
- const promptIdx = stripped.indexOf("\npencil > ");
454
- const startsWithPrompt = stripped.startsWith("pencil > ");
455
-
456
- if (promptIdx !== -1 || startsWithPrompt) {
457
- cleanup();
458
- let response;
459
- if (promptIdx !== -1) {
460
- response = stripped.substring(0, promptIdx);
461
- } else {
462
- // Buffer starts with prompt — empty response (initial prompt)
463
- response = "";
1128
+ // The reply is complete only when the prompt is the LAST thing in the buffer and
1129
+ // nothing more arrives for TIMEOUTS.promptQuietMs: a node name or a read_skill page that
1130
+ // contains the prompt text at a line start does not end the reply early.
1131
+ this._waiter = {
1132
+ feed: (text) => {
1133
+ this.buffer += text;
1134
+ if (quiet) {
1135
+ clearTimeout(quiet);
1136
+ quiet = null;
464
1137
  }
465
- resolvePrompt(response.trim());
466
- }
1138
+ const stripped = stripAnsi(this.buffer);
1139
+ if (stripped !== REPL_PROMPT && !stripped.endsWith("\n" + REPL_PROMPT)) return;
1140
+ quiet = setTimeout(() => {
1141
+ cleanup();
1142
+ resolvePrompt(stripped.slice(0, stripped.length - REPL_PROMPT.length).trim());
1143
+ }, TIMEOUTS.promptQuietMs);
1144
+ },
467
1145
  };
468
-
469
- child.stdout.on("data", this._dataHandler);
470
1146
  });
471
1147
  }
472
1148
  }
@@ -484,12 +1160,12 @@ class CommandQueue {
484
1160
  return this.runExclusive((send) => send(command));
485
1161
  }
486
1162
 
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.
1163
+ // Run `fn` as ONE queue job: no other queued command, and no restart, can land while it
1164
+ // runs. `fn` receives `send(cmd)`, which talks to the process directly (enqueueing from
1165
+ // inside a job would wait on itself). The process is (re)started here, inside the
1166
+ // serialized section, so two callers can never both spawn. Used for the save sentinel
1167
+ // (probe + save), for an edit together with its auto-save, and for open_document's
1168
+ // kill-and-respawn.
493
1169
  async runExclusive(fn, { ensure = true } = {}) {
494
1170
  return new Promise((resolveJob, reject) => {
495
1171
  this.queue.push({ job: fn, ensure, resolve: resolveJob, reject });
@@ -516,9 +1192,10 @@ const pencilProcess = new PencilProcess();
516
1192
  const commandQueue = new CommandQueue(pencilProcess);
517
1193
 
518
1194
  process.on("exit", () => {
519
- if (pencilProcess.scratchFile) {
1195
+ for (const dir of [pencilProcess.scratchFile ? dirname(pencilProcess.scratchFile) : null, CHILD_CWD]) {
1196
+ if (!dir) continue;
520
1197
  try {
521
- rmSync(dirname(pencilProcess.scratchFile), { recursive: true, force: true });
1198
+ rmSync(dir, { recursive: true, force: true });
522
1199
  } catch {
523
1200
  // best effort
524
1201
  }
@@ -527,45 +1204,180 @@ process.on("exit", () => {
527
1204
 
528
1205
  // --- Guarded save (the ONLY place the REPL `save` command is emitted) ---
529
1206
  //
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.
1207
+ // Must run inside an exclusive queue job (`send` is that job's channel): read the file on
1208
+ // disk, probe the in-memory document, decide, re-read the file, decide again, then save,
1209
+ // with nothing able to interleave. An empty document is never written over a file that
1210
+ // holds nodes, nothing is written over a file that is not a recognizable .pen (#11143), and
1211
+ // nothing is written over a file that changed behind the session (#11168); see
1212
+ // pencil-save-gate.mjs. Callers: an edit's auto-save and the explicit `save` tool.
1213
+
1214
+ // A confirmed save is exactly `Saved <this file>`: anything else (empty, another path, a
1215
+ // failure line) is not a confirmation.
1216
+ function isSavedFor(raw, file) {
1217
+ const path = savedReplyPath(raw);
1218
+ if (!path) return false;
1219
+ try {
1220
+ return canonicalFile(path) === canonicalFile(file);
1221
+ } catch {
1222
+ return false;
1223
+ }
1224
+ }
1225
+
1226
+ // A recreate (the file was removed behind a live session) is allowed only while the path is
1227
+ // still the canonical one the session opened: no directory on the way has been swapped for a
1228
+ // link or moved, so the write cannot land somewhere else.
1229
+ function canRecreatePath(file) {
1230
+ try {
1231
+ if (canonicalFile(file) !== file) return false;
1232
+ return !lstatSync(dirname(file)).isSymbolicLink();
1233
+ } catch {
1234
+ return false;
1235
+ }
1236
+ }
535
1237
 
536
1238
  async function guardedSave(send, source) {
537
1239
  const file = pencilProcess.outputFile;
538
- return runGuardedSave({
1240
+ const saved = await runGuardedSave({
539
1241
  file,
540
1242
  source,
541
- readDisk: async () => readTextOrNull(file),
1243
+ readDisk: async () => readBytesOrNull(file),
542
1244
  probeMemory: async () => {
543
- const raw = await send(formatReplCommand("batch_get", {}));
1245
+ const nonce = newCountNonce();
1246
+ const raw = await send(buildCountCommand(nonce));
544
1247
  const verdict = classifyResponse(raw);
545
1248
  if (verdict.isError) throw new Error(oneLine(verdict.text).slice(0, 200));
546
- return rawText(raw);
1249
+ return { text: rawText(raw), nonce };
547
1250
  },
1251
+ readFresh: async () => readBytesOrNull(file),
1252
+ getBaseline: () => baseline.get(),
1253
+ isRefusalPending: () => refusalPending === true,
548
1254
  send: async () => send(formatReplCommand("save", {})),
1255
+ isConfirmed: (raw) => isSavedFor(raw, file),
1256
+ isDefiniteFailure: (raw) => isDefiniteSaveFailure(raw),
1257
+ readAfterSave: async () => readBytesOrNull(file),
1258
+ adoptBaseline: (state) => baseline.adopt(state),
1259
+ wasRestarted: () => restartedWhileArmed,
1260
+ canRecreate: async () => canRecreatePath(file),
549
1261
  });
1262
+ // a refusal that says the session is behind the file, or a failed write that left the
1263
+ // file different from the baseline, arms the refusal until open_document succeeds
1264
+ if (saved.refused && saved.arm) armRefusal(file);
1265
+ else if (saved.failed && saved.arm) armRefusal(file, "failed-write");
1266
+ if (saved.refused || saved.failed || saved.unconfirmed) unpersistedEdits = true;
1267
+ else if (saved.saved) unpersistedEdits = false;
1268
+ if (saved.recreated) {
1269
+ process.stderr.write(
1270
+ oneLine(redactKey(`[pencil-adapter] [reason=recreated] ${file} baseline=${hash8(saved.baselineHash)}`)) + "\n"
1271
+ );
1272
+ }
1273
+ if (saved.failed) {
1274
+ process.stderr.write(
1275
+ `[pencil-adapter] save failed (definite): baseline kept${saved.changedDuringFailedWrite ? ", but the file changed during the failed write (refusalPending armed)" : ""}; ${failureDetail(saved.raw)}\n`
1276
+ );
1277
+ }
1278
+ if (saved.unconfirmed) {
1279
+ process.stderr.write(
1280
+ "[pencil-adapter] save unconfirmed: reply did not match the expected Saved line; baseline=unknown\n"
1281
+ );
1282
+ }
1283
+ if (saved.warning) {
1284
+ process.stderr.write(`[pencil-adapter] WARN post-save read failed (${oneLine(saved.detail)}); baseline=unknown\n`);
1285
+ }
1286
+ return saved;
1287
+ }
1288
+
1289
+ // The engine's own reason for a failed save, one line, redacted, capped.
1290
+ function failureDetail(raw) {
1291
+ return oneLine(redactKey(saveFailureLine(raw))).slice(0, 300);
1292
+ }
1293
+
1294
+ // Every refusal state leaves ONE stderr line, from here, whichever save path hit it
1295
+ // (hashes only as 8-hex-char prefixes).
1296
+ function logRefusal(saved, via) {
1297
+ const file = pencilProcess.outputFile ?? "";
1298
+ const hashes =
1299
+ saved.code === "stale" || saved.code === "refusal-pending"
1300
+ ? ` baseline=${hash8(saved.baselineHash)} disk=${hash8(saved.diskHash)}`
1301
+ : "";
1302
+ const cause =
1303
+ saved.code === "unknown-baseline"
1304
+ ? ` cause=${saved.cause ?? "unknown"}${saved.detail ? ` errno=${saved.detail}` : ""}`
1305
+ : saved.code === "refusal-pending" && restartedWhileArmed
1306
+ ? ` cause=${restartedWhileArmed}`
1307
+ : "";
1308
+ process.stderr.write(
1309
+ oneLine(redactKey(`[pencil-adapter] REFUSED save: [reason=${saved.code}] ${file}${hashes}${cause} via=${via}`)) + "\n"
1310
+ );
1311
+ }
1312
+
1313
+ // The refused operations are appended to a refusal so the replay does not depend on the
1314
+ // agent's context (64 KiB cap, redacted). Variables bound by an EARLIER batch_design call
1315
+ // are not part of the echo and are lost when the document is reopened.
1316
+ const MAX_ECHO_BYTES = 64 * 1024;
1317
+ function refusalText(saved, operations) {
1318
+ if (operations === undefined) return saved.message;
1319
+ let ops = redactKey(String(operations));
1320
+ if (Buffer.byteLength(ops) > MAX_ECHO_BYTES) ops = `${ops.slice(0, MAX_ECHO_BYTES)}\n[... truncated at 64 KiB]`;
1321
+ return `${saved.message}\n\nRefused operations (replay them in order after open_document; re-bind any variable that an earlier batch_design call defined, those bindings are lost on reopen):\n\`\`\`\n${ops}\n\`\`\``;
550
1322
  }
551
1323
 
552
1324
  function errorResult(text) {
553
1325
  return { content: [{ type: "text", text }], isError: true };
554
1326
  }
555
1327
 
1328
+ // The NOT PERSISTED result for a save outcome that is neither a refusal nor a confirmation
1329
+ // (`failed` / `unconfirmed`), with the engine's own text in `detail` (redacted, capped).
1330
+ function notPersistedResult(saved) {
1331
+ const file = pencilProcess.outputFile;
1332
+ if (saved.failed) {
1333
+ return notPersistedMessage({ code: "save-failed", file, detail: failureDetail(saved.raw), changed: saved.changedDuringFailedWrite === true });
1334
+ }
1335
+ const after = classifyResponse(saved.raw);
1336
+ const detail = after.isError ? oneLine(enrichErrorMessage(after.text)).slice(0, 300) : "";
1337
+ return notPersistedMessage({ code: "unconfirmed", file, detail });
1338
+ }
1339
+
1340
+ // A save that threw (timeout, dead engine, a desynchronised engine) after the edit was
1341
+ // applied. Runs inside the exclusive job. The text says the engine was stopped, so it is: a
1342
+ // child that is still alive (a desync, an unexpected throw) is killed here, and the next
1343
+ // call respawns from the file with the refusal armed.
1344
+ async function saveIncompleteResult(err) {
1345
+ unpersistedEdits = true;
1346
+ const reason = oneLine(redactKey(err?.message ?? err)).slice(0, 300);
1347
+ await pencilProcess.kill();
1348
+ process.stderr.write(`[pencil-adapter] save did not complete: ${reason}\n`);
1349
+ return errorResult(notPersistedMessage({ code: "save-incomplete", file: pencilProcess.outputFile, detail: reason }));
1350
+ }
1351
+
556
1352
  // --- MCP Server setup ---
557
1353
 
558
- const server = new McpServer({
559
- name: "pencil-mcp-adapter",
560
- version: "0.0.1",
561
- });
1354
+ // A failure while the server is being built or started (a tool that cannot be registered, a
1355
+ // transport that cannot connect) leaves one adapter-authored, redacted, bounded line in the
1356
+ // MCP log and exits 1; without it Claude Code only reports `failed to connect`.
1357
+ function startFailed(err) {
1358
+ process.stderr.write(`[pencil-adapter] ERROR: server start failed: ${oneLine(redactKey(err?.message ?? err)).slice(0, 300)}\n`);
1359
+ process.exit(1);
1360
+ }
1361
+
1362
+ let server;
1363
+ try {
1364
+ server = new McpServer({
1365
+ name: "pencil-mcp-adapter",
1366
+ version: "0.0.1",
1367
+ });
1368
+ } catch (err) {
1369
+ startFailed(err);
1370
+ }
562
1371
 
563
1372
  // 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.
1373
+ // open_document, and any thrown error (a REPL contract violation, a bad path, a dead
1374
+ // process, a timeout) becomes an isError result with the replacement hints AND one stderr
1375
+ // line `tool=<name> error: ...` (redacted, one line, at most 300 characters), so the
1376
+ // adapter's own log shows what the caller was told.
566
1377
  function registerTool(name, schema, handler, { allowWhenOpenFailed = false, description } = {}) {
567
1378
  const callback = async (params) => {
568
1379
  if (openFailure && !allowWhenOpenFailed) {
1380
+ process.stderr.write(`[pencil-adapter] tool=${name} refused: open failed\n`);
569
1381
  return errorResult(
570
1382
  `open failed: ${openFailure}\nNo tool runs until open_document succeeds on a valid .pen file. ${OPEN_FAILED_NEXT}`
571
1383
  );
@@ -573,20 +1385,34 @@ function registerTool(name, schema, handler, { allowWhenOpenFailed = false, desc
573
1385
  try {
574
1386
  return await handler(params ?? {});
575
1387
  } catch (err) {
576
- return errorResult(enrichErrorMessage(redactKey(String(err?.message ?? err))));
1388
+ const message = redactKey(String(err?.message ?? err));
1389
+ process.stderr.write(`[pencil-adapter] tool=${name} error: ${oneLine(message).slice(0, 300)}\n`);
1390
+ return errorResult(enrichErrorMessage(message));
577
1391
  }
578
1392
  };
579
- if (description) server.tool(name, description, schema, callback);
580
- else server.tool(name, schema, callback);
1393
+ try {
1394
+ if (description) server.tool(name, description, schema, callback);
1395
+ else server.tool(name, schema, callback);
1396
+ } catch (err) {
1397
+ startFailed(err);
1398
+ }
581
1399
  }
582
1400
 
583
1401
  // --- Read-only tool handler factory ---
584
-
585
- function registerReadOnlyTool(name, schema, options) {
1402
+ //
1403
+ // `build(params)` returns the one REPL line (validated by the surface module). Replies are
1404
+ // capped (64 KiB) by the classifier and redacted by the process, never parsed. A reply is
1405
+ // an error when it classifies as one; with `errorFrom: "stderr"` only an error on the
1406
+ // engine's stderr counts (read_skill returns markdown that can contain error-looking lines).
1407
+ function registerReadOnlyTool(name, schema, build, { errorFrom, ...options } = {}) {
586
1408
  registerTool(name, schema, async (params) => {
587
- const cmd = formatReplCommand(name, params);
588
- const raw = await commandQueue.enqueue(cmd);
589
- const { text, isError } = classifyResponse(raw);
1409
+ const cmd = build(params);
1410
+ const { raw, stderrError } = await commandQueue.runExclusive(async (send) => {
1411
+ const reply = await send(cmd);
1412
+ return { raw: reply, stderrError: pencilProcess.lastStderrError };
1413
+ });
1414
+ const { text, isError: classified } = classifyResponse(raw);
1415
+ const isError = errorFrom === "stderr" ? stderrError : classified;
590
1416
  return {
591
1417
  content: [{ type: "text", text: isError ? enrichErrorMessage(text) : text }],
592
1418
  isError,
@@ -594,243 +1420,229 @@ function registerReadOnlyTool(name, schema, options) {
594
1420
  }, options);
595
1421
  }
596
1422
 
597
- // --- Mutating tool handler factory ---
598
-
599
- function registerMutatingTool(name, schema, options) {
600
- registerTool(name, schema, async (params) => {
601
- const cmd = formatReplCommand(name, params);
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.
1423
+ // Tools @pencil.dev/cli 0.2.9 / the Desktop server had and @pen.dev/cli does not. They stay
1424
+ // registered so a stale session or Desktop-style caller gets a replacement hint instead of
1425
+ // a bare "tool not found"; nothing reaches the engine and nothing is saved. The schema is
1426
+ // empty on purpose: any arguments the caller sends must reach the hint, not an SDK
1427
+ // validation error. REMOVED_TOOL_NAMES is the ONE table (pencil-error-enrichment.mjs).
646
1428
  function registerRemovedTool(name) {
647
1429
  registerTool(
648
1430
  name,
649
1431
  {},
650
1432
  async () => {
651
- formatReplCommand(name, {});
1433
+ formatReplCommand(name, {}); // throws `Unknown tool:` for anything outside the REPL surface
652
1434
  throw new Error(`Unknown tool: ${name}`);
653
1435
  },
654
- { description: `Not available in the headless adapter. ${enrichErrorMessage(`Unknown tool: ${name}`)}` }
1436
+ { description: `Not available in the headless adapter. ${removedToolHint(name)}` }
655
1437
  );
656
1438
  }
657
1439
 
658
1440
  // --- Read-only tools ---
659
1441
 
660
- registerReadOnlyTool("batch_get", {
661
- patterns: z.array(z.record(z.string(), z.unknown())).optional(),
662
- nodeIds: z.array(z.string()).optional(),
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(),
669
- });
670
-
671
1442
  registerReadOnlyTool(
672
1443
  "get_editor_state",
673
1444
  {
674
- include_schema: z.boolean(),
1445
+ include_schema: z.boolean().optional(),
675
1446
  },
1447
+ () => buildEditorStateCommand(),
676
1448
  {
677
1449
  description:
678
- "Editor state of the open document. Pass { include_schema: true } once to get the full batch_design operation grammar.",
1450
+ "State of the open document: its top-level nodes and the selection. `include_schema` is accepted and ignored; " +
1451
+ 'the operation grammar is read_skill({ path: "execute.md" }) and the file schema is read_skill({ path: "pen-schema.md" }).',
679
1452
  }
680
1453
  );
681
1454
 
682
- registerReadOnlyTool("get_guidelines", {
683
- category: z.string().optional(),
684
- name: z.string().optional(),
685
- params: z.record(z.string(), z.unknown()).optional(),
686
- });
1455
+ registerReadOnlyTool("get_variables", {}, () => buildVariablesCommand());
687
1456
 
688
- // get_screenshot — special handling for base64 image data + auto-save to disk
689
- registerTool("get_screenshot", { nodeId: z.string() }, async ({ nodeId }) => {
690
- const cmd = formatReplCommand("get_screenshot", { nodeId });
691
- const raw = await commandQueue.enqueue(cmd);
692
- const { text, isError } = classifyResponse(raw);
693
- if (isError) {
694
- return errorResult(enrichErrorMessage(text));
1457
+ registerReadOnlyTool(
1458
+ "read_skill",
1459
+ { path: z.string().optional() },
1460
+ ({ path }) => buildReadSkillCommand(path),
1461
+ {
1462
+ errorFrom: "stderr",
1463
+ description:
1464
+ "Read the engine's own design guidance: read_skill() lists the pages; read_skill({ path }) reads one (execute.md is the operation grammar, pen-schema.md the file schema, guide/<name>.md the design guides). Read-only. " +
1465
+ "Archetype names are listed in the engine index but this adapter does not expose get_style; use brand tokens or a guide/*.md page.",
695
1466
  }
1467
+ );
696
1468
 
697
- // Try parsing as JSON — pencil returns {"image":"<base64>","mimeType":"image/png"}
698
- let base64Data = null;
699
- let mimeType = "image/png";
1469
+ // get_screenshot — the reply carries a JSON array [{nodeId,image(base64),mimeType}]; parse it
1470
+ // from the UNtruncated text (the classifier's 64 KiB cap would break it) and persist a copy
1471
+ // next to the document.
1472
+ const MAX_SHOT_REPLY = 8 * 1024 * 1024;
1473
+ const UNSAVED_WARNING = "WARNING: rendered from unsaved memory, not the file on disk";
1474
+
1475
+ function parseScreenshots(text) {
1476
+ if (text.length > MAX_SHOT_REPLY) throw new Error("screenshot reply is larger than 8 MiB");
1477
+ const m = /\n(\[\s*\{[\s\S]*\])\s*$/.exec(text);
1478
+ if (!m) return null;
1479
+ let shots;
700
1480
  try {
701
- const parsed = JSON.parse(text);
702
- if (parsed.image && parsed.mimeType) {
703
- base64Data = parsed.image;
704
- mimeType = parsed.mimeType;
705
- }
1481
+ shots = JSON.parse(m[1]);
706
1482
  } catch {
707
- // Not JSON — try data URI pattern
708
- const base64Match = text.match(
709
- /data:image\/(png|jpeg);base64,([A-Za-z0-9+/=]+)/
710
- );
711
- if (base64Match) {
712
- base64Data = base64Match[2];
713
- mimeType = `image/${base64Match[1]}`;
1483
+ throw new Error("the screenshot reply carried malformed JSON");
1484
+ }
1485
+ if (!Array.isArray(shots)) throw new Error("the screenshot reply carried malformed JSON");
1486
+ for (const s of shots) {
1487
+ if (
1488
+ !s ||
1489
+ typeof s.image !== "string" ||
1490
+ !/^[A-Za-z0-9+/=]+$/.test(s.image) ||
1491
+ !Object.hasOwn(SHOT_EXT, s.mimeType)
1492
+ ) {
1493
+ throw new Error("the screenshot reply carried a malformed image entry");
714
1494
  }
715
1495
  }
1496
+ return shots;
1497
+ }
716
1498
 
717
- if (!base64Data) {
718
- return { content: [{ type: "text", text }] };
1499
+ registerTool("get_screenshot", { nodeId: z.string() }, async ({ nodeId }) => {
1500
+ const raw = await commandQueue.enqueue(buildScreenshotCommand(nodeId));
1501
+ const { text: capped, isError } = classifyResponse(raw);
1502
+ if (isError) {
1503
+ return errorResult(enrichErrorMessage(capped));
719
1504
  }
720
-
721
- // Auto-save screenshot to disk; a disk failure must not discard the image
722
- let savedPath = null;
723
- let saveNote = null;
1505
+ const shots = parseScreenshots(rawText(raw));
1506
+ const content = [];
1507
+ if (unpersistedEdits) content.push({ type: "text", text: UNSAVED_WARNING });
1508
+ if (!shots || shots.length === 0) {
1509
+ content.push({ type: "text", text: capped });
1510
+ return { content };
1511
+ }
1512
+ for (const shot of shots) content.push({ type: "image", data: shot.image, mimeType: shot.mimeType });
1513
+ // Persist the first image; a disk failure must not discard the image
724
1514
  try {
725
- savedPath = saveScreenshot(base64Data, nodeId);
1515
+ const savedPath = saveScreenshot(shots[0].image, shots[0].mimeType, nodeId);
1516
+ if (savedPath) content.push({ type: "text", text: `Screenshot saved: ${savedPath}` });
726
1517
  } catch (err) {
727
- saveNote = `Screenshot not saved to disk: ${oneLine(err?.message ?? err)}`;
728
- process.stderr.write(`[pencil-adapter] ${saveNote}\n`);
729
- }
730
- const content = [{ type: "image", data: base64Data, mimeType }];
731
- if (savedPath) {
732
- content.push({ type: "text", text: `Screenshot saved: ${savedPath}` });
733
- } else if (saveNote) {
734
- content.push({ type: "text", text: saveNote });
1518
+ const note = `Screenshot not saved to disk: ${oneLine(redactKey(err?.message ?? err))}`;
1519
+ process.stderr.write(`[pencil-adapter] ${note}\n`);
1520
+ content.push({ type: "text", text: note });
735
1521
  }
736
1522
  return { content };
737
1523
  });
738
1524
 
739
- registerRemovedTool("get_style_guide");
740
- registerRemovedTool("get_style_guide_tags");
741
-
742
- registerReadOnlyTool("get_variables", {});
743
-
744
- registerRemovedTool("find_empty_space_on_canvas");
745
- registerRemovedTool("search_all_unique_properties");
746
-
747
- registerReadOnlyTool("snapshot_layout", {
748
- parentId: z.string().optional(),
749
- maxDepth: z.number().optional(),
750
- problemsOnly: z.boolean().optional(),
751
- });
752
-
753
- // export_nodes — custom handler to rename exported files using node names
1525
+ // export_nodes — the output directory is agent-chosen, so it is a write primitive: absolute,
1526
+ // contained (containedDir), validated before anything is created. The adapter does not
1527
+ // rename exported files (the agent does, per ux-design-lead.md step 3.4) and returns only
1528
+ // the engine-printed paths that resolve inside the directory.
754
1529
  registerTool(
755
1530
  "export_nodes",
756
1531
  {
757
1532
  nodeIds: z.array(z.string()),
758
1533
  outputDir: z.string(),
759
- format: z.enum(["png", "jpeg", "webp", "pdf"]).optional(),
1534
+ format: z.enum(EXPORT_FORMATS).optional(),
760
1535
  scale: z.number().optional(),
761
1536
  quality: z.number().optional(),
762
1537
  },
763
1538
  async ({ nodeIds, outputDir, format, scale, quality }) => {
764
- const ext = format || "png";
765
-
766
- // Step 1: Try to get node names via batch_get
767
- let nameMap = new Map();
768
- try {
769
- const batchCmd = formatReplCommand("batch_get", { nodeIds });
770
- const batchRaw = await commandQueue.enqueue(batchCmd);
771
- const parsed = JSON.parse(rawText(batchRaw));
772
- if (parsed.nodes && Array.isArray(parsed.nodes)) {
773
- for (const node of parsed.nodes) {
774
- if (node.id && node.name) {
775
- nameMap.set(node.id, node.name);
776
- }
777
- }
778
- }
779
- } catch (err) {
780
- process.stderr.write(`[pencil-adapter] batch_get for node names failed: ${oneLine(err.message)}\n`);
781
- }
782
-
783
- // Step 2: Run the original export_nodes command
784
- const cmd = formatReplCommand("export_nodes", { nodeIds, outputDir, format, scale, quality });
785
- const raw = await commandQueue.enqueue(cmd);
1539
+ const ids = validateNodeIds(nodeIds);
1540
+ const fmt = validateExportFormat(format);
1541
+ validateScale(scale);
1542
+ validateQuality(quality);
1543
+ validateOutputDir(outputDir);
1544
+ const dir = containedDir(outputDir);
1545
+ // png/jpeg/webp write `<nodeId>.<format>`; a pdf export combines the nodes into one export.pdf
1546
+ const expected = fmt === "pdf" ? ["export.pdf"] : ids.map((id) => `${id}.${fmt}`);
1547
+ const overwritten = expected.filter((name) => existsSync(join(dir, name)));
1548
+ const raw = await commandQueue.enqueue(
1549
+ buildExportCommand({ nodeIds: ids, outputDir: dir, format: fmt, scale, quality })
1550
+ );
786
1551
  const { text, isError } = classifyResponse(raw);
787
1552
  if (isError) {
788
1553
  return errorResult(enrichErrorMessage(text));
789
1554
  }
1555
+ const exported = rawText(raw)
1556
+ .split("\n")
1557
+ .map((l) => l.trim())
1558
+ .filter((l) => l.startsWith("Exported "))
1559
+ .map((l) => l.slice("Exported ".length))
1560
+ .filter((p) => {
1561
+ if (!isAbsolute(p)) return false;
1562
+ try {
1563
+ return isInside(dir, existsSync(p) ? realpathSync(p) : resolve(p));
1564
+ } catch {
1565
+ return false;
1566
+ }
1567
+ });
1568
+ const lines = [];
1569
+ if (unpersistedEdits) lines.push(UNSAVED_WARNING);
1570
+ lines.push(`Exported to: ${dir}`);
1571
+ if (overwritten.length > 0) {
1572
+ lines.push(`These files already existed there and were overwritten: ${overwritten.join(", ")}`);
1573
+ }
1574
+ for (const p of exported) lines.push(`Exported ${p}`);
1575
+ return { content: [{ type: "text", text: lines.join("\n") }] };
1576
+ }
1577
+ );
790
1578
 
791
- // Step 3: Rename exported files from nodeId to sanitized name
792
- const renamedFiles = [];
793
- for (const nodeId of nodeIds) {
794
- const nodeName = nameMap.get(nodeId);
795
- const sanitized = nodeName ? sanitizeFilename(nodeName) : "";
796
- if (!sanitized || !/^[A-Za-z0-9_-]+$/.test(nodeId)) {
797
- renamedFiles.push(`${nodeId}.${ext}`);
798
- continue;
799
- }
800
- const oldPath = join(outputDir, `${nodeId}.${ext}`);
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;
1579
+ for (const name of REMOVED_TOOL_NAMES) registerRemovedTool(name);
1580
+
1581
+ // --- Mutating tool (auto-save after) ---
1582
+
1583
+ // A successful edit's reply: the engine text (an `## issues detected:` block passes through),
1584
+ // then the document it hit, then any save warning. A save that recreated a file removed
1585
+ // behind the session is announced FIRST.
1586
+ function editResult(saved, text) {
1587
+ const lines = [];
1588
+ if (saved.recreated) lines.push(recreatedNote(pencilProcess.outputFile));
1589
+ lines.push(text, `Document: ${pencilProcess.outputFile}`);
1590
+ if (saved.warning) lines.push(`WARNING: ${saved.warning}`);
1591
+ return { content: [{ type: "text", text: lines.join("\n") }] };
1592
+ }
1593
+
1594
+ registerTool(
1595
+ "batch_design",
1596
+ { operations: z.string() },
1597
+ async ({ operations }) => {
1598
+ const cmd = buildBatchDesignCommand(operations);
1599
+ // ONE exclusive job: the edit and its save cannot be separated by a crash respawn, a
1600
+ // queued open_document or another command, so a success reply means the edit was
1601
+ // applied AND persisted (or the reply says otherwise, in a result whose first line is
1602
+ // `REFUSED save: [reason=...]` or `NOT PERSISTED: [reason=...]`).
1603
+ return commandQueue.runExclusive(async (send) => {
1604
+ const { text, isError } = classifyResponse(await send(cmd));
1605
+ if (isError) {
1606
+ // Surface the error AND skip the save: a failed edit must not trigger a write that
1607
+ // replaces valid .pen content with empty or stale state. unpersistedEdits stays as it
1608
+ // was. MEASURED: an operation that fails (a bad Insert/Update/Delete argument) makes
1609
+ // the engine roll the whole block back ("All operations in this block have been rolled
1610
+ // back"), so the in-memory document is unchanged. NOT measured: a raw Export or
1611
+ // TakeScreenshot that errors mid-block, after earlier operations of the same block
1612
+ // ran. Whether those are rolled back is unknown, and an errored block is not marked
1613
+ // unpersisted for it: an accepted residual (the steering sentence tells the agent not
1614
+ // to call them inside batch_design).
1615
+ process.stderr.write(`[pencil-adapter] SKIPPED save (batch_design errored): ${oneLine(text).slice(0, 200)}\n`);
1616
+ return errorResult(enrichErrorMessage(text));
807
1617
  }
1618
+ let saved;
808
1619
  try {
809
- renameSync(oldPath, newPath);
810
- renamedFiles.push(`${sanitized}.${ext}`);
1620
+ saved = await guardedSave(send, "auto-save");
811
1621
  } catch (err) {
812
- process.stderr.write(`[pencil-adapter] rename ${oneLine(oldPath)} -> ${oneLine(newPath)} failed: ${oneLine(err.message)}\n`);
813
- renamedFiles.push(`${nodeId}.${ext}`);
1622
+ return await saveIncompleteResult(err);
814
1623
  }
815
- }
816
-
817
- const summary = `\nExported files: ${renamedFiles.join(", ")}`;
818
- return { content: [{ type: "text", text: text + summary }] };
1624
+ if (saved.refused) {
1625
+ logRefusal(saved, "auto-save");
1626
+ return errorResult(
1627
+ `${refusalText(saved, operations)}\n\nEngine response to the edit:\n${text}`
1628
+ );
1629
+ }
1630
+ if (saved.failed || saved.unconfirmed) {
1631
+ return errorResult(`${notPersistedResult(saved)}\n\nEngine response to the edit:\n${text}`);
1632
+ }
1633
+ return editResult(saved, text);
1634
+ });
1635
+ },
1636
+ {
1637
+ description:
1638
+ "Run a Pencil operation script (Insert, Update, Copy, Replace, Move, Delete, Generate, with short aliases I, U, C, R, M, D, G). " +
1639
+ 'The field is `operations`. Full grammar: read_skill({ path: "execute.md" }). ' +
1640
+ "The document is saved after every successful call (a read through Get/Print saves too); a save that did not persist is reported as an error whose first line is `REFUSED save: [reason=...]` (refused, with the refused operations echoed) or `NOT PERSISTED: [reason=...]`. " +
1641
+ "Layout problems arrive as an `## issues detected:` block in the reply. The reply ends with `Document: <path>`. " +
1642
+ RAW_CALL_STEERING,
819
1643
  }
820
1644
  );
821
1645
 
822
- // --- Mutating tools (auto-save after) ---
823
-
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.",
829
- });
830
-
831
- registerRemovedTool("replace_all_matching_properties");
832
- registerRemovedTool("set_variables");
833
-
834
1646
  // --- Meta tools ---
835
1647
 
836
1648
  registerTool(
@@ -840,49 +1652,50 @@ registerTool(
840
1652
  inputPath: z.string().optional(),
841
1653
  },
842
1654
  async ({ filePath, inputPath }) => {
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.
1655
+ // Absolute .pen paths, never a symlink: the child process and the save sentinel must
1656
+ // agree on which file is meant, and the engine writes through links. A refusal here
1657
+ // changes no session state.
846
1658
  const outFile = penPath(filePath, "filePath");
847
1659
  const inFile = inputPath ? penPath(inputPath, "inputPath") : null;
848
1660
 
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.
1661
+ // The kill-and-respawn runs inside the same exclusive section as the saves, so no
1662
+ // queued command or save can land between the old document going away and the new one
1663
+ // loading. There is no pre-switch save: every successful edit is saved in the same job,
1664
+ // so it could only persist state the sentinel would refuse.
854
1665
  return commandQueue.runExclusive(
855
1666
  async (send) => {
856
- if (inFile && inFile !== outFile && diskTopLevelCount(readTextOrNull(outFile)) !== null) {
1667
+ if (inFile && inFile !== outFile && diskTopLevelCount(readBytesOrNull(outFile)) !== null) {
857
1668
  return errorResult(
858
1669
  `Refusing to open: ${outFile} already holds a document and inputPath ${inFile} would replace it on the first save. ` +
859
1670
  `Open ${outFile} without inputPath, or open a new .pen path.`
860
1671
  );
861
1672
  }
1673
+ // Opening ANOTHER path while edits are unpersisted discards them with the old engine:
1674
+ // the result says so (re-opening the same path is the documented recovery).
1675
+ const discardsEdits = unpersistedEdits && pencilProcess.outputFile !== null && pencilProcess.outputFile !== outFile;
862
1676
  try {
1677
+ // spawn() reads the file's baseline (and the count the load must reproduce)
1678
+ // BEFORE the engine starts and commits the baseline at the prompt
863
1679
  await pencilProcess.restart(outFile, inFile);
864
1680
  const loadedFrom = pencilProcess.lastInFile;
865
- const memoryCount = memoryTopLevelCount(
866
- rawText(await send(formatReplCommand("batch_get", {})))
867
- );
1681
+ const nonce = newCountNonce();
1682
+ const memoryCount = memoryTopLevelCount(rawText(await send(buildCountCommand(nonce))), nonce);
868
1683
  let note = "";
869
1684
  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
- }
1685
+ const diskCount = pencilProcess.lastLoadDiskCount;
1686
+ const failure = loadFidelityFailure({ file: loadedFrom, diskCount, memoryCount });
1687
+ if (failure) throw new Error(failure);
881
1688
  if (diskCount === 0) {
882
1689
  note = ` (${loadedFrom} is an empty document; if you expected content, check version control)`;
883
1690
  }
884
1691
  }
1692
+ const captured = baseline.get();
1693
+ if (captured.tag === "unknown") {
1694
+ note += `\nWARNING: could not record a baseline for ${outFile} (${oneLine(redactKey(captured.detail ?? captured.cause))}); every save is refused until the file is a readable regular file and open_document succeeds on it.`;
1695
+ }
1696
+ if (discardsEdits) note += "\nNOTE: unsaved edits to the previous document were discarded.";
885
1697
  openFailure = null;
1698
+ clearRefusal(outFile);
886
1699
  return {
887
1700
  content: [
888
1701
  {
@@ -907,29 +1720,41 @@ registerTool(
907
1720
  {
908
1721
  allowWhenOpenFailed: true,
909
1722
  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.",
1723
+ "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. After a refused (stale) save, open_document on the file reloads what is on disk and re-enables saving.",
911
1724
  }
912
1725
  );
913
1726
 
914
1727
  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"));
1728
+ // Explicit saves are subject to the same sentinel and stale check as the auto-save,
1729
+ // inside one exclusive job.
1730
+ const saved = await commandQueue.runExclusive(async (send) => {
1731
+ try {
1732
+ return await guardedSave(send, "save");
1733
+ } catch (err) {
1734
+ return { incompleteResult: await saveIncompleteResult(err) };
1735
+ }
1736
+ });
1737
+ if (saved.incompleteResult) return saved.incompleteResult;
918
1738
  if (saved.refused) {
919
- process.stderr.write(`[pencil-adapter] ${oneLine(saved.message.split("\n")[0])} (${saved.reason})\n`);
920
- return errorResult(saved.message);
1739
+ logRefusal(saved, "save");
1740
+ return errorResult(refusalText(saved));
921
1741
  }
922
- const { text, isError } = classifyResponse(saved.raw);
923
- return isError
924
- ? errorResult(enrichErrorMessage(text))
925
- : { content: [{ type: "text", text }] };
1742
+ if (saved.failed || saved.unconfirmed) return errorResult(notPersistedResult(saved));
1743
+ const { text } = classifyResponse(saved.raw);
1744
+ const lines = [];
1745
+ if (saved.recreated) lines.push(recreatedNote(pencilProcess.outputFile));
1746
+ lines.push(text);
1747
+ if (saved.warning) lines.push(`WARNING: ${saved.warning}`);
1748
+ return { content: [{ type: "text", text: lines.join("\n") }] };
926
1749
  });
927
1750
 
928
1751
  // --- Start server ---
929
- // The PENCIL_CLI_KEY hard-fail and Node-version gate both run at the top of
930
- // this module, before the dynamic imports. See the comment block above the
931
- // imports for rationale.
1752
+ // The credential hard-fail and Node-version gate both run at the top of this module, before
1753
+ // the dynamic imports. See the comment block above the imports for rationale.
932
1754
 
933
- const transport = new StdioServerTransport();
934
- await server.connect(transport);
1755
+ try {
1756
+ await server.connect(new StdioServerTransport());
1757
+ } catch (err) {
1758
+ startFailed(err);
1759
+ }
935
1760
  process.stderr.write("[pencil-adapter] MCP server started on stdio\n");