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.
- package/CHANGELOG.md +47 -0
- package/README.md +2 -2
- package/SPAWN.md +107 -53
- package/glytch.mjs +41 -10
- package/lib/acp.mjs +110 -148
- package/lib/admission.mjs +25 -5
- package/lib/agents.mjs +59 -16
- package/lib/answerTag.mjs +47 -0
- package/lib/atomic.mjs +1 -16
- package/lib/auth.mjs +25 -9
- package/lib/boardside.mjs +28 -12
- package/lib/child.mjs +89 -116
- package/lib/claudeModels.mjs +168 -0
- package/lib/codex-rpc.mjs +2 -2
- package/lib/codex.mjs +43 -63
- package/lib/codexApps.mjs +5 -3
- package/lib/codexToolInputs.mjs +98 -22
- package/lib/codingChecks.mjs +8 -4
- package/lib/conversationRules.mjs +46 -6
- package/lib/detect.mjs +14 -23
- package/lib/devserver.mjs +6 -6
- package/lib/doctor.mjs +4 -2
- 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 +113 -33
- package/lib/mcpjson.mjs +35 -2
- package/lib/multiwatch.mjs +25 -38
- package/lib/pagePictures.mjs +14 -11
- package/lib/paths.mjs +0 -1
- package/lib/permissionAsk.mjs +341 -58
- package/lib/procs.mjs +73 -2
- package/lib/refusal.mjs +0 -2
- package/lib/restartPass.mjs +39 -11
- package/lib/rowsAnswers.mjs +18 -34
- package/lib/rowsEvents.mjs +20 -2
- package/lib/runner-health.mjs +26 -2
- package/lib/runner.mjs +106 -1363
- 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 +28 -7
- package/lib/runnerSettlement.mjs +29 -9
- package/lib/spawn.mjs +0 -5
- package/lib/sync.mjs +26 -14
- package/lib/viewableFolder.mjs +8 -2
- package/lib/worktree.mjs +66 -13
- package/lib/writePolicy.mjs +90 -10
- package/package.json +1 -1
|
@@ -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
|
+
}
|
package/lib/codex-rpc.mjs
CHANGED
|
@@ -4,9 +4,9 @@
|
|
|
4
4
|
import { spawn } from "node:child_process";
|
|
5
5
|
import { runnableCommand } from "./windows-command.mjs";
|
|
6
6
|
|
|
7
|
-
export function startCodex({ bin = "codex", args = ["app-server"], cwd, env = process.env, platform = process.platform } = {}) {
|
|
7
|
+
export function startCodex({ bin = "codex", args = ["app-server"], cwd, env = process.env, platform = process.platform, recoveryGroup = false } = {}) {
|
|
8
8
|
const command = runnableCommand(bin, args, { platform, env });
|
|
9
|
-
return spawn(command.file, command.args, { cwd, env, shell: command.shell, windowsHide: true, stdio: ["pipe", "pipe", "pipe"] });
|
|
9
|
+
return spawn(command.file, command.args, { cwd, env, shell: command.shell, windowsHide: true, detached: recoveryGroup && platform !== "win32", stdio: ["pipe", "pipe", "pipe"] });
|
|
10
10
|
}
|
|
11
11
|
|
|
12
12
|
export function codexRpc(child, { onNotification = () => {}, onRequest = () => { throw new Error("This client cannot answer this request; use the board ask_user tool."); }, timeoutMs = 15_000 } = {}) {
|
package/lib/codex.mjs
CHANGED
|
@@ -2,10 +2,10 @@ import { writeRisk, riskReason } from "./writePolicy.mjs";
|
|
|
2
2
|
// Codex's native app-server protocol, translated to the board's session log.
|
|
3
3
|
// No SDK or API key is needed: this uses the user's installed, signed-in CLI.
|
|
4
4
|
import { PassThrough } from "node:stream";
|
|
5
|
-
import {
|
|
6
|
-
import { join } from "node:path";
|
|
5
|
+
import { writeFile } from "node:fs/promises";
|
|
7
6
|
import { attachChild, DEFAULTS } from "./child.mjs";
|
|
8
7
|
import { imageAttachments } from "./imageAttachments.mjs";
|
|
8
|
+
import { DELIVERED, SKIP, watchAnswers, watchReplyFiles } from "./followUps.mjs";
|
|
9
9
|
import { CODEX_TOOL_TIMEOUT_SEC } from "./mcpjson.mjs";
|
|
10
10
|
import { codexRpc, startCodex } from "./codex-rpc.mjs";
|
|
11
11
|
import { planWindowInfoMessage, readPlanWindow } from "./codexPlanWindow.mjs";
|
|
@@ -111,7 +111,7 @@ const ASKABLE_APPROVALS = new Set([
|
|
|
111
111
|
]);
|
|
112
112
|
function approvalAsAsk(method, params = {}) {
|
|
113
113
|
if (method === "item/commandExecution/requestApproval") {
|
|
114
|
-
return { toolName: "Bash", input: { command: String(params.command ?? ""), ...(params.reason ? { description: String(params.reason) } : {}) } };
|
|
114
|
+
return { toolName: "Bash", input: { command: String(params.command ?? ""), ...(typeof params.cwd === "string" && params.cwd !== "" ? { cwd: params.cwd } : {}), ...(params.reason ? { description: String(params.reason) } : {}) } };
|
|
115
115
|
}
|
|
116
116
|
if (method === "item/fileChange/requestApproval") {
|
|
117
117
|
return { toolName: "Edit", input: { file_path: String(params.grantRoot ?? ""), ...(params.reason ? { description: String(params.reason) } : {}) } };
|
|
@@ -308,8 +308,8 @@ function runCodexAttempt(opts, apps) {
|
|
|
308
308
|
let turnId = null;
|
|
309
309
|
let modelCalls = 0;
|
|
310
310
|
let ending = false;
|
|
311
|
-
let
|
|
312
|
-
let
|
|
311
|
+
let replyWatch;
|
|
312
|
+
let answerWatch;
|
|
313
313
|
let ownWordsPending = 0;
|
|
314
314
|
let finishError;
|
|
315
315
|
let closedInput = false;
|
|
@@ -343,6 +343,7 @@ function runCodexAttempt(opts, apps) {
|
|
|
343
343
|
kill: (signal) => child.kill(signal), on(event, fn) { child.on(event, fn); return facade; } };
|
|
344
344
|
const handle = attachChild(facade, {
|
|
345
345
|
...opts,
|
|
346
|
+
onSession: undefined, // The native thread/start path awaits this callback before prompting.
|
|
346
347
|
resolve: (outcome) => { clearTimeout(finishTimer); abortQuestions(); rpc?.close(); resolve({ ...outcome, ...(appsRetry ? { appsRetry } : {}) }); },
|
|
347
348
|
// Latch admission closed BEFORE SIGTERM. A still-running child may
|
|
348
349
|
// issue entirely new requests during the independent kill grace.
|
|
@@ -368,7 +369,7 @@ function runCodexAttempt(opts, apps) {
|
|
|
368
369
|
// Drain the delivery acknowledgement before closing, so a late reply is
|
|
369
370
|
// restored before the runner writes its sidecar and promotes late files.
|
|
370
371
|
const closeTurn = () => {
|
|
371
|
-
if (!ending ||
|
|
372
|
+
if (!ending || replyWatch?.busy() || answerWatch?.busy() || ownWordsPending !== 0 || closedInput || handle.settled()) return;
|
|
372
373
|
closedInput = true;
|
|
373
374
|
const error = finishError;
|
|
374
375
|
if (!appsRetry) emit({ type: "result", subtype: error ? "error_during_execution" : "success", is_error: !!error,
|
|
@@ -578,65 +579,44 @@ function runCodexAttempt(opts, apps) {
|
|
|
578
579
|
emit({ type: "user", message: { role: "user", content: [{ type: "text", text }] } });
|
|
579
580
|
return true;
|
|
580
581
|
};
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
//
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
} catch (error) {
|
|
603
|
-
emit({ type: "system", subtype: "error", message: `Reply delivery failed: ${error.message}` });
|
|
604
|
-
// Only a definite active-turn rejection is safe to promote.
|
|
605
|
-
if (/turn.*(not found|not active|mismatch|completed)|no active turn/i.test(error.message)) {
|
|
606
|
-
await writeFile(path, JSON.stringify(reply), { flag: "wx" });
|
|
607
|
-
} else {
|
|
608
|
-
finish(`Codex could not confirm delivery of your reply: ${error.message}`);
|
|
609
|
-
}
|
|
610
|
-
}
|
|
611
|
-
}
|
|
612
|
-
} catch { /* directory may disappear while disconnecting */ }
|
|
613
|
-
finally { replyBusy = false; closeTurn(); }
|
|
614
|
-
}, opts.replyPollMs ?? 2000);
|
|
615
|
-
const collectAnswers = async () => {
|
|
616
|
-
if (!opts.answerPoll) return;
|
|
617
|
-
if (answerBusy || ending || !turnId || stopping || handle.settled()) return;
|
|
618
|
-
answerBusy = true;
|
|
619
|
-
try {
|
|
620
|
-
for (const answer of await opts.answerPoll()) {
|
|
621
|
-
if (ending || stopping || handle.settled()) break;
|
|
622
|
-
try {
|
|
623
|
-
if (await deliver(answer.text, answer.images)) await answer.onDelivered?.();
|
|
624
|
-
} catch {
|
|
625
|
-
// Keep the board row unacknowledged for the existing late sweep.
|
|
626
|
-
// Never echo adapter errors, which can contain credentials.
|
|
627
|
-
finishError ??= "Codex could not confirm delivery of your board reply.";
|
|
628
|
-
finish(finishError);
|
|
629
|
-
break;
|
|
582
|
+
// Reply files and board answers: shared with the other two engines
|
|
583
|
+
// (followUps.mjs, #4625). This engine says only how a message reaches the
|
|
584
|
+
// active turn (`deliver`) and what a failure means for the run.
|
|
585
|
+
const turnOpen = () => Boolean(turnId) && !ending && !stopping;
|
|
586
|
+
replyWatch = watchReplyFiles({
|
|
587
|
+
handle, replyDir: opts.replyDir, replyPrefix: opts.replyPrefix, pollMs: opts.replyPollMs ?? 2000,
|
|
588
|
+
active: turnOpen,
|
|
589
|
+
validate: (_text, images) => { imageAttachments(images); },
|
|
590
|
+
onInvalid: (error) => finish(`Reference image reply was not delivered: ${error.message}`),
|
|
591
|
+
// The file is consumed before sending, matching the existing runner. A
|
|
592
|
+
// rejected steer becomes a resumable reply; never replay blindly.
|
|
593
|
+
send: async ({ attributed, data: reply, path }) => {
|
|
594
|
+
try {
|
|
595
|
+
if (!(await deliver(attributed, reply.images))) await writeFile(path, JSON.stringify(reply), { flag: "wx" });
|
|
596
|
+
} catch (error) {
|
|
597
|
+
emit({ type: "system", subtype: "error", message: `Reply delivery failed: ${error.message}` });
|
|
598
|
+
// Only a definite active-turn rejection is safe to promote.
|
|
599
|
+
if (/turn.*(not found|not active|mismatch|completed)|no active turn/i.test(error.message)) {
|
|
600
|
+
await writeFile(path, JSON.stringify(reply), { flag: "wx" });
|
|
601
|
+
} else {
|
|
602
|
+
finish(`Codex could not confirm delivery of your reply: ${error.message}`);
|
|
630
603
|
}
|
|
631
604
|
}
|
|
632
|
-
}
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
605
|
+
},
|
|
606
|
+
onPassEnd: closeTurn,
|
|
607
|
+
});
|
|
608
|
+
answerWatch = watchAnswers({
|
|
609
|
+
handle, answerPoll: opts.answerPoll, pollMs: opts.answerPollMs ?? 4000,
|
|
610
|
+
active: turnOpen,
|
|
611
|
+
send: async (answer) => (await deliver(answer.text, answer.images)) ? DELIVERED : SKIP,
|
|
612
|
+
// Keep the board row unacknowledged for the existing late sweep.
|
|
613
|
+
// Never echo adapter errors, which can contain credentials.
|
|
614
|
+
onSendError: () => {
|
|
615
|
+
finishError ??= "Codex could not confirm delivery of your board reply.";
|
|
616
|
+
finish(finishError);
|
|
617
|
+
},
|
|
618
|
+
onPassEnd: closeTurn,
|
|
619
|
+
});
|
|
640
620
|
const stallMs = opts.stallMs ?? DEFAULTS.stallMs;
|
|
641
621
|
handle.every(() => {
|
|
642
622
|
if (!ending && waitingOnPerson === 0 && handle.state.openToolUses.size === 0 && Date.now() - handle.state.lastStdoutAt >= stallMs) {
|
package/lib/codexApps.mjs
CHANGED
|
@@ -15,15 +15,17 @@ const exposed = (status) => Object.keys(status.tools).length || status.resources
|
|
|
15
15
|
// each signal. A blocked preflight must neither leak a child nor hang OFF or
|
|
16
16
|
// drafts forever. No process-group kill: these children share our group.
|
|
17
17
|
async function stopPreflight(child, gone, killGraceMs) {
|
|
18
|
-
const wait = async () => {
|
|
18
|
+
const wait = async (done, timeoutMs) => {
|
|
19
19
|
let timer;
|
|
20
|
-
try { return await Promise.race([
|
|
20
|
+
try { return await Promise.race([done.then(() => true), new Promise((resolve) => { timer = setTimeout(() => resolve(false), timeoutMs); })]); }
|
|
21
21
|
finally { clearTimeout(timer); }
|
|
22
22
|
};
|
|
23
23
|
if (child.exitCode !== null || child.signalCode !== null) return;
|
|
24
|
+
// Exit confirms the reap; close can wait for pipes held by descendants.
|
|
25
|
+
const exited = new Promise((resolve) => child.once("exit", resolve));
|
|
24
26
|
for (const force of [false, true]) {
|
|
25
27
|
await killTree(child.pid, { force, signal: (_pid, signal) => child.kill(signal) }).catch(() => {});
|
|
26
|
-
if (await wait()) return;
|
|
28
|
+
if (await wait(force ? exited : gone, force ? 5000 : killGraceMs)) return;
|
|
27
29
|
}
|
|
28
30
|
child.stdin.destroy(); child.stdout.destroy(); child.stderr.destroy(); child.unref();
|
|
29
31
|
throw unreadable();
|
package/lib/codexToolInputs.mjs
CHANGED
|
@@ -5,12 +5,25 @@
|
|
|
5
5
|
//
|
|
6
6
|
// Text is shown by an ALLOW rule, not a list of things to block: a string is
|
|
7
7
|
// shown only when it reads as plain text: at most 80 characters, made only of
|
|
8
|
-
// letters, digits, spaces
|
|
9
|
-
//
|
|
10
|
-
//
|
|
11
|
-
//
|
|
12
|
-
//
|
|
13
|
-
//
|
|
8
|
+
// letters, digits, spaces, quote marks (' " and curly ones), dashes (- and the
|
|
9
|
+
// long and medium dash) and . , _ / ( ) # + @ ! ? $ € £,
|
|
10
|
+
// with no run of 4 or more digits, no credential word (pass, pin, token, key…
|
|
11
|
+
// as a whole word or the start of one; "session" is not one, #4251), and neither secret-shaped nor
|
|
12
|
+
// opaque. A longer text shows its first words (up to 80 characters, ending at
|
|
13
|
+
// a word) with "…", and only that start is tested. Anything else (a tab, a
|
|
14
|
+
// line break, any other punctuation) reads "hidden, N characters". A body of
|
|
15
|
+
// any format (JSON, form, query, XML, multipart, comma or tab separated)
|
|
16
|
+
// therefore never shows, whatever it names: its colons, braces, equals signs
|
|
17
|
+
// and credential words hide it, with or without quote marks. A quote mark
|
|
18
|
+
// alone says nothing about a secret (#4060), and neither does a long dash
|
|
19
|
+
// (models write it often) (#4139).
|
|
20
|
+
// The text a ticket or a page is written in (title, description, subject,
|
|
21
|
+
// comment, page text: PROSE_FIELDS below) is read more kindly (#4363): line
|
|
22
|
+
// breaks read as spaces, and any punctuation or symbol shows (a colon, an
|
|
23
|
+
// ampersand, a bracket, an arrow, a percent sign), except = { } and a backslash, which
|
|
24
|
+
// carry form, JSON and escaped data. A year (1900 to 2099) is not a code.
|
|
25
|
+
// Every other test is the same: a credential word, a labelled or token-shaped
|
|
26
|
+
// value, an opaque run or a long run of digits still hides.
|
|
14
27
|
// Booleans and null show as themselves; a number shows when it has at most
|
|
15
28
|
// 3 digits before the point; nested values show as a count; an argument
|
|
16
29
|
// named like a credential reads "hidden".
|
|
@@ -34,27 +47,46 @@ export const secretLike = (value) => labelledSecret.test(value) || tokenShaped.t
|
|
|
34
47
|
// everything but letters stripped ("OTPCode" -> "otpcode", "passcode,482913"
|
|
35
48
|
// -> "passcode"), then tested for these parts anywhere, so one-word names,
|
|
36
49
|
// acronyms and run-together text are caught without splitting words. An
|
|
37
|
-
// argument named this way is hidden whatever its value
|
|
38
|
-
//
|
|
39
|
-
// "
|
|
50
|
+
// argument named this way is hidden whatever its value (a text value is read
|
|
51
|
+
// by words instead, see LONG_WORD below). Over-matching of names ("author",
|
|
52
|
+
// "shipping") only hides a value.
|
|
40
53
|
const SECRET_PART = /pass|pin|otp|token|key|secret|auth|cookie|session|credential|signature|cvv|cvc|private|mfa|totp|pwd|cardnumber|onetime|verification|bearer|basic/;
|
|
41
54
|
const nameLetters = (name) => name.toLowerCase().replace(/[^a-z]/g, "");
|
|
42
|
-
const mentionsSecret = (text) => SECRET_PART.test(nameLetters(text));
|
|
55
|
+
export const mentionsSecret = (text) => SECRET_PART.test(nameLetters(text));
|
|
56
|
+
// A TEXT value is read by words, not by short parts inside words: "Guided
|
|
57
|
+
// first session", "shipping", "keyboard" and "compass" are plain titles
|
|
58
|
+
// (#4251). Per run of letters in the original case: a LONG credential word
|
|
59
|
+
// anywhere in it hides the value (accessToken, mypassword, privateKey,
|
|
60
|
+
// sessionId, authorization, pinCode); a SHORT one (pass, pin, key, auth,
|
|
61
|
+
// cookie...) hides it only as a whole word, with an s, after camelCase is split
|
|
62
|
+
// (userPin, API key). "session" alone is not a credential word: a session token
|
|
63
|
+
// is caught by "token" and session=abc by its punctuation.
|
|
64
|
+
const LONG_WORD = /pass(?:word|wd|phrase|code)|token|secret|credential|apikey|privatekey|authorization|sessionid|pincode|otpcode|cardnumber|onetime|verification/;
|
|
65
|
+
const SHORT_WORD = /^(?:pass|pin|otp|key|auth|cookie|private|signature|cvv|cvc|mfa|totp|pwd|basic|bearer)s?$/;
|
|
66
|
+
const valueMentionsSecret = (text) => text.split(/[^A-Za-z]+/).some((run) => LONG_WORD.test(run.toLowerCase())
|
|
67
|
+
|| run.replace(/([a-z])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").toLowerCase().split(" ").some((word) => SHORT_WORD.test(word)));
|
|
43
68
|
// A name with "code" in it hides a number, or 4 to 10 digits as text
|
|
44
69
|
// (login_code, sms_code, PINCode; zip_code over-hides). country_code: "US"
|
|
45
70
|
// still shows.
|
|
46
71
|
const CODE_DIGITS = /^\d{4,10}$/;
|
|
47
72
|
const codeValue = (name, value) => nameLetters(name).includes("code")
|
|
48
|
-
&& (typeof value === "number" || (typeof value === "string" && CODE_DIGITS.test(value.replace(/[\s
|
|
73
|
+
&& (typeof value === "number" || (typeof value === "string" && CODE_DIGITS.test(value.replace(/[\s\-\u2013\u2014]/g, ""))));
|
|
49
74
|
// A run of mixed letters and digits (an id, a key, a hash), or a card-length
|
|
50
75
|
// number. Shorter ids like a Stripe charge id stay readable.
|
|
51
|
-
const opaque = (text) => /(?=[\w+/=-]*\d)(?=[\w+/=-]*[A-Za-z])[\w+/=-]{32,}|[\w+/=-]{64,}|(?:\d[
|
|
76
|
+
const opaque = (text) => /(?=[\w+/=-]*\d)(?=[\w+/=-]*[A-Za-z])[\w+/=-]{32,}|[\w+/=-]{64,}|(?:\d[ \-\u2013\u2014]?){13,}/.test(text);
|
|
52
77
|
// The only characters plain text may hold. Everything else (tabs, control
|
|
53
|
-
// characters, = : ;
|
|
54
|
-
|
|
78
|
+
// characters, = : ; brackets, %) can carry labelled or encoded data. A quote
|
|
79
|
+
// mark does not: a title like Show 'Start' button reads as itself, and a
|
|
80
|
+
// quoted credential is still caught by its name, its colon or its shape (#4060).
|
|
81
|
+
// A medium or long dash (\u2013 \u2014) reads like a hyphen (#4139).
|
|
82
|
+
const PROSE_CHARS = /^(?:(?![={}\\])[\p{L}\p{M}\p{N}\p{P}\p{S} ])*$/u;
|
|
83
|
+
const PLAIN_CHARS = /^[\p{L}\p{N} .,\-\u2013\u2014_/()#+@!?$€£'"\u2018\u2019\u201C\u201D]*$/u;
|
|
55
84
|
// 4 or more digits in a row may be a code, a PIN or part of a card ("Your
|
|
56
85
|
// verification code 482913"); "order 1182" over-hides.
|
|
57
86
|
const DIGIT_RUN = /\d{4,}/;
|
|
87
|
+
const YEAR = /(?<!\d)(?:19|20)\d{2}(?!\d)/g;
|
|
88
|
+
// The fields that hold what a person wrote to be read (#4363).
|
|
89
|
+
const PROSE_FIELDS = new Set(["title", "description", "subject", "body", "content", "markdown", "reason"]);
|
|
58
90
|
|
|
59
91
|
const MAX_INPUTS = 12;
|
|
60
92
|
const MAX_VALUE = 80;
|
|
@@ -63,17 +95,38 @@ const HIDDEN = "hidden";
|
|
|
63
95
|
const plainName = (name) => /^[\w .-]{1,40}$/.test(name) && !secretLike(name);
|
|
64
96
|
const record = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
65
97
|
const count = (n, one, many) => `${n} ${n === 1 ? one : many}`;
|
|
98
|
+
// A ticket's title or body on an app approval is the person's own prose
|
|
99
|
+
// (#4363): "Empty board first run: no example to start from" hid behind its
|
|
100
|
+
// colon, so the person could not read one title before Allow. Such a field
|
|
101
|
+
// takes any punctuation (PROSE_CHARS; an = or a brace still hides, a colon
|
|
102
|
+
// after a credential word still hides by its label), a year (2026) is not a
|
|
103
|
+
// code, and its markdown marks and line breaks read as plain words.
|
|
104
|
+
const proseWords = (text) => text.replace(/[*`]+/g, "").replace(/\s+/g, " ").trim();
|
|
66
105
|
// Length is checked first, so the patterns only ever scan 80 characters.
|
|
67
|
-
const plainText = (text) => text.length <= MAX_VALUE &&
|
|
106
|
+
const plainText = (text, prose = false) => text.length <= MAX_VALUE && (prose ? PROSE_CHARS : PLAIN_CHARS).test(text)
|
|
107
|
+
&& !DIGIT_RUN.test(prose ? text.replace(YEAR, "") : text) && !valueMentionsSecret(text)
|
|
68
108
|
&& !secretLike(text) && !opaque(text);
|
|
69
109
|
|
|
70
|
-
|
|
110
|
+
// The text to show, or null when it must be hidden. A long text shows its
|
|
111
|
+
// start, cut at a word, and only that start is tested, so the patterns scan
|
|
112
|
+
// at most 81 characters whatever the size. No word break in the first 80
|
|
113
|
+
// characters (one long run) stays hidden.
|
|
114
|
+
function plainStart(text, prose = false) {
|
|
115
|
+
if (text.length <= MAX_VALUE) return plainText(text, prose) ? text.trim() : null;
|
|
116
|
+
const head = text.slice(0, MAX_VALUE + 1);
|
|
117
|
+
const cut = head.lastIndexOf(" ");
|
|
118
|
+
const start = cut > 0 ? head.slice(0, cut).trim() : "";
|
|
119
|
+
return start && plainText(start, prose) ? `${start}…` : null;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function valueText(value, prose = false) {
|
|
71
123
|
if (value === null || typeof value === "boolean") return String(value);
|
|
72
124
|
// At most 3 digits before the point: 49.99 shows, a 4-digit PIN does not.
|
|
73
125
|
if (typeof value === "number") return Number.isFinite(value) && Math.abs(value) < 1000 ? String(value) : HIDDEN;
|
|
74
126
|
if (typeof value === "string") {
|
|
75
127
|
if (value.trim() === "") return "(empty)";
|
|
76
|
-
|
|
128
|
+
const start = prose ? plainStart(proseWords(value), true) : plainStart(value);
|
|
129
|
+
return start ?? `${HIDDEN}, ${count(value.length, "character", "characters")}`;
|
|
77
130
|
}
|
|
78
131
|
// Nested values are summarised by size, never opened: a secret one level
|
|
79
132
|
// down is not shown.
|
|
@@ -118,21 +171,44 @@ export function moneyText(amount, currency) {
|
|
|
118
171
|
return new Intl.NumberFormat("en-US", { style: "currency", currency: code }).format(amount / divisor);
|
|
119
172
|
}
|
|
120
173
|
// A vendor's raw id ("pi_3MtwBwLkdIwHu7ix28a3tqPa", "cus_NffrFeUfNV2Hib"):
|
|
121
|
-
// it names the record but no person knows it, so its row goes last.
|
|
122
|
-
|
|
174
|
+
// it names the record but no person knows it, so its row goes last. A UUID
|
|
175
|
+
// ("1f0c7e9a-5b3d-4e21-9a6f-0c2d8b7e4a13") is the same kind of id (#4486).
|
|
176
|
+
export const RAW_ID = /^(?:[a-z]{2,6}_[A-Za-z0-9]{6,}|[0-9a-fA-F]{8}-(?:[0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12})$/;
|
|
177
|
+
const UUID = /^[0-9a-fA-F]{8}-(?:[0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}$/;
|
|
178
|
+
|
|
179
|
+
// A value that says nothing: an empty or whitespace text, "{}", "[]", an
|
|
180
|
+
// empty list or object.
|
|
181
|
+
const placeholder = (value) => (typeof value === "string" && /^(?:\s*|\s*\{\s*\}\s*|\s*\[\s*\]\s*)$/.test(value))
|
|
182
|
+
|| (Array.isArray(value) && value.length === 0) || (record(value) && Object.keys(value).length === 0);
|
|
183
|
+
|
|
184
|
+
// What a plain argument shows: the app's own name for its id when the caller
|
|
185
|
+
// found one and it reads as plain text, a bare UUID as itself (an id holds no
|
|
186
|
+
// secret by its shape; a credential-named argument never gets here), else the
|
|
187
|
+
// ordinary rule.
|
|
188
|
+
function shownValue(name, value, names) {
|
|
189
|
+
const named = Object.hasOwn(names ?? {}, name) && typeof names[name] === "string" ? plainStart(proseWords(names[name]), true) : null;
|
|
190
|
+
if (named) return named;
|
|
191
|
+
if (typeof value === "string" && UUID.test(value)) return value;
|
|
192
|
+
return valueText(value, PROSE_FIELDS.has(name));
|
|
193
|
+
}
|
|
123
194
|
|
|
124
195
|
/** Approval-card rows, using the same secret filter as the computer asker.
|
|
125
196
|
* `tool` is the app's tool name; a Stripe amount reads "Refund" only on a
|
|
126
|
-
* refund tool (or when the tool is not known).
|
|
127
|
-
|
|
197
|
+
* refund tool (or when the tool is not known). `names` maps an argument to the
|
|
198
|
+
* name the app gives its id (a team id to the team's name, #4486); it goes
|
|
199
|
+
* through the same filter as any text, and an id with no name shows as the id
|
|
200
|
+
* instead of "hidden, 36 characters". */
|
|
201
|
+
export function appInputsText(provider, inputs = {}, tool = "refund", names = {}) {
|
|
128
202
|
if (!record(inputs)) return toolInputsText({ _meta: { tool_params: inputs } });
|
|
129
203
|
const labels = { team: "Team", title: "Title", description: "Description", priority: "Priority", page_id: "Page", page: "Page", parent: "Page", content: "Adds", markdown: "Adds", body: "Comment", owner: "Owner", repo: "Repository", issue_number: "Issue", pullNumber: "Pull request", customer: "Customer", payment_intent: "Payment", charge: "Payment", reason: "Reason", currency: "Currency", to: "To", subject: "Subject" };
|
|
130
204
|
const money = (name, value) => provider === "stripe" && name === "amount" && Number.isSafeInteger(value) && value >= 0 && value <= 99999999;
|
|
131
205
|
const rows = Object.entries(inputs).slice(0, MAX_INPUTS).flatMap(([name, value]) => {
|
|
206
|
+
// An empty value tells the person nothing; a field with content always shows, as a count if nested (#4363).
|
|
207
|
+
if (placeholder(value)) return [];
|
|
132
208
|
if (money(name, value)) return [{ line: `${/refund/i.test(tool) ? "Refund" : "Amount"}: ${moneyText(value, inputs.currency)}` }];
|
|
133
209
|
// The currency is already in the amount.
|
|
134
210
|
if (provider === "stripe" && name === "currency" && money("amount", inputs.amount) && /^[a-z]{3}$/i.test(String(value))) return [];
|
|
135
|
-
const display = mentionsSecret(name) || codeValue(name, value) ? HIDDEN :
|
|
211
|
+
const display = mentionsSecret(name) || codeValue(name, value) ? HIDDEN : shownValue(name, value, names);
|
|
136
212
|
return [{ line: `${(Object.hasOwn(labels, name) ? labels[name] : undefined) ?? (plainName(name) ? name : "hidden name")}: ${display}`, id: RAW_ID.test(display) }];
|
|
137
213
|
});
|
|
138
214
|
return "Details:\n" + [...rows.filter((row) => !row.id), ...rows.filter((row) => row.id)].map((row) => row.line).join("\n");
|
package/lib/codingChecks.mjs
CHANGED
|
@@ -4,7 +4,11 @@ import { readFile, access } from "node:fs/promises";
|
|
|
4
4
|
import { join } from "node:path";
|
|
5
5
|
import { runChild, devServerEnv } from "./child.mjs";
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
// A check that ran out of time did not finish; that is not a failure of the
|
|
8
|
+
// work, so it is skipped with this reason and never starts a repair.
|
|
9
|
+
export const OUT_OF_TIME = "Ran out of time before this check finished.";
|
|
10
|
+
|
|
11
|
+
export async function runCodingChecks({ cwd, env, deadline, stopCheck, platform, killGraceMs, onChunk, onProcess }) {
|
|
8
12
|
let pkg;
|
|
9
13
|
let unreadable = false;
|
|
10
14
|
try { pkg = JSON.parse(await readFile(join(cwd, "package.json"), "utf8")); }
|
|
@@ -27,19 +31,19 @@ export async function runCodingChecks({ cwd, env, deadline, stopCheck, platform,
|
|
|
27
31
|
stopped = true;
|
|
28
32
|
entry.reason = "Stopped before this check finished.";
|
|
29
33
|
} else if (Date.now() >= deadline) {
|
|
30
|
-
|
|
34
|
+
entry.reason = OUT_OF_TIME;
|
|
31
35
|
} else {
|
|
32
36
|
const out = await runChild({
|
|
33
37
|
bin: "npm", args: ["run", script], cwd, env: { ...devServerEnv(env, platform), CI: "true" },
|
|
34
38
|
platform, maxMs: deadline - Date.now(), stopCheck, stopPollMs: 100,
|
|
35
|
-
killGraceMs, maxLogBytes: 12_000, onChunk, killProcessGroup: true,
|
|
39
|
+
killGraceMs, maxLogBytes: 12_000, onChunk, onProcess, killProcessGroup: true,
|
|
36
40
|
});
|
|
37
41
|
logs.push(out.log ?? "");
|
|
38
42
|
if (out.stoppedByUser) {
|
|
39
43
|
stopped = true;
|
|
40
44
|
entry.reason = "Stopped before this check finished.";
|
|
41
45
|
} else if (out.timedOut) {
|
|
42
|
-
|
|
46
|
+
entry.reason = OUT_OF_TIME;
|
|
43
47
|
} else if (out.spawnError || ([127, 9009].includes(out.code) && /(?:command not found|: not found|is not recognized as an internal or external command)/i.test(out.log ?? ""))) {
|
|
44
48
|
entry.reason = "A tool needed for this check is not installed.";
|
|
45
49
|
} else if (out.ok) {
|