viewable-one 0.12.1 → 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 (71) hide show
  1. package/CHANGELOG.md +71 -1
  2. package/README.md +31 -48
  3. package/SPAWN.md +136 -79
  4. package/glytch.mjs +41 -10
  5. package/lib/acp.mjs +152 -150
  6. package/lib/admission.mjs +25 -5
  7. package/lib/agent-selection.mjs +5 -4
  8. package/lib/agents.mjs +68 -24
  9. package/lib/answerTag.mjs +47 -0
  10. package/lib/atomic.mjs +1 -16
  11. package/lib/auth.mjs +172 -52
  12. package/lib/authenticatedHttp.mjs +10 -3
  13. package/lib/boardside.mjs +28 -12
  14. package/lib/child.mjs +129 -116
  15. package/lib/claudeModels.mjs +168 -0
  16. package/lib/codex-rpc.mjs +2 -2
  17. package/lib/codex.mjs +50 -50
  18. package/lib/codexApps.mjs +17 -3
  19. package/lib/codexToolInputs.mjs +98 -22
  20. package/lib/codingChecks.mjs +8 -4
  21. package/lib/conversationRules.mjs +47 -7
  22. package/lib/detect.mjs +39 -24
  23. package/lib/devserver.mjs +30 -19
  24. package/lib/doctor.mjs +10 -8
  25. package/lib/folderReads.mjs +96 -0
  26. package/lib/followUps.mjs +170 -0
  27. package/lib/hosted.mjs +13 -4
  28. package/lib/init-connect.mjs +29 -10
  29. package/lib/lateResume.mjs +135 -0
  30. package/lib/logindaemon.mjs +129 -49
  31. package/lib/logs.mjs +2 -2
  32. package/lib/mcpjson.mjs +35 -2
  33. package/lib/memberPreview.mjs +22 -14
  34. package/lib/multiwatch.mjs +28 -41
  35. package/lib/pagePictures.mjs +15 -12
  36. package/lib/pageRoutes.mjs +5 -2
  37. package/lib/paths.mjs +3 -3
  38. package/lib/permissionAsk.mjs +344 -61
  39. package/lib/previewGateway.mjs +4 -3
  40. package/lib/procs.mjs +73 -2
  41. package/lib/refusal.mjs +0 -2
  42. package/lib/registry.mjs +7 -7
  43. package/lib/repomap.mjs +4 -3
  44. package/lib/restartPass.mjs +39 -11
  45. package/lib/rowsAnswers.mjs +52 -69
  46. package/lib/rowsEvents.mjs +20 -2
  47. package/lib/runner-health.mjs +29 -5
  48. package/lib/runner.mjs +161 -1347
  49. package/lib/runnerAdmission.mjs +6 -12
  50. package/lib/runnerApi.mjs +20 -11
  51. package/lib/runnerBeat.mjs +384 -0
  52. package/lib/runnerCompletion.mjs +5 -2
  53. package/lib/runnerExecute.mjs +227 -0
  54. package/lib/runnerGates.mjs +338 -0
  55. package/lib/runnerLaunch.mjs +351 -0
  56. package/lib/runnerLease.mjs +31 -9
  57. package/lib/runnerOps.mjs +217 -0
  58. package/lib/runnerPace.mjs +10 -6
  59. package/lib/runnerRecovery.mjs +457 -0
  60. package/lib/runnerRegister.mjs +29 -8
  61. package/lib/runnerSettlement.mjs +43 -16
  62. package/lib/runnerWorkspace.mjs +19 -4
  63. package/lib/spawn.mjs +0 -5
  64. package/lib/sync.mjs +28 -16
  65. package/lib/uninstall-project.mjs +12 -11
  66. package/lib/uninstall.mjs +32 -25
  67. package/lib/update.mjs +4 -4
  68. package/lib/{glytchFolder.mjs → viewableFolder.mjs} +22 -16
  69. package/lib/worktree.mjs +83 -26
  70. package/lib/writePolicy.mjs +90 -10
  71. package/package.json +2 -2
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") {
@@ -412,7 +370,7 @@ export function lineForUpdate(update, sessionId) {
412
370
  * an error - a future adapter inventing one must not turn finished work into
413
371
  * a failed receipt, which is the mistake that cost 26 sessions their verdict
414
372
  * (child.mjs, "a finished stream is finished"). */
415
- export function resultEnvelope({ response, sessionId, turns, durationMs, priorCostUsd = 0 }) {
373
+ export function resultEnvelope({ response, sessionId, turns, durationMs, priorCostUsd = 0, result = "" }) {
416
374
  const stop = response?.stopReason;
417
375
  const isError = stop === "refusal" || stop === "cancelled";
418
376
  // CUMULATIVE, because the runner keeps only the LAST envelope (child.mjs,
@@ -434,6 +392,7 @@ export function resultEnvelope({ response, sessionId, turns, durationMs, priorCo
434
392
  subtype: isError ? `error_${stop}` : "success",
435
393
  is_error: isError,
436
394
  stop_reason: stop ?? "unknown",
395
+ ...(stop !== "cancelled" && result !== "" ? { result } : {}),
437
396
  session_id: sessionId,
438
397
  num_turns: turns,
439
398
  duration_ms: durationMs,
@@ -480,6 +439,7 @@ export function runAcpChild(opts) {
480
439
  stopCheck,
481
440
  stopPollMs = 2000,
482
441
  acp = {},
442
+ askPermission,
483
443
  } = opts;
484
444
 
485
445
  return new Promise((resolve) => {
@@ -504,7 +464,7 @@ export function runAcpChild(opts) {
504
464
 
505
465
  let child;
506
466
  try {
507
- 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"] });
508
468
  } catch (error) {
509
469
  resolve({ ok: false, spawnError: error instanceof Error ? error.message : String(error), log: "" });
510
470
  return;
@@ -528,6 +488,8 @@ export function runAcpChild(opts) {
528
488
  };
529
489
 
530
490
  const facade = {
491
+ // Windows taskkill needs the adapter identity to stop its descendants.
492
+ pid: child.pid,
531
493
  stdout: translated,
532
494
  stderr: child.stderr,
533
495
  kill: (signal) => child.kill(signal),
@@ -540,6 +502,8 @@ export function runAcpChild(opts) {
540
502
  };
541
503
 
542
504
  const handle = attachChild(facade, {
505
+ onProcess: opts.onProcess,
506
+ onSession: opts.onSession,
543
507
  resolve,
544
508
  maxMs,
545
509
  maxLogBytes,
@@ -594,6 +558,8 @@ export function runAcpChild(opts) {
594
558
 
595
559
  let connection = null;
596
560
  let turns = 0;
561
+ // Only the current prompt owns closing text; session/load can replay history.
562
+ let answerChunks = null;
597
563
  let cancelled = false;
598
564
  // Every turn's estimate, added up, because the receipt reads the last
599
565
  // envelope only. See resultEnvelope.
@@ -602,6 +568,8 @@ export function runAcpChild(opts) {
602
568
 
603
569
  const cancelTurn = async () => {
604
570
  cancelled = true;
571
+ // Stop ends a wait on a person too: the ask is answered "cancelled".
572
+ abortPermissions();
605
573
  if (!sessionId || !connection) return;
606
574
  try {
607
575
  await connection.agent.notify("session/cancel", { sessionId });
@@ -640,7 +608,7 @@ export function runAcpChild(opts) {
640
608
  return [{ type: "text", text }, ...attachments.map((image) => ({ type: "image", mimeType: image.mimeType, data: image.data }))];
641
609
  };
642
610
 
643
- const runTurn = async (text, imageUrls) => {
611
+ const runTurn = async (text, imageUrls, boardReply = false) => {
644
612
  if (!connection || !sessionId || cancelled) return;
645
613
  turns += 1;
646
614
  // A new turn means whatever envelope stood no longer describes the
@@ -649,10 +617,15 @@ export function runAcpChild(opts) {
649
617
  handle.markSent();
650
618
  const at = Date.now();
651
619
  let response;
620
+ let validated = false;
621
+ const chunks = [];
652
622
  try {
623
+ const blocks = promptBlocks(text, imageUrls);
624
+ validated = true;
625
+ answerChunks = chunks;
653
626
  response = await connection.agent.request("session/prompt", {
654
627
  sessionId,
655
- prompt: promptBlocks(text, imageUrls),
628
+ prompt: blocks,
656
629
  });
657
630
  } catch (error) {
658
631
  // A failed prompt is a failed TURN, not a crashed runner. It becomes
@@ -665,9 +638,13 @@ export function runAcpChild(opts) {
665
638
  session_id: sessionId,
666
639
  num_turns: turns,
667
640
  duration_ms: Date.now() - at,
668
- error: String(error?.message ?? error),
641
+ error: boardReply && validated
642
+ ? "ACP could not confirm delivery of your board reply."
643
+ : String(error?.message ?? error),
669
644
  });
670
645
  return;
646
+ } finally {
647
+ answerChunks = null;
671
648
  }
672
649
  const envelope = resultEnvelope({
673
650
  response,
@@ -675,9 +652,11 @@ export function runAcpChild(opts) {
675
652
  turns,
676
653
  durationMs: Date.now() - startedAt,
677
654
  priorCostUsd: costSoFar,
655
+ result: cancelled || handle.settled() ? "" : chunks.join(""),
678
656
  });
679
657
  if (typeof envelope.total_cost_usd === "number") costSoFar = envelope.total_cost_usd;
680
658
  emit(envelope);
659
+ return !envelope.is_error && !cancelled && !handle.settled();
681
660
  };
682
661
 
683
662
  const pump = async () => {
@@ -685,7 +664,17 @@ export function runAcpChild(opts) {
685
664
  promptBusy = true;
686
665
  while (queue.length > 0 && !handle.settled() && !cancelled) {
687
666
  const next = queue.shift();
688
- await runTurn(next.text, next.images);
667
+ const delivered = await runTurn(next.text, next.images, !!next.onDelivered);
668
+ if (next.onDelivered) {
669
+ if (!delivered) {
670
+ // A queued board reply is not delivery. Leave its source row for
671
+ // the existing late sweep; do not hide this failure with a later turn.
672
+ cancelled = true;
673
+ handle.kill();
674
+ break;
675
+ }
676
+ try { await next.onDelivered(); } catch { /* the source can retry its ack */ }
677
+ }
689
678
  }
690
679
  promptBusy = false;
691
680
  // A one-shot request is over when its only turn is: closing stdin ends
@@ -697,88 +686,88 @@ export function runAcpChild(opts) {
697
686
  }
698
687
  };
699
688
 
700
- const push = (text, imageUrls) => {
701
- if (handle.settled() || cancelled || typeof text !== "string" || text.trim() === "") return;
702
- queue.push({ text, images: imageUrls });
689
+ const push = (text, imageUrls, onDelivered) => {
690
+ if (handle.settled() || cancelled || typeof text !== "string" || (text.trim() === "" && (imageUrls === undefined || (Array.isArray(imageUrls) && imageUrls.length === 0)))) return;
691
+ queue.push({ text, images: imageUrls, onDelivered });
703
692
  void pump();
704
693
  };
705
694
 
706
695
  // --------------------------------------------------------- reply files
707
696
  //
708
- // THE SAME DOOR the streaming child has, behind a different knock. A
709
- // reply file is delivered as a second `session/prompt` into the same
710
- // sessionId rather than as a line on stdin, and everything else about it
711
- // is unchanged: sorted by name, consumed BEFORE it is sent (an unlink
712
- // that fails after a successful write is how a human's message arrives
713
- // twice), a `from` label wrapped around a peer's words.
714
- const watchReplies = () => {
715
- if (!replyDir || !replyPrefix) return;
716
- const watcher = handle.every(async () => {
717
- if (handle.settled()) { clearInterval(watcher); return; }
718
- try {
719
- const files = (await readdir(replyDir))
720
- .filter((f) => f.startsWith(replyPrefix) && f.endsWith(".json"))
721
- .sort();
722
- for (const file of files) {
723
- if (handle.settled()) break;
724
- const full = join(replyDir, file);
725
- let text = null;
726
- let replyImages;
727
- let fromField = null;
728
- try {
729
- const data = JSON.parse(await readFile(full, "utf8"));
730
- text = typeof data.message === "string" ? data.message : null;
731
- replyImages = data.images;
732
- fromField =
733
- typeof data.from === "string" && data.from.trim() !== "" ? data.from.trim() : null;
734
- } catch { continue; }
735
- try { promptBlocks(text ?? "", replyImages); } catch (error) {
736
- emit({ type: "result", subtype: "error_during_execution", is_error: true, session_id: sessionId, errors: [error.message] });
737
- cancelled = true;
738
- handle.kill();
739
- return;
740
- }
741
- try { await unlink(full); } catch { continue; }
742
- if (text) push(fromField ? `[message from ${fromField}] ${text}` : text, replyImages);
743
- }
744
- } catch { /* replyDir may not exist yet */ }
745
- }, replyPollMs);
746
- };
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
+ });
747
712
 
748
713
  // Answers the human gave on the canvas after ask_user had already timed
749
714
  // out. Same contract as runStreamingChild: onDelivered runs AFTER the
750
715
  // message is accepted, never before, or a ruling is marked delivered to a
751
- // session that never heard it.
752
- let answerBusy = false;
753
- const watchAnswers = () => {
754
- if (!answerPoll) return;
755
- const collect = async () => {
756
- if (handle.settled()) return;
757
- if (answerBusy) return;
758
- answerBusy = true;
759
- try {
760
- for (const answer of await answerPoll()) {
761
- if (handle.settled()) break;
762
- push(answer.text);
763
- if (answer.onDelivered) await answer.onDelivered();
764
- }
765
- } catch { /* a poll that throws is not an answer either way */ }
766
- answerBusy = false;
767
- };
768
- handle.every(collect, answerPollMs);
769
- answerPoll.subscribe?.(collect);
770
- };
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
+ });
771
728
 
772
729
  // THE STALL WATCHDOG, byte for byte the rule runStreamingChild uses -
773
730
  // armed only when the MODEL should be producing output (a turn open, no
774
731
  // tool awaiting its result) - because the events it reads are now the
775
732
  // same events. This is the whole reason the translation above bothers to
776
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
+
777
764
  const armStallWatchdog = () => {
778
765
  const watcher = handle.every(() => {
779
766
  const state = handle.state;
780
767
  if (state.settled) return;
781
- 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;
782
771
  if (armed && Date.now() - state.lastStdoutAt >= stallMs) {
783
772
  state.stalled = true;
784
773
  handle.kill();
@@ -794,11 +783,20 @@ export function runAcpChild(opts) {
794
783
  const app = sdk
795
784
  .client({ name: "pm-bridge" })
796
785
  .onNotification("session/update", ({ params }) => {
797
- if (!sessionId) sessionId = params?.sessionId ?? null;
798
- emit(lineForUpdate(params?.update, sessionId));
786
+ if (!sessionId || params?.sessionId !== sessionId) return;
787
+ const update = params?.update;
788
+ if (answerChunks && !cancelled && !handle.settled() &&
789
+ update?.sessionUpdate === "agent_message_chunk" &&
790
+ update.content?.type === "text" && typeof update.content.text === "string") {
791
+ answerChunks.push(update.content.text);
792
+ }
793
+ emit(lineForUpdate(update, sessionId));
799
794
  })
800
- .onRequest("session/request_permission", ({ params }) => {
801
- 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";
802
800
  const optionId = permissionOptionId(params?.options, allow);
803
801
  // The decision goes in the LOG, as a tool_result-shaped note beside
804
802
  // the call it answered, because a session that quietly did less
@@ -852,21 +850,25 @@ export function runAcpChild(opts) {
852
850
  // `-32000 Authentication required` from session/new and stopped there.)
853
851
  const authMethods = Array.isArray(init?.authMethods) ? init.authMethods : [];
854
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 : [];
855
856
  const params = {
856
857
  cwd,
857
858
  mcpServers: Array.isArray(acp.mcpServers) ? acp.mcpServers : [],
859
+ ...(allowedTools.length > 0 ? { _meta: { claudeCode: { options: { allowedTools } } } } : {}),
858
860
  };
859
861
  let created;
860
- // RESUME IS UNTESTED and is treated as such. `loadSession: true` was
861
- // advertised in the spike's initialize reply, but no session was ever
862
- // loaded, so this TRIES and falls back to a fresh session rather than
863
- // 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.
864
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.");
865
866
  if (resume !== "" && init?.agentCapabilities?.loadSession === true) {
866
867
  try {
867
868
  created = await connection.agent.request("session/load", { ...params, sessionId: resume });
868
869
  sessionId = resume;
869
870
  } catch (error) {
871
+ if (opts.requireResume) throw error;
870
872
  emit({
871
873
  type: "system",
872
874
  subtype: "resume_failed",
@@ -950,7 +952,7 @@ export function runAcpChild(opts) {
950
952
  await set("model", typeof acp.model === "string" ? acp.model.trim() : "");
951
953
 
952
954
  watchReplies();
953
- watchAnswers();
955
+ watchAnswersInto();
954
956
  armStallWatchdog();
955
957
  push(prompt, images);
956
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.
@@ -7,7 +7,7 @@ import { writeFileAtomic } from "./atomic.mjs";
7
7
  import { colorEnabled, dim } from "./cli-output.mjs";
8
8
  import { pickMany } from "./picker.mjs";
9
9
 
10
- export const SELECTION_FILE = ".glytch/agents.json";
10
+ export const SELECTION_FILE = ".viewable/agents.json";
11
11
  export const AGENT_KEYS = PROBE_BINS.map((b) => b.key);
12
12
 
13
13
  export function parseAgentSelection(value) {
@@ -23,8 +23,9 @@ export async function readAgentSelection(root) {
23
23
  try {
24
24
  text = await readFile(join(root, SELECTION_FILE), "utf8");
25
25
  } catch (error) {
26
- if (error.code === "ENOENT") return null;
27
- throw error;
26
+ if (error.code !== "ENOENT") throw error;
27
+ try { text = await readFile(join(root, ".glytch/agents.json"), "utf8"); }
28
+ catch (legacyError) { if (legacyError.code === "ENOENT") return null; throw legacyError; }
28
29
  }
29
30
  try {
30
31
  const saved = JSON.parse(text);
@@ -37,7 +38,7 @@ export async function readAgentSelection(root) {
37
38
 
38
39
  export async function saveAgentSelection(root, agents) {
39
40
  const selected = parseAgentSelection(agents);
40
- await mkdir(join(root, ".glytch"), { recursive: true });
41
+ await mkdir(join(root, ".viewable"), { recursive: true });
41
42
  await writeFileAtomic(join(root, SELECTION_FILE), `${JSON.stringify({ version: 1, agents: selected }, null, 2)}\n`);
42
43
  }
43
44