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.
- package/CHANGELOG.md +71 -1
- package/README.md +31 -48
- package/SPAWN.md +136 -79
- package/glytch.mjs +41 -10
- package/lib/acp.mjs +152 -150
- package/lib/admission.mjs +25 -5
- package/lib/agent-selection.mjs +5 -4
- package/lib/agents.mjs +68 -24
- package/lib/answerTag.mjs +47 -0
- package/lib/atomic.mjs +1 -16
- package/lib/auth.mjs +172 -52
- package/lib/authenticatedHttp.mjs +10 -3
- package/lib/boardside.mjs +28 -12
- package/lib/child.mjs +129 -116
- package/lib/claudeModels.mjs +168 -0
- package/lib/codex-rpc.mjs +2 -2
- package/lib/codex.mjs +50 -50
- package/lib/codexApps.mjs +17 -3
- package/lib/codexToolInputs.mjs +98 -22
- package/lib/codingChecks.mjs +8 -4
- package/lib/conversationRules.mjs +47 -7
- package/lib/detect.mjs +39 -24
- package/lib/devserver.mjs +30 -19
- package/lib/doctor.mjs +10 -8
- package/lib/folderReads.mjs +96 -0
- package/lib/followUps.mjs +170 -0
- package/lib/hosted.mjs +13 -4
- package/lib/init-connect.mjs +29 -10
- package/lib/lateResume.mjs +135 -0
- package/lib/logindaemon.mjs +129 -49
- package/lib/logs.mjs +2 -2
- package/lib/mcpjson.mjs +35 -2
- package/lib/memberPreview.mjs +22 -14
- package/lib/multiwatch.mjs +28 -41
- package/lib/pagePictures.mjs +15 -12
- package/lib/pageRoutes.mjs +5 -2
- package/lib/paths.mjs +3 -3
- package/lib/permissionAsk.mjs +344 -61
- package/lib/previewGateway.mjs +4 -3
- package/lib/procs.mjs +73 -2
- package/lib/refusal.mjs +0 -2
- package/lib/registry.mjs +7 -7
- package/lib/repomap.mjs +4 -3
- package/lib/restartPass.mjs +39 -11
- package/lib/rowsAnswers.mjs +52 -69
- package/lib/rowsEvents.mjs +20 -2
- package/lib/runner-health.mjs +29 -5
- package/lib/runner.mjs +161 -1347
- package/lib/runnerAdmission.mjs +6 -12
- package/lib/runnerApi.mjs +20 -11
- package/lib/runnerBeat.mjs +384 -0
- package/lib/runnerCompletion.mjs +5 -2
- package/lib/runnerExecute.mjs +227 -0
- package/lib/runnerGates.mjs +338 -0
- package/lib/runnerLaunch.mjs +351 -0
- package/lib/runnerLease.mjs +31 -9
- package/lib/runnerOps.mjs +217 -0
- package/lib/runnerPace.mjs +10 -6
- package/lib/runnerRecovery.mjs +457 -0
- package/lib/runnerRegister.mjs +29 -8
- package/lib/runnerSettlement.mjs +43 -16
- package/lib/runnerWorkspace.mjs +19 -4
- package/lib/spawn.mjs +0 -5
- package/lib/sync.mjs +28 -16
- package/lib/uninstall-project.mjs +12 -11
- package/lib/uninstall.mjs +32 -25
- package/lib/update.mjs +4 -4
- package/lib/{glytchFolder.mjs → viewableFolder.mjs} +22 -16
- package/lib/worktree.mjs +83 -26
- package/lib/writePolicy.mjs +90 -10
- package/package.json +2 -2
package/lib/child.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { observeClaudeModel } from "./claudeModels.mjs";
|
|
1
2
|
import { imageAttachments } from "./imageAttachments.mjs";
|
|
2
3
|
// RUNNING A CHILD PROCESS, and nothing about the board.
|
|
3
4
|
//
|
|
@@ -13,13 +14,14 @@ import { imageAttachments } from "./imageAttachments.mjs";
|
|
|
13
14
|
// runaway and stall paths testable against a fake binary.
|
|
14
15
|
|
|
15
16
|
import { spawn } from "node:child_process";
|
|
16
|
-
import { readFile, readdir, unlink } from "node:fs/promises";
|
|
17
17
|
import { createWriteStream } from "node:fs";
|
|
18
18
|
import { createGzip, constants as zlibConstants } from "node:zlib";
|
|
19
19
|
import { join } from "node:path";
|
|
20
20
|
|
|
21
21
|
import { killTree } from "./kill.mjs";
|
|
22
|
+
import { makeAnswerTracker } from "./answerTag.mjs";
|
|
22
23
|
import { RUNNER_BEAT_MS } from "./spawn.mjs";
|
|
24
|
+
import { DELIVERED, SKIP, STOP, watchAnswers, watchReplyFiles } from "./followUps.mjs";
|
|
23
25
|
import { runnableCommand } from "./windows-command.mjs";
|
|
24
26
|
|
|
25
27
|
// Defaults, all overridable by env and all bounds rather than preferences.
|
|
@@ -44,6 +46,11 @@ export const DEFAULTS = {
|
|
|
44
46
|
beatMs: RUNNER_BEAT_MS,
|
|
45
47
|
// How long a SIGTERM'd child gets to exit before SIGKILL.
|
|
46
48
|
killGraceMs: 5_000,
|
|
49
|
+
// Automatic tests, build and pictures after the agent finishes get their own
|
|
50
|
+
// cap, so they cannot hold the result and Keep changes for the rest of a
|
|
51
|
+
// 90-minute coding session. A check that hits it is "not finished", never
|
|
52
|
+
// failed. The one repair run stays on the session budget.
|
|
53
|
+
checkMaxMs: 300_000,
|
|
47
54
|
// Stall watchdog: no stdout for this long with a turn open (no result envelope
|
|
48
55
|
// since the last user message AND no tool_use waiting for its tool_result) kills
|
|
49
56
|
// the child. Default 15 minutes. Armed only when the MODEL should be producing
|
|
@@ -311,6 +318,8 @@ export function costOf(envelope) {
|
|
|
311
318
|
* settled() whether the promise has already been resolved
|
|
312
319
|
*/
|
|
313
320
|
export function attachChild(child, {
|
|
321
|
+
onProcess,
|
|
322
|
+
onSession,
|
|
314
323
|
resolve,
|
|
315
324
|
maxMs,
|
|
316
325
|
maxLogBytes = DEFAULTS.maxLogBytes,
|
|
@@ -319,6 +328,7 @@ export function attachChild(child, {
|
|
|
319
328
|
onChunk,
|
|
320
329
|
stopCheck,
|
|
321
330
|
killProcessGroup = false,
|
|
331
|
+
flushFinalLine = false,
|
|
322
332
|
// What the wall clock means for this child. The one-shot answer is "out of
|
|
323
333
|
// time"; the streaming answer is "out of time ONLY if the turn is still
|
|
324
334
|
// open", because for an idle child the wall clock is the reply window
|
|
@@ -330,6 +340,9 @@ export function attachChild(child, {
|
|
|
330
340
|
// 2026-09-06 ruling and the whole of "a finished session exits". Called
|
|
331
341
|
// once per envelope, never after the promise has settled.
|
|
332
342
|
onResult = () => {},
|
|
343
|
+
onEvent = () => {},
|
|
344
|
+
// Close protocol admission before signalling a child that may linger.
|
|
345
|
+
onKill = () => {},
|
|
333
346
|
// A `control_request` or `control_cancel_request` line arrived on stdout:
|
|
334
347
|
// the CLI is asking the host something (today, "may I use this tool?" under
|
|
335
348
|
// `--permission-prompt-tool stdio`). Only the streaming child has a stdin to
|
|
@@ -350,7 +363,11 @@ export function attachChild(child, {
|
|
|
350
363
|
// unaffected, byte for byte.
|
|
351
364
|
transcriptDir,
|
|
352
365
|
}) {
|
|
366
|
+
onProcess?.(child.pid);
|
|
367
|
+
let reportedSession;
|
|
353
368
|
const ring = makeLogRing(maxLogBytes);
|
|
369
|
+
// The answer as events stream, kept apart from the capped ring (#3634).
|
|
370
|
+
const answers = makeAnswerTracker();
|
|
354
371
|
const timers = new Set();
|
|
355
372
|
/** An interval that cannot outlive the child: settle clears every one. */
|
|
356
373
|
const every = (fn, ms) => {
|
|
@@ -455,6 +472,14 @@ export function attachChild(child, {
|
|
|
455
472
|
try {
|
|
456
473
|
const parsed = JSON.parse(line);
|
|
457
474
|
if (parsed === null || typeof parsed !== "object") continue;
|
|
475
|
+
if (!state.settled) {
|
|
476
|
+
onEvent(parsed);
|
|
477
|
+
if (typeof parsed.session_id === "string" && parsed.session_id && parsed.session_id !== reportedSession) {
|
|
478
|
+
reportedSession = parsed.session_id;
|
|
479
|
+
void Promise.resolve(onSession?.(reportedSession)).catch(() => {});
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
answers.push(parsed);
|
|
458
483
|
if (parsed.type === "assistant") state.sawAssistant = true;
|
|
459
484
|
if ((parsed.type === "control_request" || parsed.type === "control_cancel_request") && !state.settled) {
|
|
460
485
|
try { onControl(parsed); } catch { /* a listener must not take the child down */ }
|
|
@@ -536,14 +561,16 @@ export function attachChild(child, {
|
|
|
536
561
|
});
|
|
537
562
|
|
|
538
563
|
let killTimer;
|
|
564
|
+
let killing = false;
|
|
539
565
|
/** The one kill path: SIGTERM, then SIGKILL after the grace. A child that
|
|
540
566
|
* ignores SIGTERM is still billing.
|
|
541
567
|
*
|
|
542
568
|
* IT IS THE CHILD'S PID AND NOT ITS PROCESS GROUP, and since 2026-09-06
|
|
543
569
|
* that is load-bearing rather than incidental. `child.kill(sig)` signals
|
|
544
570
|
* one pid; `process.kill(-pgid, sig)` would signal everything the child
|
|
545
|
-
* started
|
|
546
|
-
*
|
|
571
|
+
* started. Recovery-tracked agents now have a private group, but ordinary
|
|
572
|
+
* callers can still share the runner's group. Normal agent shutdown
|
|
573
|
+
* remains a single-PID signal; orphan recovery verifies members separately.
|
|
547
574
|
*
|
|
548
575
|
* Ruling A that day is what makes the distinction matter: a session
|
|
549
576
|
* with the Browser switch on starts its dev server detached so the browser
|
|
@@ -564,12 +591,15 @@ export function attachChild(child, {
|
|
|
564
591
|
* killProcessGroup: runChild gives them their OWN group, with no preview
|
|
565
592
|
* intended to survive. Agent sessions never enable it. */
|
|
566
593
|
const kill = () => {
|
|
594
|
+
if (state.settled || killing) return;
|
|
595
|
+
killing = true;
|
|
596
|
+
try { onKill(); } catch { /* cleanup must not prevent termination */ }
|
|
567
597
|
const send = (force) =>
|
|
568
598
|
killTree(child.pid, { force, signal: (_pid, sig) => killProcessGroup ? process.kill(-child.pid, sig) : child.kill(sig) }).catch(() => {
|
|
569
599
|
/* a child that is already gone is not an error here */
|
|
570
600
|
});
|
|
571
|
-
send(false);
|
|
572
601
|
killTimer = setTimeout(() => send(true), killGraceMs);
|
|
602
|
+
send(false);
|
|
573
603
|
};
|
|
574
604
|
|
|
575
605
|
const wallTimer = setTimeout(() => {
|
|
@@ -581,19 +611,24 @@ export function attachChild(child, {
|
|
|
581
611
|
// The SIGTERM + grace + SIGKILL path is the same one the wall clock uses,
|
|
582
612
|
// so a stopped session ends the same way a timed-out one does.
|
|
583
613
|
if (stopCheck) {
|
|
614
|
+
let checkingStop = false;
|
|
584
615
|
const stopWatcher = every(async () => {
|
|
585
616
|
if (state.settled) { clearInterval(stopWatcher); return; }
|
|
617
|
+
if (checkingStop) return;
|
|
618
|
+
checkingStop = true;
|
|
586
619
|
try {
|
|
587
|
-
if (await stopCheck()) {
|
|
620
|
+
if (await stopCheck() && !state.settled) {
|
|
588
621
|
state.stoppedByUser = true;
|
|
589
622
|
kill();
|
|
590
623
|
clearInterval(stopWatcher);
|
|
591
624
|
}
|
|
592
625
|
} catch { /* a failed check is not a stop */ }
|
|
626
|
+
finally { checkingStop = false; }
|
|
593
627
|
}, stopPollMs);
|
|
594
628
|
}
|
|
595
629
|
|
|
596
630
|
const settle = (result) => {
|
|
631
|
+
if (state.settled) return;
|
|
597
632
|
state.settled = true;
|
|
598
633
|
clearTimeout(wallTimer);
|
|
599
634
|
clearTimeout(killTimer);
|
|
@@ -619,6 +654,7 @@ export function attachChild(child, {
|
|
|
619
654
|
// The running total - see the note on `state.totalTokens`.
|
|
620
655
|
totalTokens: state.totalTokens,
|
|
621
656
|
sawAssistant: state.sawAssistant,
|
|
657
|
+
answer: answers.answer(),
|
|
622
658
|
...extraFields(state),
|
|
623
659
|
});
|
|
624
660
|
const closed = transcriptSink?.close();
|
|
@@ -627,7 +663,10 @@ export function attachChild(child, {
|
|
|
627
663
|
};
|
|
628
664
|
|
|
629
665
|
child.on("error", (error) => settle({ ok: false, spawnError: error.message }));
|
|
630
|
-
child.on("close", (code, signal) =>
|
|
666
|
+
child.on("close", (code, signal) => {
|
|
667
|
+
if (flushFinalLine && !state.settled && lineBuf) scan("\n");
|
|
668
|
+
settle({ ok: okOf(state, code, signal), code, signal });
|
|
669
|
+
});
|
|
631
670
|
|
|
632
671
|
return {
|
|
633
672
|
state,
|
|
@@ -650,7 +689,7 @@ export function attachChild(child, {
|
|
|
650
689
|
* The wall clock is not a progress protocol and does not put a third state on
|
|
651
690
|
* the board. It is the one bound between "a session hung" and "a session
|
|
652
691
|
* billed all night". */
|
|
653
|
-
export function runChild({ bin, args, cwd, env, input, maxMs, maxLogBytes = DEFAULTS.maxLogBytes, killGraceMs = DEFAULTS.killGraceMs, onChunk, onStdout, stopCheck, stopPollMs = 2000, onSpend, platform = process.platform, transcriptDir, killProcessGroup = false }) {
|
|
692
|
+
export function runChild({ bin, args, cwd, env, input, recoveryGroup = false, onProcess, onSession, maxMs, maxLogBytes = DEFAULTS.maxLogBytes, killGraceMs = DEFAULTS.killGraceMs, onChunk, onStdout, stopCheck, stopPollMs = 2000, onSpend, platform = process.platform, transcriptDir, killProcessGroup = false, claudeResult = false }) {
|
|
654
693
|
return new Promise((resolve) => {
|
|
655
694
|
let child;
|
|
656
695
|
try {
|
|
@@ -663,7 +702,7 @@ export function runChild({ bin, args, cwd, env, input, maxMs, maxLogBytes = DEFA
|
|
|
663
702
|
// `windowsHide: true` is harmless on POSIX (detect.mjs's execProbe has
|
|
664
703
|
// carried it unconditionally since before this brief) and stops a
|
|
665
704
|
// console window flashing per session on Windows.
|
|
666
|
-
child = spawn(resolved.file, resolved.args, { cwd, env, stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"], shell: resolved.shell, windowsHide: true, detached: killProcessGroup && platform !== "win32" });
|
|
705
|
+
child = spawn(resolved.file, resolved.args, { cwd, env, stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"], shell: resolved.shell, windowsHide: true, detached: (killProcessGroup || recoveryGroup) && platform !== "win32" });
|
|
667
706
|
} catch (error) {
|
|
668
707
|
resolve({ ok: false, spawnError: error instanceof Error ? error.message : String(error), log: "" });
|
|
669
708
|
return;
|
|
@@ -675,9 +714,10 @@ export function runChild({ bin, args, cwd, env, input, maxMs, maxLogBytes = DEFA
|
|
|
675
714
|
}
|
|
676
715
|
// Everything below this line is attachChild's: the ring, the stderr tail,
|
|
677
716
|
// the envelope scan, the wall clock, the stop watcher and the settle. A
|
|
678
|
-
//
|
|
679
|
-
// whole function.
|
|
717
|
+
// Claude error envelope vetoes success; ordinary command output does not.
|
|
680
718
|
attachChild(child, {
|
|
719
|
+
onProcess,
|
|
720
|
+
onSession,
|
|
681
721
|
resolve,
|
|
682
722
|
maxMs,
|
|
683
723
|
maxLogBytes,
|
|
@@ -687,8 +727,11 @@ export function runChild({ bin, args, cwd, env, input, maxMs, maxLogBytes = DEFA
|
|
|
687
727
|
stopPollMs,
|
|
688
728
|
killProcessGroup: killProcessGroup && platform !== "win32",
|
|
689
729
|
transcriptDir,
|
|
730
|
+
flushFinalLine: claudeResult,
|
|
731
|
+
...(claudeResult ? { onEvent: observeClaudeModel(args, { ...process.env, ...env }) } : {}),
|
|
690
732
|
...(onSpend ? { onSpend } : {}),
|
|
691
|
-
okOf: (state, code) => !state.timedOut && !state.stoppedByUser && code === 0,
|
|
733
|
+
okOf: (state, code) => !state.timedOut && !state.stoppedByUser && !(claudeResult && state.resultWasError) && code === 0,
|
|
734
|
+
extraFields: (state) => claudeResult ? { finishedWithError: state.resultWasError && !state.timedOut && !state.stoppedByUser } : {},
|
|
692
735
|
});
|
|
693
736
|
if (input !== undefined) {
|
|
694
737
|
// A child that dies during startup can close the pipe before end lands.
|
|
@@ -766,7 +809,7 @@ export function runChild({ bin, args, cwd, env, input, maxMs, maxLogBytes = DEFA
|
|
|
766
809
|
* whole new resume request - the watch loop's 5s poll, the app's receipt, the
|
|
767
810
|
* worktree, and a cold `claude --resume`. That is tens of seconds and it is a
|
|
768
811
|
* design decision, not a constant. */
|
|
769
|
-
export function runStreamingChild({ bin, args, cwd, env, onSpawn, maxMs, maxLogBytes = DEFAULTS.maxLogBytes, killGraceMs = DEFAULTS.killGraceMs, stallMs = DEFAULTS.stallMs, onChunk, prompt, images, replyDir, replyPrefix, replyPollMs = 500, onUndeliveredReply, answerPoll, answerPollMs = 4000, askPermission, stopCheck, stopPollMs = 2000, onSpend, platform = process.platform, transcriptDir }) {
|
|
812
|
+
export function runStreamingChild({ bin, args, cwd, env, recoveryGroup = false, onSpawn, onProcess, onSession, maxMs, maxLogBytes = DEFAULTS.maxLogBytes, killGraceMs = DEFAULTS.killGraceMs, stallMs = DEFAULTS.stallMs, onChunk, prompt, images, replyDir, replyPrefix, replyPollMs = 500, onUndeliveredReply, answerPoll, answerPollMs = 4000, askPermission, stopCheck, stopPollMs = 2000, onSpend, platform = process.platform, transcriptDir }) {
|
|
770
813
|
return new Promise((resolve) => {
|
|
771
814
|
try { imageAttachments(images); } catch (error) { resolve({ ok: false, log: "", spawnError: error.message }); return; }
|
|
772
815
|
let child;
|
|
@@ -775,7 +818,7 @@ export function runStreamingChild({ bin, args, cwd, env, onSpawn, maxMs, maxLogB
|
|
|
775
818
|
// AND opencode per ruling 5B) - streaming is the path a persistent
|
|
776
819
|
// Claude Code session takes.
|
|
777
820
|
const resolved = runnableCommand(bin, args, { platform, env });
|
|
778
|
-
child = spawn(resolved.file, resolved.args, { cwd, env, stdio: ["pipe", "pipe", "pipe"], shell: resolved.shell, windowsHide: true });
|
|
821
|
+
child = spawn(resolved.file, resolved.args, { cwd, env, stdio: ["pipe", "pipe", "pipe"], shell: resolved.shell, windowsHide: true, detached: recoveryGroup && platform !== "win32" });
|
|
779
822
|
} catch (error) {
|
|
780
823
|
resolve({ ok: false, spawnError: error instanceof Error ? error.message : String(error), log: "" });
|
|
781
824
|
return;
|
|
@@ -788,6 +831,9 @@ export function runStreamingChild({ bin, args, cwd, env, onSpawn, maxMs, maxLogB
|
|
|
788
831
|
// uses. What is left in this function is the half a one-shot child does
|
|
789
832
|
// not have: stdin.
|
|
790
833
|
const handle = attachChild(child, {
|
|
834
|
+
onProcess,
|
|
835
|
+
onSession,
|
|
836
|
+
onEvent: observeClaudeModel(args, { ...process.env, ...env }),
|
|
791
837
|
resolve,
|
|
792
838
|
maxMs,
|
|
793
839
|
maxLogBytes,
|
|
@@ -821,6 +867,7 @@ export function runStreamingChild({ bin, args, cwd, env, onSpawn, maxMs, maxLogB
|
|
|
821
867
|
try { stdin.end(); } catch { /* the pipe is already gone */ }
|
|
822
868
|
},
|
|
823
869
|
onControl: (message) => handleControl(message),
|
|
870
|
+
onKill: () => abortPermissions(),
|
|
824
871
|
// A standing SUCCESS envelope is a finished session whatever the exit
|
|
825
872
|
// looks like - SIGTERM from the wall clock or from Stop leaves a null
|
|
826
873
|
// code, and that must not turn done work into a failure. An ERROR
|
|
@@ -887,12 +934,17 @@ export function runStreamingChild({ bin, args, cwd, env, onSpawn, maxMs, maxLogB
|
|
|
887
934
|
// waiting on a person is not a stalled run. The wall clock and Stop still
|
|
888
935
|
// apply, and settling the child aborts every wait.
|
|
889
936
|
const pendingPermissions = new Map();
|
|
890
|
-
|
|
937
|
+
let permissionsClosed = false;
|
|
938
|
+
const abortPermissions = () => {
|
|
939
|
+
permissionsClosed = true;
|
|
940
|
+
for (const controller of pendingPermissions.values()) controller.abort();
|
|
941
|
+
pendingPermissions.clear();
|
|
942
|
+
};
|
|
891
943
|
child.once("close", abortPermissions);
|
|
892
944
|
child.once("error", abortPermissions);
|
|
893
945
|
const writeControl = (response) => {
|
|
894
946
|
const stdin = child.stdin;
|
|
895
|
-
if (handle.settled() || !stdin || stdin.destroyed || !stdin.writable) return false;
|
|
947
|
+
if (permissionsClosed || handle.settled() || !stdin || stdin.destroyed || !stdin.writable) return false;
|
|
896
948
|
try {
|
|
897
949
|
stdin.write(JSON.stringify({ type: "control_response", response }) + "\n");
|
|
898
950
|
// The CLI is about to resume; its silence so far was ours.
|
|
@@ -905,6 +957,7 @@ export function runStreamingChild({ bin, args, cwd, env, onSpawn, maxMs, maxLogB
|
|
|
905
957
|
const answerControl = (requestId, payload) => writeControl({ subtype: "success", request_id: requestId, response: payload });
|
|
906
958
|
const refuseControl = (requestId, error) => writeControl({ subtype: "error", request_id: requestId, error });
|
|
907
959
|
function handleControl(message) {
|
|
960
|
+
if (permissionsClosed || handle.settled()) return;
|
|
908
961
|
if (message.type === "control_cancel_request") {
|
|
909
962
|
pendingPermissions.get(message.request_id)?.abort();
|
|
910
963
|
return;
|
|
@@ -923,10 +976,15 @@ export function runStreamingChild({ bin, args, cwd, env, onSpawn, maxMs, maxLogB
|
|
|
923
976
|
answerControl(requestId, { behavior: "deny", message: "This run cannot ask the person for permission. Carry on without it." });
|
|
924
977
|
return;
|
|
925
978
|
}
|
|
979
|
+
// A repeated ID is the same outstanding request, not a second wait.
|
|
980
|
+
if (pendingPermissions.has(requestId)) return;
|
|
926
981
|
const controller = new AbortController();
|
|
927
982
|
pendingPermissions.set(requestId, controller);
|
|
928
983
|
Promise.resolve()
|
|
929
|
-
.then(() =>
|
|
984
|
+
.then(() => {
|
|
985
|
+
if (permissionsClosed || controller.signal.aborted) return null;
|
|
986
|
+
return askPermission({ toolName: request.tool_name, input, toolUseId: request.tool_use_id, signal: controller.signal });
|
|
987
|
+
})
|
|
930
988
|
.then(
|
|
931
989
|
(verdict) => {
|
|
932
990
|
// null: the wait was cancelled (the CLI withdrew it, or the run ended).
|
|
@@ -934,119 +992,74 @@ export function runStreamingChild({ bin, args, cwd, env, onSpawn, maxMs, maxLogB
|
|
|
934
992
|
if (verdict.behavior === "allow") answerControl(requestId, { behavior: "allow", updatedInput: input });
|
|
935
993
|
else answerControl(requestId, { behavior: "deny", message: verdict.message ?? "The person said no to this. Carry on without it." });
|
|
936
994
|
},
|
|
937
|
-
() => {
|
|
995
|
+
() => {
|
|
996
|
+
if (!controller.signal.aborted) answerControl(requestId, { behavior: "deny", message: "The person could not be asked just now. Carry on without it." });
|
|
997
|
+
},
|
|
938
998
|
)
|
|
939
999
|
.finally(() => { pendingPermissions.delete(requestId); });
|
|
940
1000
|
}
|
|
941
1001
|
|
|
942
1002
|
sendToChild(userMessage(prompt, images));
|
|
943
1003
|
|
|
944
|
-
//
|
|
945
|
-
//
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
try { imageAttachments(replyImages); } catch (error) {
|
|
975
|
-
const detail = `Reference image reply was not delivered: ${error.message}`;
|
|
976
|
-
const failure = JSON.stringify({ type: "result", subtype: "error_during_execution", is_error: true, errors: [detail] }) + "\n";
|
|
977
|
-
child.stdout.emit("data", Buffer.from(failure));
|
|
978
|
-
handle.kill();
|
|
979
|
-
return;
|
|
980
|
-
}
|
|
981
|
-
// CONSUME BEFORE SENDING. The write used to come first, and an
|
|
982
|
-
// unlink that then failed (permission, or the app rewriting the
|
|
983
|
-
// file) left the reply on disk for the next 2s poll to send
|
|
984
|
-
// again - the human's message arrived at the session twice, with
|
|
985
|
-
// the failure swallowed. Deleting first means the worst case is a
|
|
986
|
-
// reply that is not delivered because the child is already gone,
|
|
987
|
-
// which is not a delivery this could have made anyway.
|
|
988
|
-
try {
|
|
989
|
-
await unlink(full);
|
|
990
|
-
} catch {
|
|
991
|
-
continue;
|
|
992
|
-
}
|
|
993
|
-
if (text) {
|
|
994
|
-
const attributed = fromField ? `[message from ${fromField}] ${text}` : text;
|
|
995
|
-
// A REPLY THAT CANNOT BE SPOKEN IS NOT A LOST REPLY (2026-09-06).
|
|
996
|
-
// Since the envelope closes stdin, this is the ordinary ending
|
|
997
|
-
// of a finished session rather than a rare race: the human typed
|
|
998
|
-
// into a session whose turn was already over. The file has been
|
|
999
|
-
// consumed above, so the words exist only here - hand them
|
|
1000
|
-
// straight back to whoever passed this callback (runner.mjs
|
|
1001
|
-
// turns them into a resume request) rather than dropping them on
|
|
1002
|
-
// the floor the way a `false` from sendToChild used to.
|
|
1003
|
-
if (!sendToChild(userMessage(attributed, replyImages)) && onUndeliveredReply) {
|
|
1004
|
-
try {
|
|
1005
|
-
await onUndeliveredReply({ text, from: fromField, images: replyImages, attributed });
|
|
1006
|
-
} catch { /* the caller's problem to log; never take the child down */ }
|
|
1007
|
-
}
|
|
1008
|
-
}
|
|
1009
|
-
}
|
|
1010
|
-
} catch { /* replyDir may not exist yet */ }
|
|
1011
|
-
}, replyPollMs);
|
|
1012
|
-
};
|
|
1013
|
-
watchReplies();
|
|
1004
|
+
// Reply files and board answers: the steps are shared by all three engines
|
|
1005
|
+
// (followUps.mjs, #4625); this engine says only how a message reaches the
|
|
1006
|
+
// child. Each reply file is a JSON object with a `message` string and may
|
|
1007
|
+
// carry images in the same data URL format as the spawn request, which the
|
|
1008
|
+
// runner sends as image content blocks on stdin.
|
|
1009
|
+
watchReplyFiles({
|
|
1010
|
+
handle, replyDir, replyPrefix, pollMs: replyPollMs,
|
|
1011
|
+
validate: (_text, images) => { imageAttachments(images); },
|
|
1012
|
+
onInvalid: (error) => {
|
|
1013
|
+
const detail = `Reference image reply was not delivered: ${error.message}`;
|
|
1014
|
+
const failure = JSON.stringify({ type: "result", subtype: "error_during_execution", is_error: true, errors: [detail] }) + "\n";
|
|
1015
|
+
child.stdout.emit("data", Buffer.from(failure));
|
|
1016
|
+
handle.kill();
|
|
1017
|
+
},
|
|
1018
|
+
send: async ({ text, from, images, attributed }) => {
|
|
1019
|
+
// A REPLY THAT CANNOT BE SPOKEN IS NOT A LOST REPLY (2026-09-06).
|
|
1020
|
+
// Since the envelope closes stdin, this is the ordinary ending
|
|
1021
|
+
// of a finished session rather than a rare race: the human typed
|
|
1022
|
+
// into a session whose turn was already over. The file has been
|
|
1023
|
+
// consumed, so the words exist only here - hand them straight back to
|
|
1024
|
+
// whoever passed this callback (runner.mjs turns them into a resume
|
|
1025
|
+
// request) rather than dropping them on the floor the way a `false`
|
|
1026
|
+
// from sendToChild used to.
|
|
1027
|
+
if (!sendToChild(userMessage(attributed, images)) && onUndeliveredReply) {
|
|
1028
|
+
try {
|
|
1029
|
+
await onUndeliveredReply({ text, from, images, attributed });
|
|
1030
|
+
} catch { /* the caller's problem to log; never take the child down */ }
|
|
1031
|
+
}
|
|
1032
|
+
},
|
|
1033
|
+
});
|
|
1014
1034
|
|
|
1015
1035
|
// THE SAME DOOR, for answers the human gave on the canvas after ask_user
|
|
1016
1036
|
// had already returned pending. `answerPoll` hands back ready-made
|
|
1017
|
-
// messages so this function stays free of board vocabulary
|
|
1018
|
-
// that something upstream may have words for the child.
|
|
1037
|
+
// messages so this function stays free of board vocabulary.
|
|
1019
1038
|
//
|
|
1020
1039
|
// Delivery is confirmed AFTER the write, not before: onDelivered is what
|
|
1021
1040
|
// records that the session has been told, and marking first would lose a
|
|
1022
1041
|
// ruling for good if the child settled in between.
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
//
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
answerBusy = false;
|
|
1045
|
-
};
|
|
1046
|
-
handle.every(collect, answerPollMs);
|
|
1047
|
-
answerPoll.subscribe?.(collect);
|
|
1048
|
-
};
|
|
1049
|
-
watchAnswers();
|
|
1042
|
+
watchAnswers({
|
|
1043
|
+
handle, answerPoll, pollMs: answerPollMs,
|
|
1044
|
+
send: async (answer) => {
|
|
1045
|
+
// `answer.images` (item 6, brief 30 Move 2b): a message's images,
|
|
1046
|
+
// delivered through the SAME content-block channel a reply file's
|
|
1047
|
+
// images already use (`userMessage`).
|
|
1048
|
+
let payload;
|
|
1049
|
+
try { payload = userMessage(answer.text, answer.images); }
|
|
1050
|
+
catch (error) {
|
|
1051
|
+
// Omit only this invalid reply, leaving it unacknowledged for
|
|
1052
|
+
// late recovery. Other rows in this batch still need delivery.
|
|
1053
|
+
const failure = JSON.stringify({ type: "system", subtype: "error",
|
|
1054
|
+
message: `Reference image reply was not delivered: ${error.message}` }) + "\n";
|
|
1055
|
+
child.stdout.emit("data", Buffer.from(failure));
|
|
1056
|
+
return SKIP;
|
|
1057
|
+
}
|
|
1058
|
+
// Only record delivery if the pipe actually took it, or a ruling
|
|
1059
|
+
// would be marked delivered to a child that never heard it.
|
|
1060
|
+
return sendToChild(payload) ? DELIVERED : STOP;
|
|
1061
|
+
},
|
|
1062
|
+
});
|
|
1050
1063
|
|
|
1051
1064
|
// STALL WATCHDOG: no stdout for stallMs while the MODEL should be producing
|
|
1052
1065
|
// output. Armed when a turn is open (no result envelope since the last user
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
// Version evidence for Claude short names (#3556). This is computer metadata,
|
|
2
|
+
// never a board run. Attempts survive reconnects, including failed checks.
|
|
3
|
+
import { spawn } from "node:child_process";
|
|
4
|
+
import { readFileSync } from "node:fs";
|
|
5
|
+
import { mkdir, readFile, stat, unlink, writeFile } from "node:fs/promises";
|
|
6
|
+
import { createHash } from "node:crypto";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
import { viewableHome } from "./registry.mjs";
|
|
9
|
+
import { writeFileAtomic } from "./atomic.mjs";
|
|
10
|
+
import { runnableCommand } from "./windows-command.mjs";
|
|
11
|
+
import { killTree } from "./kill.mjs";
|
|
12
|
+
|
|
13
|
+
export const CLAUDE_MODEL_NAMES = ["fable", "opus", "sonnet", "haiku"];
|
|
14
|
+
// Only the family named by the short name counts: `opus` accepts claude-opus-5-5,
|
|
15
|
+
// never claude-haiku-5-5 (a helper model a run may report first).
|
|
16
|
+
const exactModel = (name, model) => typeof model === "string" && model.toLowerCase().startsWith(`claude-${name}-`) && /^claude-[a-z0-9-]+-\d+(?:-\d+)*$/i.test(model);
|
|
17
|
+
// A reservation younger than this, held by a live process, is a check still running.
|
|
18
|
+
const CHECK_STALE_MS = 60_000;
|
|
19
|
+
const cacheDir = (version, env) => join(viewableHome(env), "claude-models", createHash("sha256").update(`${env.CLAUDE_CONFIG_DIR ?? ""}\n${version}`).digest("hex"));
|
|
20
|
+
const read = (file) => { try { return JSON.parse(readFileSync(file, "utf8")); } catch { return null; } };
|
|
21
|
+
|
|
22
|
+
export function readClaudeModels(version, env = process.env) {
|
|
23
|
+
if (!version) return {};
|
|
24
|
+
const dir = cacheDir(version, env);
|
|
25
|
+
return Object.fromEntries(CLAUDE_MODEL_NAMES.flatMap((name) => {
|
|
26
|
+
const model = read(join(dir, `${name}.observed.json`)) ?? read(join(dir, `${name}.probe.json`));
|
|
27
|
+
return exactModel(name, model) ? [[name, model]] : [];
|
|
28
|
+
}));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Stop on system/init, before the answer. Older CLIs that omit its model
|
|
32
|
+
* can supply an assistant model instead. No tools, hooks, MCP or history. */
|
|
33
|
+
export function probeClaudeModel(bin, name, { env = process.env, timeoutMs = 15_000, cwd, platform = process.platform } = {}) {
|
|
34
|
+
return new Promise((resolve) => {
|
|
35
|
+
let child, timer, forceTimer, model, buffer = "", stopping = false;
|
|
36
|
+
const stop = () => {
|
|
37
|
+
if (stopping) return;
|
|
38
|
+
stopping = true;
|
|
39
|
+
void killTree(child.pid, { platform, signal: (_pid, sig) => child.kill(sig) }).catch(() => {});
|
|
40
|
+
forceTimer = setTimeout(() => { void killTree(child.pid, { platform, force: true, signal: (_pid, sig) => child.kill(sig) }).catch(() => {}); }, 250);
|
|
41
|
+
};
|
|
42
|
+
const finish = () => { clearTimeout(timer); clearTimeout(forceTimer); resolve(model); };
|
|
43
|
+
try {
|
|
44
|
+
const args = ["-p", "Reply OK.", "--model", name, "--output-format", "stream-json", "--verbose", "--max-turns", "1", "--tools", "", "--strict-mcp-config", "--mcp-config", '{"mcpServers":{}}', "--setting-sources", "", "--settings", '{"disableAllHooks":true}', "--disable-slash-commands", "--no-chrome", "--no-session-persistence", "--system-prompt", "Reply OK."];
|
|
45
|
+
const probeEnv = { ...env, CLAUDE_CODE_SAFE_MODE: "1" };
|
|
46
|
+
// A connection may be started from inside Claude Code. This isolated
|
|
47
|
+
// metadata check is not a nested interactive coding session.
|
|
48
|
+
delete probeEnv.CLAUDECODE;
|
|
49
|
+
const command = runnableCommand(bin, args, { env: probeEnv, platform });
|
|
50
|
+
child = spawn(command.file, command.args, { env: probeEnv, cwd, shell: false, windowsHide: true, stdio: ["ignore", "pipe", "ignore"] });
|
|
51
|
+
timer = setTimeout(stop, timeoutMs);
|
|
52
|
+
child.stdout.setEncoding("utf8");
|
|
53
|
+
child.stdout.on("data", (chunk) => {
|
|
54
|
+
buffer += chunk;
|
|
55
|
+
if (buffer.length > 1_000_000) { buffer = ""; stop(); return; }
|
|
56
|
+
const lines = buffer.split("\n"); buffer = lines.pop();
|
|
57
|
+
for (const line of lines) {
|
|
58
|
+
let event; try { event = JSON.parse(line); } catch { continue; }
|
|
59
|
+
if (!event || event.parent_tool_use_id) continue;
|
|
60
|
+
const candidate = event.type === "system" && event.subtype === "init" ? event.model : event.type === "assistant" ? event.message?.model : undefined;
|
|
61
|
+
if (!stopping && exactModel(name, candidate)) { model = candidate; stop(); }
|
|
62
|
+
}
|
|
63
|
+
});
|
|
64
|
+
child.once("error", finish);
|
|
65
|
+
child.once("close", finish);
|
|
66
|
+
} catch { finish(); }
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const alive = (pid) => {
|
|
71
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
72
|
+
try { process.kill(pid, 0); return true; } catch (error) { return error.code === "EPERM"; }
|
|
73
|
+
};
|
|
74
|
+
const exists = (file) => stat(file).then(() => true, () => false);
|
|
75
|
+
|
|
76
|
+
/** True when this process now owns the check for `name`. A finished check
|
|
77
|
+
* (result or not) is never repeated for this CLI version. A reservation with no
|
|
78
|
+
* finish mark is a check that was cut off (daemon killed): it is taken over
|
|
79
|
+
* unless a live process wrote it a moment ago. */
|
|
80
|
+
async function reserve(dir, name) {
|
|
81
|
+
if (await exists(join(dir, `${name}.done`)) || await exists(join(dir, `${name}.probe.json`))) return false;
|
|
82
|
+
const file = join(dir, `${name}.attempted`);
|
|
83
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
84
|
+
try { await writeFile(file, String(process.pid), { flag: "wx" }); return true; }
|
|
85
|
+
catch (error) { if (error.code !== "EEXIST") throw error; }
|
|
86
|
+
let pid, age = Infinity;
|
|
87
|
+
try { pid = Number.parseInt(await readFile(file, "utf8"), 10); age = Date.now() - (await stat(file)).mtimeMs; } catch { /* gone: try again */ }
|
|
88
|
+
// The file exists a moment before its pid is written (create, then write):
|
|
89
|
+
// an empty one that is young is a check just starting, not one cut off.
|
|
90
|
+
if ((alive(pid) || !Number.isInteger(pid)) && age < CHECK_STALE_MS) return false;
|
|
91
|
+
await unlink(file).catch(() => {});
|
|
92
|
+
}
|
|
93
|
+
return false;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** `claude auth status` makes no model request; it prints the login as JSON.
|
|
97
|
+
* Undefined when the command is missing (an older Claude Code), fails or
|
|
98
|
+
* prints something else. */
|
|
99
|
+
export function claudeAuthStatus(bin, { env = process.env, platform = process.platform, timeoutMs = 10_000 } = {}) {
|
|
100
|
+
return new Promise((resolve) => {
|
|
101
|
+
let out = "", child, timer;
|
|
102
|
+
const finish = (value) => { clearTimeout(timer); resolve(value); };
|
|
103
|
+
try {
|
|
104
|
+
const command = runnableCommand(bin, ["auth", "status"], { env, platform });
|
|
105
|
+
child = spawn(command.file, command.args, { env, shell: false, windowsHide: true, stdio: ["ignore", "pipe", "ignore"] });
|
|
106
|
+
timer = setTimeout(() => { child.kill(); finish(undefined); }, timeoutMs);
|
|
107
|
+
child.stdout.setEncoding("utf8");
|
|
108
|
+
child.stdout.on("data", (chunk) => { if (out.length < 100_000) out += chunk; });
|
|
109
|
+
child.once("error", () => finish(undefined));
|
|
110
|
+
child.once("close", (code) => { try { const status = JSON.parse(out); finish(code === 0 && status && typeof status === "object" ? status : undefined); } catch { finish(undefined); } });
|
|
111
|
+
} catch { finish(undefined); }
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
/** Only a Claude subscription login may be checked. An answer that says
|
|
115
|
+
* otherwise (Console API login, a cloud provider, logged out) stops the check;
|
|
116
|
+
* no answer keeps the old behaviour so older Claude Code still gets one. */
|
|
117
|
+
const notSubscription = (status) => status !== undefined &&
|
|
118
|
+
!(status.loggedIn === true && status.authMethod === "claude.ai" && (status.apiProvider ?? "firstParty") === "firstParty");
|
|
119
|
+
|
|
120
|
+
export async function discoverClaudeModels(agent, { bin, env = process.env, probe = probeClaudeModel, authStatus = claudeAuthStatus, log = () => {} } = {}) {
|
|
121
|
+
if (!agent?.found || !agent.version || agent.loggedIn !== true) return {};
|
|
122
|
+
// This permission is for the Claude subscription, not API-key/provider spend.
|
|
123
|
+
// Any nonempty provider switch is unsafe to probe, regardless of spelling.
|
|
124
|
+
if (env.ANTHROPIC_API_KEY || env.ANTHROPIC_AUTH_TOKEN || env.ANTHROPIC_BASE_URL ||
|
|
125
|
+
[env.CLAUDE_CODE_USE_BEDROCK, env.CLAUDE_CODE_USE_VERTEX, env.CLAUDE_CODE_USE_FOUNDRY,
|
|
126
|
+
env.CLAUDE_CODE_USE_ANTHROPIC_AWS, env.CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD, env.CLAUDE_CODE_USE_MANTLE].some(Boolean)) return {};
|
|
127
|
+
const dir = cacheDir(agent.version, env);
|
|
128
|
+
let status, asked = false;
|
|
129
|
+
try {
|
|
130
|
+
await mkdir(dir, { recursive: true });
|
|
131
|
+
for (const name of CLAUDE_MODEL_NAMES) {
|
|
132
|
+
// Exclusive creation reserves a single request even with two connecting
|
|
133
|
+
// processes. A check that ran and found nothing stays done until the CLI
|
|
134
|
+
// changes; one cut off mid-way (no done mark) is tried again.
|
|
135
|
+
if (!await reserve(dir, name)) continue;
|
|
136
|
+
// Ask once, before the first request.
|
|
137
|
+
if (!asked) { asked = true; status = await authStatus(bin, { env }).catch(() => undefined); }
|
|
138
|
+
if (notSubscription(status)) { await unlink(join(dir, `${name}.attempted`)).catch(() => {}); break; }
|
|
139
|
+
let model;
|
|
140
|
+
try { model = await probe(bin, name, { env, cwd: dir }); } catch { /* no result: done below */ }
|
|
141
|
+
if (exactModel(name, model)) await writeFileAtomic(join(dir, `${name}.probe.json`), JSON.stringify(model));
|
|
142
|
+
else log(`Claude model check failed: ${name}`);
|
|
143
|
+
await writeFile(join(dir, `${name}.done`), "").catch(() => {});
|
|
144
|
+
}
|
|
145
|
+
} catch (error) { log(`Claude model check failed: ${error.message}`); }
|
|
146
|
+
return readClaudeModels(agent.version, env);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Existing child parser calls this for actual runs. Init supplies the CLI
|
|
150
|
+
* version; only top-level assistant evidence supersedes a connection check. */
|
|
151
|
+
export function observeClaudeModel(args, env = process.env) {
|
|
152
|
+
const index = args.indexOf("--model");
|
|
153
|
+
const name = index < 0 ? undefined : args[index + 1];
|
|
154
|
+
let version, last, writes = Promise.resolve();
|
|
155
|
+
return (event) => {
|
|
156
|
+
if (!CLAUDE_MODEL_NAMES.includes(name)) return writes;
|
|
157
|
+
if (event.type === "system" && event.subtype === "init" && typeof event.claude_code_version === "string") version = event.claude_code_version;
|
|
158
|
+
const model = event.type === "assistant" && !event.parent_tool_use_id ? event.message?.model : undefined;
|
|
159
|
+
if (!version || !exactModel(name, model) || model === last) return writes;
|
|
160
|
+
last = model;
|
|
161
|
+
const dir = cacheDir(version, env);
|
|
162
|
+
writes = writes.then(async () => {
|
|
163
|
+
await mkdir(dir, { recursive: true });
|
|
164
|
+
await writeFileAtomic(join(dir, `${name}.observed.json`), JSON.stringify(model));
|
|
165
|
+
}).catch((error) => { process.stderr.write(`Claude model cache failed: ${error.message}\n`); });
|
|
166
|
+
return writes;
|
|
167
|
+
};
|
|
168
|
+
}
|