viewable-one 0.12.2 → 0.12.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/README.md +2 -2
  3. package/SPAWN.md +107 -53
  4. package/glytch.mjs +41 -10
  5. package/lib/acp.mjs +110 -148
  6. package/lib/admission.mjs +25 -5
  7. package/lib/agents.mjs +59 -16
  8. package/lib/answerTag.mjs +47 -0
  9. package/lib/atomic.mjs +1 -16
  10. package/lib/auth.mjs +25 -9
  11. package/lib/boardside.mjs +28 -12
  12. package/lib/child.mjs +89 -116
  13. package/lib/claudeModels.mjs +168 -0
  14. package/lib/codex-rpc.mjs +2 -2
  15. package/lib/codex.mjs +43 -63
  16. package/lib/codexApps.mjs +5 -3
  17. package/lib/codexToolInputs.mjs +98 -22
  18. package/lib/codingChecks.mjs +8 -4
  19. package/lib/conversationRules.mjs +46 -6
  20. package/lib/detect.mjs +14 -23
  21. package/lib/devserver.mjs +6 -6
  22. package/lib/doctor.mjs +4 -2
  23. package/lib/folderReads.mjs +96 -0
  24. package/lib/followUps.mjs +170 -0
  25. package/lib/hosted.mjs +13 -4
  26. package/lib/init-connect.mjs +29 -10
  27. package/lib/lateResume.mjs +135 -0
  28. package/lib/logindaemon.mjs +113 -33
  29. package/lib/mcpjson.mjs +35 -2
  30. package/lib/multiwatch.mjs +25 -38
  31. package/lib/pagePictures.mjs +14 -11
  32. package/lib/paths.mjs +0 -1
  33. package/lib/permissionAsk.mjs +341 -58
  34. package/lib/procs.mjs +73 -2
  35. package/lib/refusal.mjs +0 -2
  36. package/lib/restartPass.mjs +39 -11
  37. package/lib/rowsAnswers.mjs +18 -34
  38. package/lib/rowsEvents.mjs +20 -2
  39. package/lib/runner-health.mjs +26 -2
  40. package/lib/runner.mjs +106 -1363
  41. package/lib/runnerAdmission.mjs +6 -12
  42. package/lib/runnerApi.mjs +20 -11
  43. package/lib/runnerBeat.mjs +384 -0
  44. package/lib/runnerCompletion.mjs +5 -2
  45. package/lib/runnerExecute.mjs +227 -0
  46. package/lib/runnerGates.mjs +338 -0
  47. package/lib/runnerLaunch.mjs +351 -0
  48. package/lib/runnerLease.mjs +31 -9
  49. package/lib/runnerOps.mjs +217 -0
  50. package/lib/runnerPace.mjs +10 -6
  51. package/lib/runnerRecovery.mjs +457 -0
  52. package/lib/runnerRegister.mjs +28 -7
  53. package/lib/runnerSettlement.mjs +29 -9
  54. package/lib/spawn.mjs +0 -5
  55. package/lib/sync.mjs +26 -14
  56. package/lib/viewableFolder.mjs +8 -2
  57. package/lib/worktree.mjs +66 -13
  58. package/lib/writePolicy.mjs +90 -10
  59. package/package.json +1 -1
package/lib/acp.mjs CHANGED
@@ -4,9 +4,11 @@ import { imageAttachments } from "./imageAttachments.mjs";
4
4
  //
5
5
  // Added 2026-09-02 for brief 15 decision 8 ("Engine layer: ACP beside the
6
6
  // existing Claude runner"), on the findings of the spike in
7
- // spikes/acp-2026-09-02/. That spike's `capture/*.jsonl` is the evidence for
8
- // every shape asserted below; where a line here says "verified", it means a
9
- // real adapter sent it, not that a doc implied it.
7
+ // spikes/acp-2026-09-02/ (removed 2026-11-02, #4451; read it with
8
+ // `git show e39d057c5:spikes/acp-2026-09-02/capture/claude.jsonl`). That
9
+ // spike's `capture/*.jsonl` is the evidence for every shape asserted below;
10
+ // where a line here says "verified", it means a real adapter sent it, not
11
+ // that a doc implied it.
10
12
  //
11
13
  // WHY THIS FILE EXISTS AT ALL, rather than a second `args` row in agents.mjs.
12
14
  // Claude Code speaks `--output-format stream-json`: one JSON object per line
@@ -24,6 +26,7 @@ import { imageAttachments } from "./imageAttachments.mjs";
24
26
  // stdout. The mapping, and it is the point of the file:
25
27
  //
26
28
  // agent_message_chunk -> {"type":"assistant", message.content:[{type:"text"}]}
29
+ // agent_thought_chunk -> {"type":"assistant", message.content:[{type:"thinking"}]}
27
30
  // tool_call (pending) -> {"type":"assistant", message.content:[{type:"tool_use", id}]}
28
31
  // tool_call_update -> {"type":"user", message.content:[{type:"tool_result", tool_use_id}]}
29
32
  // (completed/failed) ... which is what re-arms the stall watchdog
@@ -46,10 +49,10 @@ import { PassThrough } from "node:stream";
46
49
  import { Readable, Writable } from "node:stream";
47
50
  import { createRequire } from "node:module";
48
51
  import { accessSync, constants, readFileSync, writeFileSync } from "node:fs";
49
- import { readdir, readFile, unlink } from "node:fs/promises";
50
52
  import { delimiter, isAbsolute, join } from "node:path";
51
53
 
52
54
  import { DEFAULTS, attachChild } from "./child.mjs";
55
+ import { QUEUED, watchAnswers, watchReplyFiles } from "./followUps.mjs";
53
56
 
54
57
  // ---------------------------------------------------------------- the money
55
58
  //
@@ -180,74 +183,26 @@ export function estimateCostUsd(usage) {
180
183
 
181
184
  // --------------------------------------------------------- the permission door
182
185
  //
183
- // ACP puts the allowlist ON THE CLIENT, which is the shape the bridge wanted
184
- // all along. `session/request_permission` arrives as a REQUEST carrying
185
- // `toolCall.name` - the raw Claude tool name, `mcp__spikeboard__spike_ping`
186
- // in the capture - and `options` labelled by `kind`: allow_once, allow_always,
187
- // reject_once, reject_always. The spike answered from a regex list and the
188
- // turn continued, so this is verified rather than designed.
186
+ // ONE LIST, ONE JUDGE, the same two doors the `claude` engine has (#4615).
187
+ // 1. CLAUDE_TOOLS goes to the adapter's own Claude Code as `allowedTools`
188
+ // (`_meta.claudeCode.options` at session/new and session/load, which
189
+ // claude-agent-acp spreads into the SDK's options). Claude Code matches
190
+ // it there exactly as it matches `--allowedTools` for the `claude`
191
+ // engine, so a call on the list runs without reaching this client.
192
+ // 2. Everything else arrives as `session/request_permission` and goes to
193
+ // the runner's shared asker (permissionAsk.mjs, `createPermissionAsker`),
194
+ // the same judge Claude's `control_request` and Codex's approvals use: it
195
+ // refuses a command that drives another app, honours "Allow for this
196
+ // run" and remembered rules, and otherwise asks the person in the idea.
197
+ // With no asker (no board to ask on) the answer is no, as it is for the
198
+ // `claude` engine.
199
+ // This client used to answer from its own prefix matcher, which waved a
200
+ // chained command (`git status && ...`) or a read outside the folder
201
+ // (`cat /etc/passwd`) through on its first word. That matcher is gone.
189
202
  //
190
- // CLAUDE_TOOLS is the list, unchanged and un-forked: the same strings the
191
- // `claude` engine hands to `--allowedTools`, matched here instead of there.
192
- // One list, two enforcement points, no second place to keep in step.
193
- //
194
- // ALLOW_ONCE, NEVER ALLOW_ALWAYS. `allow_always` is cheaper - the adapter
195
- // stops asking - and it is wrong here, because "always" outlives the decision
196
- // that justified it: `Bash(git:*)` allows `git push` on the strength of a
197
- // `git status` the model asked about first. Asking every time costs a
198
- // round trip inside the adapter's own process and keeps every answer a
199
- // decision about the call in front of it.
200
-
201
- /** One entry of CLAUDE_TOOLS, split into the tool and its argument pattern.
202
- * `Read` -> {tool:"Read", arg:null}; `Bash(git:*)` -> {tool:"Bash", arg:"git:*"}. */
203
- function parseRule(rule) {
204
- const match = /^([A-Za-z_][\w-]*)\((.*)\)$/.exec(String(rule ?? "").trim());
205
- return match ? { tool: match[1], arg: match[2] } : { tool: String(rule ?? "").trim(), arg: null };
206
- }
207
-
208
- /** Does the allowlist cover this tool call?
209
- *
210
- * Three matches, and no fourth:
211
- * exact `Read` covers the tool named Read.
212
- * mcp namespace `mcp__glytch` covers `mcp__glytch__report`, because Claude
213
- * Code namespaces an MCP server's tools that way and the
214
- * allowlist names the SERVER (renamed from `board` to
215
- * `glytch` 2026-09-12, brief 31, Move 3b - see agents.mjs's
216
- * CLAUDE_TOOLS).
217
- * command prefix `Bash(git:*)` covers a Bash call whose command starts with
218
- * `git`. The `:*` suffix is Claude Code's own spelling.
219
- *
220
- * Anything else is rejected. A rule this function cannot understand matches
221
- * NOTHING - failing closed is the only safe direction for a door that spends
222
- * money and writes files. */
223
- export function toolCallAllowed(toolCall, allowTools = []) {
224
- const name = typeof toolCall?.name === "string" && toolCall.name.trim() !== ""
225
- ? toolCall.name.trim()
226
- // The capture shows `title` carrying the same string when `name` is
227
- // absent on an update; the permission request itself always has `name`.
228
- : typeof toolCall?.title === "string"
229
- ? toolCall.title.trim()
230
- : "";
231
- if (name === "") return false;
232
- const command =
233
- typeof toolCall?.rawInput?.command === "string" ? toolCall.rawInput.command.trim() : "";
234
- for (const raw of allowTools) {
235
- const { tool, arg } = parseRule(raw);
236
- if (tool === "") continue;
237
- if (arg === null) {
238
- if (name === tool) return true;
239
- // The MCP namespace, and only as a namespace: `mcp__glytch` must not
240
- // match `mcp__glytched__x`, so the separator is part of the test.
241
- if (name.startsWith(`${tool}__`)) return true;
242
- continue;
243
- }
244
- if (name !== tool) continue;
245
- const prefix = arg.endsWith(":*") ? arg.slice(0, -2) : arg;
246
- if (prefix === "" || command === "") continue;
247
- if (command === prefix || command.startsWith(`${prefix} `)) return true;
248
- }
249
- return false;
250
- }
203
+ // ALLOW_ONCE, NEVER ALLOW_ALWAYS. "Always" belongs to the asker, which keeps
204
+ // it per folder with the scope the person picked; the adapter's own
205
+ // `allow_always` would outlive that decision inside Claude Code.
251
206
 
252
207
  /** The option id to answer a permission request with.
253
208
  *
@@ -340,10 +295,13 @@ export function lineForUpdate(update, sessionId) {
340
295
  if (kind === "agent_message_chunk" || kind === "agent_thought_chunk") {
341
296
  const text = update?.content?.type === "text" ? update.content.text : null;
342
297
  if (typeof text !== "string" || text === "") return null;
298
+ // Reasoning goes out as a `thinking` block, the shape Claude and Codex
299
+ // already write, so it never joins the turn's answer text (#3644).
300
+ const block = kind === "agent_thought_chunk" ? { type: "thinking", thinking: text } : { type: "text", text };
343
301
  return {
344
302
  ...base,
345
303
  type: "assistant",
346
- message: { role: "assistant", content: [{ type: "text", text }] },
304
+ message: { role: "assistant", content: [block] },
347
305
  };
348
306
  }
349
307
  if (kind === "tool_call") {
@@ -481,6 +439,7 @@ export function runAcpChild(opts) {
481
439
  stopCheck,
482
440
  stopPollMs = 2000,
483
441
  acp = {},
442
+ askPermission,
484
443
  } = opts;
485
444
 
486
445
  return new Promise((resolve) => {
@@ -505,7 +464,7 @@ export function runAcpChild(opts) {
505
464
 
506
465
  let child;
507
466
  try {
508
- child = spawn(bin, args, { cwd, env: childEnvironment, stdio: ["pipe", "pipe", "pipe"] });
467
+ child = spawn(bin, args, { cwd, env: childEnvironment, detached: opts.recoveryGroup === true && (opts.platform ?? process.platform) !== "win32", stdio: ["pipe", "pipe", "pipe"] });
509
468
  } catch (error) {
510
469
  resolve({ ok: false, spawnError: error instanceof Error ? error.message : String(error), log: "" });
511
470
  return;
@@ -543,6 +502,8 @@ export function runAcpChild(opts) {
543
502
  };
544
503
 
545
504
  const handle = attachChild(facade, {
505
+ onProcess: opts.onProcess,
506
+ onSession: opts.onSession,
546
507
  resolve,
547
508
  maxMs,
548
509
  maxLogBytes,
@@ -607,6 +568,8 @@ export function runAcpChild(opts) {
607
568
 
608
569
  const cancelTurn = async () => {
609
570
  cancelled = true;
571
+ // Stop ends a wait on a person too: the ask is answered "cancelled".
572
+ abortPermissions();
610
573
  if (!sessionId || !connection) return;
611
574
  try {
612
575
  await connection.agent.notify("session/cancel", { sessionId });
@@ -731,88 +694,80 @@ export function runAcpChild(opts) {
731
694
 
732
695
  // --------------------------------------------------------- reply files
733
696
  //
734
- // THE SAME DOOR the streaming child has, behind a different knock. A
735
- // reply file is delivered as a second `session/prompt` into the same
736
- // sessionId rather than as a line on stdin, and everything else about it
737
- // is unchanged: sorted by name, consumed BEFORE it is sent (an unlink
738
- // that fails after a successful write is how a human's message arrives
739
- // twice), a `from` label wrapped around a peer's words.
740
- const watchReplies = () => {
741
- if (!replyDir || !replyPrefix) return;
742
- const watcher = handle.every(async () => {
743
- if (handle.settled()) { clearInterval(watcher); return; }
744
- try {
745
- const files = (await readdir(replyDir))
746
- .filter((f) => f.startsWith(replyPrefix) && f.endsWith(".json"))
747
- .sort();
748
- for (const file of files) {
749
- if (handle.settled()) break;
750
- const full = join(replyDir, file);
751
- let text = null;
752
- let replyImages;
753
- let fromField = null;
754
- try {
755
- const data = JSON.parse(await readFile(full, "utf8"));
756
- text = typeof data.message === "string" ? data.message : null;
757
- replyImages = data.images;
758
- fromField =
759
- typeof data.from === "string" && data.from.trim() !== "" ? data.from.trim() : null;
760
- } catch { continue; }
761
- try { promptBlocks(text ?? "", replyImages); } catch (error) {
762
- emit({ type: "result", subtype: "error_during_execution", is_error: true, session_id: sessionId, errors: [error.message] });
763
- cancelled = true;
764
- handle.kill();
765
- return;
766
- }
767
- try { await unlink(full); } catch { continue; }
768
- if (text) push(fromField ? `[message from ${fromField}] ${text}` : text, replyImages);
769
- }
770
- } catch { /* replyDir may not exist yet */ }
771
- }, replyPollMs);
772
- };
697
+ // THE SAME DOOR the streaming child has, behind a different knock - and
698
+ // since #4625 the same CODE (followUps.mjs). A reply file is delivered as a
699
+ // second `session/prompt` into the same sessionId rather than as a line on
700
+ // stdin; consuming, ordering and the `from` label are the shared part.
701
+ const watchReplies = () => watchReplyFiles({
702
+ handle, replyDir, replyPrefix, pollMs: replyPollMs,
703
+ active: () => !cancelled,
704
+ validate: (text, images) => { promptBlocks(text ?? "", images); },
705
+ onInvalid: (error) => {
706
+ emit({ type: "result", subtype: "error_during_execution", is_error: true, session_id: sessionId, errors: [error.message] });
707
+ cancelled = true;
708
+ handle.kill();
709
+ },
710
+ send: async ({ attributed, images }) => { push(attributed, images); },
711
+ });
773
712
 
774
713
  // Answers the human gave on the canvas after ask_user had already timed
775
714
  // out. Same contract as runStreamingChild: onDelivered runs AFTER the
776
715
  // message is accepted, never before, or a ruling is marked delivered to a
777
- // session that never heard it.
778
- let answerBusy = false;
779
- // Poll objects are recreated on every collection. Question identity,
780
- // scoped to this child, stays reserved until the prompt is acknowledged.
781
- const pendingAnswers = new Set();
782
- const watchAnswers = () => {
783
- if (!answerPoll) return;
784
- const collect = async () => {
785
- if (handle.settled() || cancelled) return;
786
- if (answerBusy) return;
787
- answerBusy = true;
788
- try {
789
- for (const answer of await answerPoll()) {
790
- if (handle.settled() || cancelled) break;
791
- const key = answer.deliveryKey ?? answer;
792
- if (pendingAnswers.has(key)) continue;
793
- pendingAnswers.add(key);
794
- push(answer.text, answer.images, async () => {
795
- try { await answer.onDelivered?.(); }
796
- finally { pendingAnswers.delete(key); }
797
- });
798
- }
799
- } catch { /* a poll that throws is not an answer either way */ }
800
- answerBusy = false;
801
- };
802
- handle.every(collect, answerPollMs);
803
- answerPoll.subscribe?.(collect);
804
- };
716
+ // session that never heard it. The shared watcher keeps a question
717
+ // reserved until its prompt is acknowledged (poll objects are recreated on
718
+ // every collection), and the queue below holds a message that arrives
719
+ // while a turn is running.
720
+ const watchAnswersInto = () => watchAnswers({
721
+ handle, answerPoll, pollMs: answerPollMs,
722
+ active: () => !cancelled,
723
+ send: async (answer, acknowledge) => {
724
+ push(answer.text, answer.images, acknowledge);
725
+ return QUEUED;
726
+ },
727
+ });
805
728
 
806
729
  // THE STALL WATCHDOG, byte for byte the rule runStreamingChild uses -
807
730
  // armed only when the MODEL should be producing output (a turn open, no
808
731
  // tool awaiting its result) - because the events it reads are now the
809
732
  // same events. This is the whole reason the translation above bothers to
810
733
  // emit tool_use/tool_result pairs at all.
734
+ // Permission asks waiting on the shared asker. Each wait ends when the
735
+ // adapter withdraws the request (its own signal), when the run settles,
736
+ // or on Stop; the asker then resolves null and the answer is "cancelled".
737
+ const pendingPermissions = new Set();
738
+ const askFor = async (params, requestSignal) => {
739
+ const toolCall = params?.toolCall ?? {};
740
+ const toolName = typeof toolCall.name === "string" ? toolCall.name.trim() : "";
741
+ const input = toolCall.rawInput && typeof toolCall.rawInput === "object" ? toolCall.rawInput : {};
742
+ // A call with no tool name cannot be judged or asked about: no.
743
+ if (toolName === "" || typeof askPermission !== "function") return { behavior: "deny" };
744
+ const controller = new AbortController();
745
+ const onAbort = () => controller.abort();
746
+ requestSignal?.addEventListener?.("abort", onAbort, { once: true });
747
+ if (requestSignal?.aborted || cancelled || handle.settled()) controller.abort();
748
+ pendingPermissions.add(controller);
749
+ try {
750
+ return await askPermission({ toolName, input, toolUseId: toolCall.toolCallId, signal: controller.signal });
751
+ } catch {
752
+ return controller.signal.aborted ? null : { behavior: "deny" };
753
+ } finally {
754
+ pendingPermissions.delete(controller);
755
+ requestSignal?.removeEventListener?.("abort", onAbort);
756
+ // The adapter is about to resume; its silence so far was ours.
757
+ handle.state.lastStdoutAt = Date.now();
758
+ }
759
+ };
760
+ const abortPermissions = () => { for (const controller of pendingPermissions) controller.abort(); };
761
+ child.once("close", abortPermissions);
762
+ child.once("error", abortPermissions);
763
+
811
764
  const armStallWatchdog = () => {
812
765
  const watcher = handle.every(() => {
813
766
  const state = handle.state;
814
767
  if (state.settled) return;
815
- const armed = !state.sawResult && state.openToolUses.size === 0;
768
+ // A run waiting on a person is not a stalled run (child.mjs does the
769
+ // same with its pendingPermissions).
770
+ const armed = !state.sawResult && state.openToolUses.size === 0 && pendingPermissions.size === 0;
816
771
  if (armed && Date.now() - state.lastStdoutAt >= stallMs) {
817
772
  state.stalled = true;
818
773
  handle.kill();
@@ -837,8 +792,11 @@ export function runAcpChild(opts) {
837
792
  }
838
793
  emit(lineForUpdate(update, sessionId));
839
794
  })
840
- .onRequest("session/request_permission", ({ params }) => {
841
- const allow = toolCallAllowed(params?.toolCall, acp.allowTools ?? []);
795
+ .onRequest("session/request_permission", async ({ params, signal }) => {
796
+ const verdict = await askFor(params, signal);
797
+ // null: the wait was withdrawn or the run ended, so nothing decided.
798
+ if (!verdict) return { outcome: { outcome: "cancelled" } };
799
+ const allow = verdict.behavior === "allow";
842
800
  const optionId = permissionOptionId(params?.options, allow);
843
801
  // The decision goes in the LOG, as a tool_result-shaped note beside
844
802
  // the call it answered, because a session that quietly did less
@@ -892,21 +850,25 @@ export function runAcpChild(opts) {
892
850
  // `-32000 Authentication required` from session/new and stopped there.)
893
851
  const authMethods = Array.isArray(init?.authMethods) ? init.authMethods : [];
894
852
 
853
+ // The allowlist rides to the adapter's Claude Code as `allowedTools`
854
+ // (the permission door above); without one nothing is auto-allowed.
855
+ const allowedTools = Array.isArray(acp.allowTools) ? acp.allowTools : [];
895
856
  const params = {
896
857
  cwd,
897
858
  mcpServers: Array.isArray(acp.mcpServers) ? acp.mcpServers : [],
859
+ ...(allowedTools.length > 0 ? { _meta: { claudeCode: { options: { allowedTools } } } } : {}),
898
860
  };
899
861
  let created;
900
- // RESUME IS UNTESTED and is treated as such. `loadSession: true` was
901
- // advertised in the spike's initialize reply, but no session was ever
902
- // loaded, so this TRIES and falls back to a fresh session rather than
903
- // failing the run over a path nobody has watched work.
862
+ // Explicit crash recovery requires the saved conversation. Ordinary
863
+ // resumes retain the existing fresh-session fallback.
904
864
  const resume = typeof acp.resumeSessionId === "string" ? acp.resumeSessionId.trim() : "";
865
+ if (opts.requireResume && resume && init?.agentCapabilities?.loadSession !== true) throw new Error("Interrupted conversation cannot be resumed by this adapter.");
905
866
  if (resume !== "" && init?.agentCapabilities?.loadSession === true) {
906
867
  try {
907
868
  created = await connection.agent.request("session/load", { ...params, sessionId: resume });
908
869
  sessionId = resume;
909
870
  } catch (error) {
871
+ if (opts.requireResume) throw error;
910
872
  emit({
911
873
  type: "system",
912
874
  subtype: "resume_failed",
@@ -990,7 +952,7 @@ export function runAcpChild(opts) {
990
952
  await set("model", typeof acp.model === "string" ? acp.model.trim() : "");
991
953
 
992
954
  watchReplies();
993
- watchAnswers();
955
+ watchAnswersInto();
994
956
  armStallWatchdog();
995
957
  push(prompt, images);
996
958
  };
package/lib/admission.mjs CHANGED
@@ -2,12 +2,31 @@ import { mkdir, writeFile, unlink, link, open } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
3
  import { hostname } from "node:os";
4
4
  import { randomUUID } from "node:crypto";
5
+ import { readProcessIdentity } from "./devserver.mjs";
6
+ import { sameProcessIdentity } from "./procs.mjs";
5
7
  import { SPAWN_DIR } from "./spawn.mjs";
6
8
 
7
- const deadLocalOwner = (owner) => {
9
+ // Successful self identity is immutable for this process. Share concurrent
10
+ // probes too, but retry an unavailable probe instead of caching its failure.
11
+ const selfIdentities = new WeakMap();
12
+ export function selfProcessIdentity(readIdentity = readProcessIdentity) {
13
+ let pending = selfIdentities.get(readIdentity);
14
+ if (!pending) {
15
+ pending = Promise.resolve().then(() => readIdentity(process.pid)).catch(() => null).then(identity => {
16
+ if (!Number.isFinite(identity?.startedAt) || !identity?.command) selfIdentities.delete(readIdentity);
17
+ return identity;
18
+ });
19
+ selfIdentities.set(readIdentity, pending);
20
+ }
21
+ return pending;
22
+ }
23
+
24
+ const deadLocalOwner = async (owner, readIdentity) => {
8
25
  if (owner?.host !== hostname() || !Number.isInteger(owner.pid) || owner.pid <= 0) return false;
9
- try { process.kill(owner.pid, 0); return false; }
26
+ try { process.kill(owner.pid, 0); }
10
27
  catch (error) { return error?.code === "ESRCH"; }
28
+ const current = await readIdentity(owner.pid).catch(() => null);
29
+ return sameProcessIdentity({ startedAt: owner.ownerStartedAt }, current) === false;
11
30
  };
12
31
 
13
32
  /** The bytes at `path` AND the identity of the file they came off, read
@@ -38,13 +57,14 @@ const readLock = async (path) => {
38
57
  * release. Publish a complete owner via an exclusive hard link: a reader can
39
58
  * never mistake an incomplete owner write for a dead process. The directory
40
59
  * override lets registry restores reuse this protocol apart from run claims. */
41
- export async function acquireAdmission(root, { directory = join(root, SPAWN_DIR) } = {}) {
60
+ export async function acquireAdmission(root, { directory = join(root, SPAWN_DIR), readIdentity = readProcessIdentity } = {}) {
42
61
  const dir = directory;
43
62
  const path = join(dir, ".admission.lock");
44
63
  const token = randomUUID();
45
64
  const temporary = join(dir, `.admission-owner-${token}`);
46
65
  await mkdir(dir, { recursive: true });
47
- await writeFile(temporary, JSON.stringify({ pid: process.pid, host: hostname(), token }), { flag: "wx" });
66
+ const identity = await selfProcessIdentity(readIdentity);
67
+ await writeFile(temporary, JSON.stringify({ pid: process.pid, host: hostname(), ownerStartedAt: identity?.startedAt, ownerCommand: identity?.command, token }), { flag: "wx" });
48
68
  try {
49
69
  for (;;) {
50
70
  try {
@@ -73,7 +93,7 @@ export async function acquireAdmission(root, { directory = join(root, SPAWN_DIR)
73
93
  // supply anything, so the inode it is written on IS its generation -
74
94
  // unlinking frees it and the next holder is a different inode entirely.
75
95
  const generation =
76
- deadLocalOwner(owner) && /^[a-f0-9-]{36}$/.test(owner.token ?? "") ? owner.token : corrupt;
96
+ await deadLocalOwner(owner, readIdentity) && /^[a-f0-9-]{36}$/.test(owner.token ?? "") ? owner.token : corrupt;
77
97
  if (generation) {
78
98
  // One cleaner for this exact dead generation. Keep its tiny marker:
79
99
  // another delayed cleaner must never unlink a newer holder's lock.
package/lib/agents.mjs CHANGED
@@ -94,6 +94,7 @@ import { PLAN_MODE_AGENTS } from "./spawn.mjs";
94
94
  // SERVER_KEY, so this imports that one spelling rather than adding a fourth
95
95
  // copy of the literal.
96
96
  import { SERVER_KEY } from "./init-connect.mjs";
97
+ import { randomBytes } from "node:crypto";
97
98
 
98
99
  /** What a spawned session may do under Claude Code.
99
100
  *
@@ -165,6 +166,19 @@ export const CLAUDE_TOOLS = [
165
166
  "Bash(grep:*)",
166
167
  ];
167
168
 
169
+ /** Commands that click, type into or look at another app's window (#4204,
170
+ * #4273). Barred for Claude Code so the Mac never asks it for Accessibility or
171
+ * Screen Recording, and so "Allow for this run" (#4105) cannot let them
172
+ * through: a deny rule is checked before any permission prompt. `open -a
173
+ * <App>` is not here and stays allowed. Only a command that STARTS with one of
174
+ * these is caught: `node -e` can still spawn one, which the rule in
175
+ * conversationRules.mjs covers in words only. */
176
+ export const CLAUDE_CLICK_AND_SCREEN_TOOLS = [
177
+ "Bash(osascript:*)",
178
+ "Bash(screencapture:*)",
179
+ "Bash(cliclick:*)",
180
+ ];
181
+
168
182
  /** Tools a headless session must never be OFFERED, because they open an
169
183
  * interactive prompt no one is there to answer.
170
184
  *
@@ -180,7 +194,10 @@ export const CLAUDE_TOOLS = [
180
194
  * terminal nobody is watching. The preamble already points every session at
181
195
  * the board's ask_user instead; taking the dead tool away means the model
182
196
  * reaches for the live one first rather than after a failed call. */
183
- export const CLAUDE_DISALLOWED_TOOLS = ["EnterPlanMode", "AskUserQuestion"];
197
+ export const CLAUDE_DISALLOWED_TOOLS = [
198
+ "EnterPlanMode", "AskUserQuestion",
199
+ ...CLAUDE_CLICK_AND_SCREEN_TOOLS,
200
+ ];
184
201
 
185
202
  /** The two tools that reach the web. Allowed up front only when the person
186
203
  * turned web search on for this run (`webSearch: true` on the spawn request);
@@ -191,8 +208,12 @@ export const CLAUDE_WEB_TOOLS = ["WebSearch", "WebFetch"];
191
208
  /** The allowlist for one run: the standing list, plus the web tools when the
192
209
  * request switched web search on. A plain function of the request, so the
193
210
  * one-shot and streaming command lines cannot disagree. */
194
- export const claudeToolsFor = (wants = {}) =>
195
- wants.webSearch === true ? [...CLAUDE_TOOLS, ...CLAUDE_WEB_TOOLS] : CLAUDE_TOOLS;
211
+ export const claudeToolsFor = (wants = {}) => {
212
+ const tools = wants.boardServerKey
213
+ ? CLAUDE_TOOLS.map(tool => tool === `mcp__${SERVER_KEY}` ? `mcp__${wants.boardServerKey}` : tool)
214
+ : CLAUDE_TOOLS;
215
+ return wants.webSearch === true ? [...tools, ...CLAUDE_WEB_TOOLS] : tools;
216
+ };
196
217
 
197
218
  export const AGENTS = {
198
219
  codex: {
@@ -302,7 +323,7 @@ export const AGENTS = {
302
323
  // WHAT THIS ENGINE IS FOR, and it is not "replacing claude". It is the one
303
324
  // engine whose events arrive in a shape the live view of brief 15 wants
304
325
  // without inference: streamed text, tool open and close, an
305
- // auto-answerable permission door, a session that takes a second prompt,
326
+ // permission door the client answers, a session that takes a second prompt,
306
327
  // and a `session/cancel` for Stop. What it costs is the two things this
307
328
  // bridge learned the hard way and acp.mjs re-states: no ceiling to set, and
308
329
  // no dollar figure to report. Every receipt from here says "estimate".
@@ -311,9 +332,9 @@ export const AGENTS = {
311
332
  bin: process.execPath,
312
333
  binEnv: "PM_ACP_NODE_BIN",
313
334
  argsEnv: "PM_ACP_CLAUDE_ARGS",
314
- // The SAME allowlist as `claude`, enforced at a different door: there it
315
- // is `--allowedTools`, here it is the client answering
316
- // session/request_permission from CLAUDE_TOOLS. One list, two doors.
335
+ // The SAME allowlist as `claude`, handed to the adapter's Claude Code as
336
+ // `allowedTools` at session/new; anything off it reaches the client as
337
+ // session/request_permission and goes to the shared asker (#4615).
317
338
  fenced: true,
318
339
  // The board server is passed inline at session/new (acpServersFor), so
319
340
  // there is nothing to write into the worktree.
@@ -530,6 +551,9 @@ export function acpServersFor(agent, { mcpUrl, token, sessionKey, boardId }) {
530
551
  // server of the person's named `glytch_` or `glytch__x`, whose tools would
531
552
  // otherwise read as glytch's; no glytch tool starts with `_` or holds `__`.
532
553
  const TOOL_NAME_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-";
554
+ /** The per-launch board server name (#3612): `v` + five hex characters. */
555
+ export const boardRunKey = () => `v${randomBytes(3).toString("hex").slice(0, 5)}`;
556
+
533
557
  export function appAskRules(keep = `mcp__${SERVER_KEY}__`) {
534
558
  const rules = [];
535
559
  for (let i = "mcp__".length; i < keep.length; i += 1) {
@@ -538,6 +562,17 @@ export function appAskRules(keep = `mcp__${SERVER_KEY}__`) {
538
562
  return [...rules, `${keep}_*`, `${keep}*__*`];
539
563
  }
540
564
 
565
+ /** Claude Code takes its own names (opus, sonnet, haiku, fable, or a full
566
+ * claude-… id), never an OpenRouter id. The Board Agent keeps
567
+ * "anthropic/claude-haiku-5.5" when a person moves it to Claude Code, and
568
+ * `--model` refuses that (#3869). The family alias is the closest name the
569
+ * CLI always knows; any other id passes through unchanged. */
570
+ export function claudeModelName(model) {
571
+ const name = typeof model === "string" ? model.trim() : "";
572
+ const family = /^anthropic\/(?:[^/]*?-)?(fable|opus|sonnet|haiku)(?:-|$)/i.exec(name);
573
+ return family ? family[1].toLowerCase() : name;
574
+ }
575
+
541
576
  export function commandFor(agent, env = process.env, wants = {}) {
542
577
  const spec = AGENTS[agentFor(agent)];
543
578
  const bin = env[spec.binEnv]?.trim() || spec.bin;
@@ -593,7 +628,7 @@ export function commandFor(agent, env = process.env, wants = {}) {
593
628
  "--strict-mcp-config", "--mcp-config", '{"mcpServers":{}}',
594
629
  "--setting-sources", "", "--settings", '{"disableAllHooks":true}',
595
630
  "--disable-slash-commands", "--no-chrome", "--no-session-persistence"];
596
- if (typeof wants.model === "string" && wants.model.trim()) args.push("--model", wants.model.trim());
631
+ if (typeof wants.model === "string" && wants.model.trim()) args.push("--model", claudeModelName(wants.model));
597
632
  const effort = typeof wants.effort === "string" ? wants.effort.trim() : "";
598
633
  if (effort && wants.claudeEfforts?.includes(effort)) args.push("--effort", effort);
599
634
  return { bin, args, spec, ignored: effort && !wants.claudeEfforts?.includes(effort) ? ["effort (not supported by this model on this computer)"] : [], acp: null };
@@ -605,7 +640,16 @@ export function commandFor(agent, env = process.env, wants = {}) {
605
640
  // the environment can build it - `acp-claude` resolves its adapter's
606
641
  // entrypoint, and PM_ACP_ADAPTER overrides it. Every other engine ignores
607
642
  // the field.
608
- const asked = { ...wants, env };
643
+ // Claude caches OAuth failures by server name even when --mcp-config
644
+ // supplies a working bearer (#3612). A fresh, runner-owned name on each
645
+ // launch cannot inherit the person's connector state or a previous
646
+ // expired bearer. Keep config, allowlist and app ask rules on ONE name.
647
+ // SIX CHARACTERS, like `glytch`: appAskRules grows by 63 rules per
648
+ // character, and a longer name would push the computer-apps --settings
649
+ // past Windows' command-line limit. src/components/run/runWords.ts
650
+ // matches this `v` + five hex shape to read the calls as board work.
651
+ const asked = { ...wants, env, ...(agentFor(agent) === "claude"
652
+ ? { boardServerKey: boardRunKey() } : {}) };
609
653
  let args = asked.streaming && spec.streamingArgs ? spec.streamingArgs(asked) : spec.args(asked);
610
654
  let overridden = false;
611
655
  if (typeof raw === "string" && raw.trim() !== "") {
@@ -633,7 +677,8 @@ export function commandFor(agent, env = process.env, wants = {}) {
633
677
  // an older CLI must not fail the whole run over a preference.
634
678
  const ignored = [];
635
679
  if (!overridden) {
636
- const model = typeof wants.model === "string" ? wants.model.trim() : "";
680
+ const rawModel = typeof wants.model === "string" ? wants.model.trim() : "";
681
+ const model = agentFor(agent) === "claude" ? claudeModelName(rawModel) : rawModel;
637
682
  if (model !== "" && spec.modelFlag) args = [...args, spec.modelFlag, model];
638
683
  const effort = typeof wants.effort === "string" ? wants.effort.trim() : "";
639
684
  if (effort !== "") {
@@ -670,10 +715,8 @@ export function commandFor(agent, env = process.env, wants = {}) {
670
715
  // into .mcp.json - `{"mcpServers":{"board":{"type":"http","url":...,
671
716
  // "headers":{...}}}}` - so this is the JSON `--mcp-config` is documented
672
717
  // to accept as a string, run against the real binary rather than assumed.
673
- // RENAMED 2026-09-12 (brief 31, Move 3b): the key WRITTEN below is
674
- // `glytch` (SERVER_KEY), not `board` - the verification above predates
675
- // the rename and is kept dated rather than rerun, since it was checking
676
- // the shape `--mcp-config` accepts, not the key name.
718
+ // The runtime key is launch-specific (#3612); saved connectors retain
719
+ // their names. The shape and authentication headers stay the same.
677
720
  //
678
721
  // --strict-mcp-config makes this the ONLY MCP config the session sees:
679
722
  // any committed .mcp.json (which may still name the retired local
@@ -693,7 +736,7 @@ export function commandFor(agent, env = process.env, wants = {}) {
693
736
  const mcpServers =
694
737
  boardUrl && boardToken
695
738
  ? {
696
- [SERVER_KEY]: {
739
+ [asked.boardServerKey]: {
697
740
  type: "http",
698
741
  url: boardUrl,
699
742
  headers: {
@@ -714,7 +757,7 @@ export function commandFor(agent, env = process.env, wants = {}) {
714
757
  // their own settings before still asks each time; in -p mode that
715
758
  // ask is refused until the permission ask (#478) reaches the person.
716
759
  const apps = wants.computerApps === true
717
- ? ["--settings", JSON.stringify({ permissions: { ask: appAskRules() } })]
760
+ ? ["--settings", JSON.stringify({ permissions: { ask: appAskRules(`mcp__${asked.boardServerKey}__`) } })]
718
761
  : ["--strict-mcp-config"];
719
762
  args = [...args, ...apps, "--mcp-config", JSON.stringify({ mcpServers })];
720
763
  }