viewable-one 0.12.6 → 0.12.8

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/lib/detect.mjs CHANGED
@@ -176,7 +176,8 @@ function ownPathDirs({ env = process.env } = {}) {
176
176
  * with `existsSync`, so a caller gets back a concrete path instead of a
177
177
  * boolean), the well-known install directories (`knownBinDirs`, also no
178
178
  * process spawned), and last a login shell's `command -v` (`loginShellWhich`
179
- * - slowest, memoized, asked only when the first two came up empty).
179
+ * - slowest, asked only when the first two came up empty; `detectAgents`
180
+ * remembers its answer, see `resolveMemo`).
180
181
  *
181
182
  * On POSIX a `bin` that already names a place (it contains a separator) is
182
183
  * `PM_<AGENT>_BIN` set to an explicit path, handed back unchanged and
@@ -476,6 +477,12 @@ export async function probeClaudeEffort(bin, { exec = execProbe, env = process.e
476
477
  return models;
477
478
  }
478
479
 
480
+ /** What `detectAgents` learned from `resolveAgentBinary`, per tool name, PATH and
481
+ * shell: a found path stays until it stops answering, a miss for this long. A
482
+ * tool installed after a miss shows up within one window. */
483
+ export const RESOLVE_MISS_MS = 30 * 60 * 1000;
484
+ const resolveMemo = new Map();
485
+
479
486
  /** Probe every engine. Returns the `agents` block stage 2 writes into the
480
487
  * mark file:
481
488
  *
@@ -493,11 +500,44 @@ export async function detectAgents({
493
500
  fileExists,
494
501
  timeoutMs = PROBE_TIMEOUT_MS,
495
502
  codexDiscover = exec === execProbe ? discoverCodex : null,
503
+ // The way a real run finds a tool (`resolveAgentBinary`: PATH, the usual
504
+ // install folders, then a login shell). Only the real probe uses it; a test's
505
+ // fake exec answers for the names it is given and nothing else.
506
+ resolve = exec === execProbe ? resolveAgentBinary : null,
507
+ memo,
508
+ now = Date.now,
496
509
  } = {}) {
510
+ const cache = memo ?? (resolve === resolveAgentBinary ? resolveMemo : new Map());
497
511
  const agents = {};
512
+ const probedBin = {};
498
513
  for (const spec of bins) {
499
514
  const bin = env[`PM_${spec.key.toUpperCase()}_BIN`]?.trim() || spec.bin;
500
- const result = await exec(bin, ["--version"], { timeoutMs, env });
515
+ let result = await exec(bin, ["--version"], { timeoutMs, env });
516
+ probedBin[spec.key] = bin;
517
+ // A watcher started by hand or by a service has a short PATH. "Not on this
518
+ // PATH" is not "not installed": a run would find the tool through
519
+ // `resolveAgentBinary`, so the mark must too, or the board reads Claude Code
520
+ // as missing and sends the run to another tool (#6646).
521
+ if (result?.ok !== true && resolve) {
522
+ // The lookup can spawn login shells, and this probe runs every five
523
+ // minutes before the first beat: remember a path, and a miss for a while.
524
+ const key = `${bin}\0${env.PATH ?? ""}\0${env.SHELL ?? ""}\0${env.HOME ?? ""}`;
525
+ const seen = cache.get(key);
526
+ try {
527
+ let path;
528
+ if (seen && (seen.path !== null || now() - seen.at < RESOLVE_MISS_MS)) path = seen.path;
529
+ else {
530
+ const resolved = await resolve(bin, { env, platform });
531
+ path = resolved?.found && resolved.path !== bin ? resolved.path : null;
532
+ cache.set(key, { path, at: now() });
533
+ }
534
+ if (path !== null) {
535
+ const retry = await exec(path, ["--version"], { timeoutMs, env });
536
+ if (retry?.ok === true) { result = retry; probedBin[spec.key] = path; }
537
+ else cache.delete(key);
538
+ }
539
+ } catch { /* an unresolvable tool stays not found */ }
540
+ }
501
541
  const found = result?.ok === true;
502
542
  const version = found ? versionFrom(result.stdout || result.stderr) : undefined;
503
543
  agents[spec.key] = { found, ...(version ? { version } : {}) };
@@ -506,14 +546,14 @@ export async function detectAgents({
506
546
  // elsewhere; Codex is queried through app-server below.
507
547
  if (agents.claude) {
508
548
  if (agents.claude.found) {
509
- const effortModels = await probeClaudeEffort(env.PM_CLAUDE_BIN?.trim() || bins.find((b) => b.key === "claude")?.bin || "claude", { exec, env, timeoutMs });
549
+ const effortModels = await probeClaudeEffort(probedBin.claude, { exec, env, timeoutMs });
510
550
  if (Object.keys(effortModels).length) agents.claude.effortModels = effortModels;
511
551
  }
512
552
  agents.claude.loggedIn = await claudeLoggedIn({ exec, env, platform, credentialsPath, fileExists });
513
553
  }
514
554
  if (agents.codex?.found && codexDiscover) {
515
555
  try {
516
- Object.assign(agents.codex, await codexDiscover({ bin: env.PM_CODEX_BIN?.trim() || "codex", env, timeoutMs }));
556
+ Object.assign(agents.codex, await codexDiscover({ bin: probedBin.codex, env, timeoutMs }));
517
557
  } catch { /* version detection remains valid when model discovery fails */ }
518
558
  }
519
559
  return agents;
package/lib/doctor.mjs CHANGED
@@ -447,7 +447,9 @@ export async function doctorRows(
447
447
  ? row("version", "version", true, "unknown", `${version} installed; npm did not answer (offline?)`)
448
448
  : compareVersions(newestPublished, version) > 0
449
449
  ? row("version", "version", true, "update available", `${version} installed, ${newestPublished} on npm: npm i -g viewable-one@latest --force`)
450
- : row("version", "version", true, "current", `${version} is the latest`),
450
+ : row("version", "version", true, "current", compareVersions(version, newestPublished) > 0
451
+ ? `${version} is newer than the published ${newestPublished}`
452
+ : `${version} is the latest`),
451
453
  );
452
454
 
453
455
  return rows;
@@ -0,0 +1,81 @@
1
+ // Ending what an agent left running in its own process group (#6557).
2
+ //
3
+ // A recovery-tracked agent leads a private group, so everything it started
4
+ // without `setsid` shares that group. Stop, the wall clock and the stall
5
+ // watchdog end the group, EXCEPT the preview server the session recorded in
6
+ // `.viewable-server.json` (ruling A, 2026-09-06). That server is not always in
7
+ // a group of its own: on macOS the instruction is `nohup <cmd> & disown`,
8
+ // which keeps the agent's group. So the server is spared by pid (and what it
9
+ // started), not by group. With no recorded server the whole group is signalled
10
+ // at once, which leaves no window for a fork to slip through.
11
+ import { processSnapshot, descendantPids } from "./procs.mjs";
12
+
13
+ const nap = (ms) => new Promise((done) => setTimeout(done, ms));
14
+
15
+ /** Is anything still alive in the group `pgid` leads? A member we may not
16
+ * signal (EPERM) is still a member. A group cannot be recycled while it has
17
+ * members, so a true answer here is about OUR group. */
18
+ function groupAlive(pgid) {
19
+ try { process.kill(-pgid, 0); return true; } catch (error) { return error.code === "EPERM"; }
20
+ }
21
+
22
+ async function spared(keep) {
23
+ try {
24
+ const pids = await keep?.();
25
+ return new Set([...(pids ?? [])].map(Number).filter((pid) => Number.isInteger(pid) && pid > 1));
26
+ } catch { return new Set(); }
27
+ }
28
+
29
+ /** The members of `pgid` that may be ended: all of them minus the spared
30
+ * servers and their descendants. null means the process list was unreadable. */
31
+ async function members(pgid, spare, snapshot) {
32
+ const table = await snapshot();
33
+ if (!table) return null;
34
+ const keep = new Set();
35
+ for (const pid of spare) {
36
+ if (!table.has(pid)) continue;
37
+ keep.add(pid);
38
+ for (const child of descendantPids(pid, table)) keep.add(child);
39
+ }
40
+ const found = [];
41
+ for (const [pid, row] of table) {
42
+ if (pid > 1 && row.pgid === pgid && !keep.has(pid) && !row.command?.includes("<defunct>")) found.push(pid);
43
+ }
44
+ return found;
45
+ }
46
+
47
+ /** Send `sig` to everything in the group that is not a spared server.
48
+ * `verified` signals only pids the process table shows in this group right
49
+ * now, never a bare group number (the late SIGKILL pass: a group that emptied
50
+ * during the grace must not be signalled blind). */
51
+ export async function signalGroup(pgid, sig, { keep, verified = false, snapshot = () => processSnapshot(), kill = (pid, s) => process.kill(pid, s) } = {}) {
52
+ const spare = await spared(keep);
53
+ if (!spare.size && !verified) {
54
+ try { kill(-pgid, sig); } catch { /* the group is already empty */ }
55
+ return;
56
+ }
57
+ // Signal members one by one. If the list is unreadable, end only the agent
58
+ // itself, as before #6557 (and nothing at all on a verified pass).
59
+ const found = (await members(pgid, spare, snapshot)) ?? (verified ? [] : [pgid]);
60
+ for (const pid of found) {
61
+ try { kill(pid, sig); } catch { /* gone already */ }
62
+ }
63
+ }
64
+
65
+ /** AFTER A KILL, WAIT UNTIL THE GROUP HAS NOTHING LEFT TO END. What the agent
66
+ * started gets until `deadline` (the kill grace) to follow SIGTERM, then
67
+ * SIGKILL, then a bounded wait for the kernel to reap them. Returns the pids
68
+ * that survived (empty: done), so the caller can keep recovery evidence for
69
+ * exactly those. POSIX only, like the group itself. */
70
+ export async function reapGroup(pgid, deadline, { keep, snapshot = () => processSnapshot(), alive = groupAlive, kill, wait = nap, now = Date.now, finalWaitMs = 2_000 } = {}) {
71
+ if (!Number.isInteger(pgid) || pgid <= 1) return [];
72
+ const spare = await spared(keep);
73
+ const step = spare.size ? 100 : 25;
74
+ const left = async () => spare.size ? ((await members(pgid, spare, snapshot))?.length ?? 1) > 0 : alive(pgid);
75
+ while (await left() && now() < deadline) await wait(step);
76
+ if (!await left()) return [];
77
+ await signalGroup(pgid, "SIGKILL", { keep, verified: true, snapshot, ...(kill ? { kill } : {}) });
78
+ for (let waited = 0; waited < finalWaitMs && await left(); waited += step) await wait(step);
79
+ if (!await left()) return [];
80
+ return (await members(pgid, spare, snapshot)) ?? [pgid];
81
+ }
@@ -41,6 +41,7 @@ import { makeRunnerHealth } from "./runner-health.mjs";
41
41
  import { unwatchFile, watchFile } from "node:fs";
42
42
  import { stat } from "node:fs/promises";
43
43
  import { makeAgentProbe } from "./detect.mjs";
44
+ import { makeChoiceMark } from "./agent-selection.mjs";
44
45
  import { platformMark } from "./platform.mjs";
45
46
  import { ensureViewableFolder } from "./viewableFolder.mjs";
46
47
  import { readRegistryChecked, registryPath } from "./registry.mjs";
@@ -117,6 +118,10 @@ export async function watchRegistered({
117
118
  makeRealtime = makeRunnerRealtime,
118
119
  // THE BOARD'S UPDATE BUTTON (#4949). Injected for the tests.
119
120
  makeSelfUpdater = makeSelfUpdate,
121
+ // THE PROGRAMS CHOSEN FOR EACH FOLDER (#6704), read from each folder's
122
+ // `.viewable/agents.json`. Injected for the tests; the default reads the
123
+ // folders this daemon watches.
124
+ choices,
120
125
  goodbye,
121
126
  } = {}) {
122
127
  // An installed update stops every watcher the same way Ctrl-C does: each
@@ -194,6 +199,14 @@ export async function watchRegistered({
194
199
  // first mark a person sees already carries the `agents` block rather than
195
200
  // arriving bare and filling in a beat later.
196
201
  await probe.once();
202
+ // And the programs chosen for each folder, for the same reason: a board
203
+ // that files a run before this arrives would pick one the person did not
204
+ // choose (#6704).
205
+ // `joining` holds the folders a registry re-read is about to start, so their
206
+ // choice is read before their watcher's first register.
207
+ let joining = [];
208
+ const chosen = choices ?? makeChoiceMark({ folders: () => [...first, ...watched, ...joining], log });
209
+ await chosen.refresh();
197
210
 
198
211
  // The mark file gains `version`, `updateAvailable`, `agents` and (brief 21
199
212
  // session 5, ruling 3A) `platform` here, and only here: `watch()`
@@ -240,7 +253,7 @@ export async function watchRegistered({
240
253
  holdsRuns: () => selfUpdater.holdsRuns(),
241
254
  claimStarted: () => selfUpdater.claimStarted(),
242
255
  };
243
- const markExtra = () => ({ ...platform, ...updater.mark(), ...probe.mark(), ...health.mark(), ...selfUpdater.mark() });
256
+ const markExtra = () => ({ ...platform, ...updater.mark(), ...probe.mark(), ...chosen.mark(), ...health.mark(), ...selfUpdater.mark() });
244
257
 
245
258
  // ONE REGISTER AND ONE HEARTBEAT FOR THE WHOLE PROCESS (ticket e8,
246
259
  // 2026-10-03; #616, 2026-10-16). Every folder's beat registers the whole
@@ -411,6 +424,7 @@ export async function watchRegistered({
411
424
  log(`${folder} left the registry - stopping its watcher`);
412
425
  entry.controller.abort();
413
426
  }
427
+ const joined = [];
414
428
  for (const folder of now) {
415
429
  if (running.has(folder)) continue;
416
430
  if (!(await isDir(folder))) {
@@ -424,8 +438,17 @@ export async function watchRegistered({
424
438
  announcedMissing.delete(folder);
425
439
  log(`${folder} joined the registry - syncing and watching it`);
426
440
  await syncOne(folder);
427
- startFolder(folder);
441
+ joined.push(folder);
428
442
  }
443
+ // The choices are read before a joining folder is watched (its first
444
+ // register would otherwise say none, and a run filed then would take
445
+ // another program), and before the beat a rewritten list asks for:
446
+ // setup choosing a program writes the list again (#6704).
447
+ if (joined.length > 0 || rewritten) {
448
+ joining = joined;
449
+ try { await chosen.refresh(); } finally { joining = []; }
450
+ }
451
+ for (const folder of joined) startFolder(folder);
429
452
  if (rewritten) askBeat();
430
453
  } while (refreshAgain);
431
454
  } catch (error) {
@@ -0,0 +1,282 @@
1
+ // A REFUSAL STOPS THE RUN; IT NEVER SENDS IT TO ANOTHER LOGIN (#6995).
2
+ //
3
+ // A computer run asked for a Supabase user count. Its read-only key was
4
+ // refused, so it ran the count through the Supabase CLI's own login, which
5
+ // has full rights to the database. A narrow key is the person's choice of how
6
+ // much the run may do; a stronger login that happens to sit on the same
7
+ // computer is not a second door to the same data.
8
+ //
9
+ // This file is the one list of those other logins, and every door that can
10
+ // hold a run back reads it:
11
+ // - the words every run is told (conversationRules.mjs `refusalRule`, in the
12
+ // idea preamble and the chat turn's prefix, for every engine);
13
+ // - Claude Code's deny rules (`CLAUDE_OTHER_LOGIN_TOOLS`, in agents.mjs's
14
+ // --disallowedTools and the ACP adapter's `disallowedTools`), checked
15
+ // before any permission prompt, so neither the allowlist's `Bash(npx:*)`
16
+ // nor "Allow for this run" can let one through;
17
+ // - the shared permission asker (permissionAsk.mjs), which refuses
18
+ // `usesAnotherLogin` commands before any question, remembered rule or
19
+ // "Allow for this run": Claude's prompts, ACP's and Codex's sandbox
20
+ // escalations all land there;
21
+ // - opencode's own config (`OPENCODE_OTHER_LOGIN_RULES`, agents.mjs
22
+ // prepareWorkspace), since `--auto` approves everything it does not deny.
23
+ //
24
+ // WHAT IT DOES NOT STOP, said plainly so nobody repeats it as a fence: a
25
+ // command the allowlist already lets through without asking can still reach
26
+ // one through a script (`node -e`, `npm run <script>`, a `cat` of a token file
27
+ // spelled some new way). The words cover those. The child's environment is
28
+ // already an allowlist (child.mjs `childEnv`), so a token exported in the
29
+ // person's shell (SUPABASE_ACCESS_TOKEN, GH_TOKEN) is not handed to the run.
30
+ //
31
+ // WHAT COUNTS. A command-line tool that signs in with a stored login of its
32
+ // own and reaches the data a connected app's key was meant to bound (the
33
+ // Supabase CLI), and the stores that hand out a saved secret (the macOS
34
+ // keychain, the Linux keyring, password managers, git's credential helpers,
35
+ // `gh auth token`). A tool is judged where it RUNS, at a command's start, so
36
+ // a commit message or a folder named `supabase` is not refused.
37
+
38
+ /** Command-line tools that use a stored login of their own. */
39
+ const LOGIN_TOOLS = ["supabase"];
40
+
41
+ /** Password managers: every call hands out or unlocks saved secrets. */
42
+ const PASSWORD_MANAGERS = new Set(["op", "bw", "lpass"]);
43
+
44
+ /** The macOS keychain subcommands that print a saved secret. */
45
+ const KEYCHAIN_READS = new Set(["find-generic-password", "find-internet-password", "find-key", "dump-keychain", "export"]);
46
+
47
+ /** Token files a login tool keeps on disk, matched anywhere in a command:
48
+ * `cat`, `head`, `node -e` or a redirection that names one is refused. Each
49
+ * is written with `/`; a `\\` (Windows) is matched too. */
50
+ const TOKEN_FILE_PATHS = [".supabase/access-token"];
51
+ const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
52
+ const TOKEN_FILES = new RegExp(TOKEN_FILE_PATHS.map((path) => path.split("/").map(escapeRegExp).join("[\\\\/]")).join("|"), "i");
53
+
54
+ /** Words that run the command after them. Each may take flags first; the
55
+ * flags listed take a value, which is skipped too. */
56
+ const WRAPPERS = new Map([
57
+ ["env", new Set(["-u", "-C", "--unset", "--chdir"])],
58
+ ["sudo", new Set(["-u", "-g", "-h", "-p", "-C", "-U", "-r", "-t", "-D"])],
59
+ ["doas", new Set(["-u", "-C"])],
60
+ ["command", new Set()], ["exec", new Set(["-a"])], ["builtin", new Set()], ["noglob", new Set()],
61
+ ["nohup", new Set()], ["time", new Set(["-f", "-o"])], ["nice", new Set(["-n"])],
62
+ ["xargs", new Set(["-I", "-n", "-P", "-L", "-d", "-E", "-s", "-a"])],
63
+ ["arch", new Set()], ["caffeinate", new Set(["-t", "-w"])], ["stdbuf", new Set()],
64
+ ["timeout", new Set(["-s", "-k", "--signal", "--kill-after"])],
65
+ // Shell keywords that start a command after them.
66
+ ["if", new Set()], ["then", new Set()], ["else", new Set()], ["elif", new Set()], ["do", new Set()],
67
+ ["while", new Set()], ["until", new Set()], ["!", new Set()],
68
+ ]);
69
+ /** Wrappers whose first plain word is a value, not the command. */
70
+ const FIRST_WORD_IS_VALUE = new Set(["timeout"]);
71
+
72
+ const SHELLS = new Set(["sh", "bash", "zsh", "dash", "ksh", "fish"]);
73
+
74
+ /** Package runners: `npx supabase`, `npm exec supabase`, `pnpm dlx supabase`. */
75
+ const PACKAGE_RUNNERS = new Map([
76
+ ["npx", null], ["bunx", null], ["pnpx", null],
77
+ ["npm", new Set(["exec", "x"])], ["pnpm", new Set(["dlx", "exec"])], ["yarn", new Set(["dlx", "exec"])], ["bun", new Set(["x"])],
78
+ ]);
79
+
80
+ /** A program's name as the shell finds it: no folder, no Windows suffix, any
81
+ * case (a Mac's disk does not tell `Supabase` from `supabase`). */
82
+ const programOf = (word) => String(word ?? "").split(/[\\/]/).pop().toLowerCase().replace(/\.(?:exe|cmd|bat|ps1)$/, "");
83
+
84
+ /** A package word without its version: `supabase@latest` is `supabase`. */
85
+ const packageOf = (word) => {
86
+ const name = String(word ?? "").replace(/^--package=/, "");
87
+ const at = name.indexOf("@", 1);
88
+ return (at > 0 ? name.slice(0, at) : name).toLowerCase();
89
+ };
90
+
91
+ /** A shell line as commands, each a list of words with quotes removed, and
92
+ * the command substitutions inside double quotes (`"$(...)"`, `` "`...`" ``),
93
+ * which still run. Separators (`;`, `&`, `|`, newline, parentheses, braces,
94
+ * backticks, `$(`) end a command only outside quotes; a quoted word stays one
95
+ * word, and single quotes hide a `$(` (it is literal text there). A
96
+ * redirection is not a word: `2>/dev/null supabase` runs `supabase`, so the
97
+ * fd number, the operator and its target are dropped. */
98
+ function commandsOf(line) {
99
+ const commands = [];
100
+ const substitutions = [];
101
+ let words = [];
102
+ let word = "";
103
+ let inWord = false;
104
+ let quote = null;
105
+ let target = false; // the next word is a redirection's target
106
+ const endWord = () => {
107
+ if (inWord && !target) words.push(word);
108
+ if (inWord) target = false;
109
+ word = "";
110
+ inWord = false;
111
+ };
112
+ const endCommand = () => { endWord(); target = false; if (words.length > 0) commands.push(words); words = []; };
113
+ for (let i = 0; i < line.length; i += 1) {
114
+ const c = line[i];
115
+ if (quote === "'") { if (c === "'") quote = null; else word += c; continue; }
116
+ if (quote === "\"") {
117
+ if (c === "\"") quote = null;
118
+ else if (c === "\\" && i + 1 < line.length) word += line[++i];
119
+ else {
120
+ if (c === "`" || (c === "$" && line[i + 1] === "(")) substitutions.push(line.slice(i + (c === "`" ? 1 : 2)));
121
+ word += c;
122
+ }
123
+ continue;
124
+ }
125
+ if (c === "\\") { if (i + 1 < line.length) { word += line[++i]; inWord = true; } continue; }
126
+ if (c === "'" || c === "\"") { quote = c; inWord = true; continue; }
127
+ if (c === "\n" || c === "\r") { endCommand(); continue; }
128
+ if (/\s/.test(c)) { endWord(); continue; }
129
+ if (c === "$" && line[i + 1] === "(") { endCommand(); i += 1; continue; }
130
+ if ((c === "<" || c === ">") && line[i + 1] !== "(") {
131
+ // `2>`, `&>`, `>>`, `<<<`, `>&1`, `>|`: a digit-only word before it is
132
+ // its fd, never a word of the command.
133
+ if (/^\d*$/.test(word) && !target) { word = ""; inWord = false; } else endWord();
134
+ while (i + 1 < line.length && "<>&|".includes(line[i + 1])) i += 1;
135
+ target = true;
136
+ continue;
137
+ }
138
+ if (";&|(){}`<>".includes(c)) { endCommand(); continue; }
139
+ word += c;
140
+ inWord = true;
141
+ }
142
+ endCommand();
143
+ return { commands, substitutions };
144
+ }
145
+
146
+ /** Whether one call of a program, with its words, reaches another login. */
147
+ function callUsesLogin(program, rest) {
148
+ if (LOGIN_TOOLS.includes(program) || PASSWORD_MANAGERS.has(program)) return true;
149
+ if (program.startsWith("git-credential")) return true;
150
+ if (program === "security") return KEYCHAIN_READS.has(rest[0]);
151
+ if (program === "secret-tool") return rest[0] === "lookup" || rest[0] === "search";
152
+ if (program === "git") {
153
+ // git's own options come before the subcommand; -c and -C take a value.
154
+ let i = 0;
155
+ while (i < rest.length && rest[i].startsWith("-")) i += rest[i] === "-c" || rest[i] === "-C" ? 2 : 1;
156
+ const sub = rest[i] ?? "";
157
+ return sub === "credential" || sub.startsWith("credential-");
158
+ }
159
+ if (program === "gh") {
160
+ const plain = rest.filter((w) => !w.startsWith("-"));
161
+ if (plain[0] !== "auth") return false;
162
+ return plain[1] === "token" || (plain[1] === "status" && rest.some((w) => w === "-t" || w === "--show-token"));
163
+ }
164
+ return false;
165
+ }
166
+
167
+ /** Whether a package runner's words start a login tool. */
168
+ function packageRunUsesLogin(words, depth) {
169
+ for (let i = 0; i < words.length; i += 1) {
170
+ const w = words[i];
171
+ if (w === "--") continue;
172
+ if (w === "-p" || w === "--package") { if (LOGIN_TOOLS.includes(packageOf(words[i + 1]))) return true; i += 1; continue; }
173
+ if (w.startsWith("--package=")) { if (LOGIN_TOOLS.includes(packageOf(w))) return true; continue; }
174
+ if (w === "-c" || w === "--call") return usesAnotherLogin(words[i + 1] ?? "", depth + 1);
175
+ if (w.startsWith("-")) continue;
176
+ return LOGIN_TOOLS.includes(packageOf(w)) || LOGIN_TOOLS.includes(programOf(w));
177
+ }
178
+ return false;
179
+ }
180
+
181
+ /** Whether one command (its words) reaches another login. */
182
+ function commandUsesLogin(words, depth) {
183
+ let i = 0;
184
+ for (;;) {
185
+ const w = words[i];
186
+ if (w === undefined) return false;
187
+ if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(w)) { i += 1; continue; }
188
+ const wrapper = WRAPPERS.get(programOf(w));
189
+ if (!wrapper) break;
190
+ i += 1;
191
+ while (words[i]?.startsWith("-") && words[i] !== "-") i += wrapper.has(words[i]) ? 2 : 1;
192
+ if (FIRST_WORD_IS_VALUE.has(programOf(w)) && words[i] !== undefined) i += 1;
193
+ }
194
+ const program = programOf(words[i]);
195
+ const rest = words.slice(i + 1);
196
+ if (SHELLS.has(program)) {
197
+ const flag = rest.findIndex((w) => /^-[A-Za-z]*c[A-Za-z]*$/.test(w));
198
+ return flag >= 0 && usesAnotherLogin(rest[flag + 1] ?? "", depth + 1);
199
+ }
200
+ if (program === "eval") return usesAnotherLogin(rest.join(" "), depth + 1);
201
+ if (PACKAGE_RUNNERS.has(program)) {
202
+ const subs = PACKAGE_RUNNERS.get(program);
203
+ if (subs === null) return packageRunUsesLogin(rest, depth);
204
+ return subs.has(rest[0]) && packageRunUsesLogin(rest.slice(1), depth);
205
+ }
206
+ return callUsesLogin(program, rest);
207
+ }
208
+
209
+ /** Whether a shell command reaches another login or a saved secret, at any
210
+ * command in the line, inside `sh -c`, `eval`, a package runner or a `$( )`.
211
+ * Anything it cannot read for sure (too deeply nested) counts as a yes. */
212
+ export function usesAnotherLogin(command, depth = 0) {
213
+ const line = String(command ?? "");
214
+ if (depth > 4) return true;
215
+ if (TOKEN_FILES.test(line)) return true;
216
+ const { commands, substitutions } = commandsOf(line);
217
+ if (commands.some((words) => commandUsesLogin(words, depth))) return true;
218
+ // A substitution inside double quotes still runs: "$(supabase ...)".
219
+ return substitutions.some((rest) => usesAnotherLogin(rest, depth + 1));
220
+ }
221
+
222
+ /** What the agent reads when the asker refuses one, naming the board's ask
223
+ * in that engine's own words (`ask_user` for Claude Code and ACP,
224
+ * `mcp__glytch__ask_user` for Codex), the way refusalRule does. It shuts the
225
+ * other doors and sends the run to ask with the reason. */
226
+ export const otherLoginDenied = (ask = "ask_user") =>
227
+ "Refused: this uses another login, token or saved key on this computer. A run never gets round a refusal that way. " +
228
+ `Stop this part of the task and ask the person on the board with ${ask}: say what was refused and why ` +
229
+ "(the error you got), and what they could change. Do not try another login, CLI, token or key.";
230
+
231
+ /** Claude Code deny rules for the same tools. A deny rule is checked before
232
+ * any allow rule or prompt, so it holds where `Bash(npx:*)`, `Bash(npm:*)`
233
+ * and `Bash(git:*)` on the allowlist would otherwise let the call run with no
234
+ * question, and so never reach usesAnotherLogin. The `:*` rules are prefix
235
+ * rules every Claude Code reads. The `*` rules are wildcards (Claude Code
236
+ * 2.1.316 reads them, "Use * for wildcards"; an older one matches nothing
237
+ * with them): they catch the package named by a flag (`npx --package
238
+ * supabase supabase`, `npx -y -p supabase@2 supabase`), a version, a script
239
+ * (`npx -c 'supabase ...'`) and flags before the name. They need the name as
240
+ * its own word, so `npx vitest run supabase/functions/x.test.mjs` and
241
+ * `npx eslint supabase` still run. `npm exec` and `npm x` are barred whenever
242
+ * they name the tool at all: a run uses npx for its own tools. */
243
+ /** git's credential subcommand and the helpers that print a saved login. */
244
+ const GIT_CREDENTIAL_WORDS = ["credential fill", "credential approve", "credential reject", "credential capability",
245
+ ...["osxkeychain", "manager", "manager-core", "store", "cache", "libsecret", "wincred"].map((helper) => `credential-${helper}`)];
246
+
247
+ export const CLAUDE_OTHER_LOGIN_TOOLS = [
248
+ ...LOGIN_TOOLS.flatMap((tool) => [
249
+ `Bash(${tool}:*)`,
250
+ `Bash(npx ${tool}:*)`, `Bash(npx -y ${tool}:*)`, `Bash(npx --yes ${tool}:*)`, `Bash(npx ${tool}@latest:*)`,
251
+ `Bash(npm exec ${tool}:*)`, `Bash(npm exec -- ${tool}:*)`, `Bash(npm x ${tool}:*)`,
252
+ `Bash(npx ${tool}*)`, `Bash(npx -* ${tool})`, `Bash(npx -* ${tool} *)`, `Bash(npx -* ${tool}@*)`,
253
+ `Bash(npx *-p ${tool}*)`, `Bash(npx *--package ${tool}*)`, `Bash(npx *--package=${tool}*)`,
254
+ `Bash(npx *-c *${tool}*)`, `Bash(npx *--call *${tool}*)`,
255
+ `Bash(npm exec *${tool}*)`, `Bash(npm x *${tool}*)`,
256
+ ]),
257
+ // git's own options first (`git -c core.pager=cat credential fill`, `git -C
258
+ // <dir> credential fill`) still match Bash(git:*), so the subcommands and
259
+ // helpers are named after any options. A commit message would have to say
260
+ // "credential fill" to be caught.
261
+ "Bash(git credential:*)",
262
+ ...GIT_CREDENTIAL_WORDS.flatMap((word) => [`Bash(git ${word}:*)`, `Bash(git * ${word}*)`]),
263
+ // A shell read of a token file (`cat`, `head`, `node -e`) is on the
264
+ // allowlist too: deny any command that names one.
265
+ ...TOKEN_FILE_PATHS.flatMap((path) => [`Bash(*${path}*)`, `Bash(*${path.replaceAll("/", "\\")}*)`]),
266
+ "Read(~/.supabase/**)",
267
+ ];
268
+
269
+ /** opencode's own deny rules (its `permission.bash` patterns), for the same
270
+ * tools: `--auto` approves everything that is not denied. */
271
+ export const OPENCODE_OTHER_LOGIN_RULES = Object.fromEntries([
272
+ ...LOGIN_TOOLS.flatMap((tool) => [tool, `${tool} *`, `npx ${tool}*`, `npx -y ${tool}*`, `npm exec ${tool}*`]),
273
+ ...[...PASSWORD_MANAGERS].flatMap((tool) => [tool, `${tool} *`]),
274
+ ...LOGIN_TOOLS.flatMap((tool) => [`npx -* ${tool}`, `npx -* ${tool} *`, `npx -* ${tool}@*`, `npx *-p ${tool}*`, `npx *--package ${tool}*`,
275
+ `npx *--package=${tool}*`, `npx *-c *${tool}*`, `npm exec *${tool}*`, `npm x *${tool}*`]),
276
+ "security find-*", "security dump-keychain*", "security export*",
277
+ "secret-tool lookup*", "secret-tool search*",
278
+ "gh auth token*", "gh auth status *--show-token*", "gh auth status *-t*",
279
+ "git credential*", "git-credential*",
280
+ ...GIT_CREDENTIAL_WORDS.map((word) => `git * ${word}*`),
281
+ ...TOKEN_FILE_PATHS.flatMap((path) => [`*${path}*`, `*${path.replaceAll("/", "\\")}*`]),
282
+ ].map((pattern) => [pattern, "deny"]));