viewable-one 0.12.7 → 0.12.9

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.
@@ -5,15 +5,85 @@ import { readFile } from 'node:fs/promises';
5
5
  import { homedir } from 'node:os';
6
6
  import { join } from 'node:path';
7
7
  import { prepareCodexApps } from './codexApps.mjs';
8
- import { execProbe, resolveAgentBinary } from './detect.mjs';
8
+ import { claudeConfigDir, claudeGlobalConfigPath, execProbe, resolveAgentBinary } from './detect.mjs';
9
+ import { isBoardServer } from './mcpjson.mjs';
10
+
11
+ const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
12
+
13
+ /** One server line of `claude mcp list` (2.1.328): `name: <url> (HTTP) - ✔ Connected`
14
+ * or `name: <command and args> - ✔ Connected`, as an entry isBoardServer reads. */
15
+ function listedEntry(line, name) {
16
+ const target = line.slice(name.length + 1).replace(/\s+-\s+\S*\s*(?:Connected|Failed to connect|Needs authentication)\s*$/, '').trim();
17
+ const url = /^(\S+)\s+\((?:HTTP|SSE)\)$/i.exec(target);
18
+ if (url) return { url: url[1] };
19
+ const [command, ...args] = target.split(/\s+/);
20
+ return { command, args };
21
+ }
22
+
23
+ const unreadableList = () => new Error("Couldn't read the apps set up in Claude Code.");
24
+
25
+ // THE SERVERS A CLAUDE RUN WITH THE PERSON'S APPS LOADS (#7550). The run keeps
26
+ // --strict-mcp-config and is handed exactly these, beside its own board server,
27
+ // in one --mcp-config file. Read from the files Claude Code reads them from, by
28
+ // name and address, never from `claude mcp list` (a line it cannot parse would
29
+ // let a server through). Every Viewable board server is left out, whatever its
30
+ // name. Plugins and claude.ai connectors are not read and do not load: strict
31
+ // hides both (checked on Claude Code 2.1.328), until each can be checked.
32
+ // Throws when a file is there but cannot be read: the run then goes with the
33
+ // apps off, never with a list it could not check.
34
+ export async function claudeAppServers({ cwd, root = cwd, env = process.env, home, read = readFile } = {}) {
35
+ const parse = async (path) => {
36
+ let raw;
37
+ try { raw = await read(path, 'utf8'); } catch (error) {
38
+ if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') return null;
39
+ throw unreadableList();
40
+ }
41
+ if (raw.length > 2_000_000) throw unreadableList();
42
+ const errors = [];
43
+ const data = parseJsonc(raw, errors, { allowTrailingComma: true });
44
+ if (errors.length || !isObject(data)) throw unreadableList();
45
+ return data;
46
+ };
47
+ const serversOf = (holder) => {
48
+ const servers = holder?.mcpServers;
49
+ if (servers === undefined || servers === null) return {};
50
+ if (!isObject(servers) || Object.values(servers).some((entry) => !isObject(entry))) throw unreadableList();
51
+ return servers;
52
+ };
53
+ const list = (value) => (Array.isArray(value) ? value.filter((name) => typeof name === 'string') : []);
54
+ const global = (await parse(claudeGlobalConfigPath(env, home))) ?? {};
55
+ const folders = [...new Set([cwd, root].filter(Boolean))];
56
+ const configDir = claudeConfigDir(env, home);
57
+ // A folder's .mcp.json server loads only once the person approved it there.
58
+ const approvals = [
59
+ ...folders.map((folder) => global.projects?.[folder]),
60
+ ...(await Promise.all([join(configDir, 'settings.json'), join(cwd, '.claude', 'settings.json'), join(cwd, '.claude', 'settings.local.json')].map(parse))),
61
+ ].filter(isObject);
62
+ const approved = (name) => !approvals.some((holder) => list(holder.disabledMcpjsonServers).includes(name)) &&
63
+ approvals.some((holder) => holder.enableAllProjectMcpServers === true || list(holder.enabledMcpjsonServers).includes(name));
64
+ const project = serversOf(await parse(join(cwd, '.mcp.json')));
65
+ // Claude Code's order when two share a name: local, then project, then user.
66
+ const all = { ...serversOf(global),
67
+ ...Object.fromEntries(Object.entries(project).filter(([name]) => approved(name))),
68
+ ...Object.assign({}, ...folders.map((folder) => serversOf(global.projects?.[folder]))) };
69
+ const servers = {};
70
+ const dropped = [];
71
+ for (const [name, entry] of Object.entries(all)) {
72
+ if (isBoardServer(name, entry, { env })) dropped.push(name);
73
+ else servers[name] = entry;
74
+ }
75
+ return { servers, dropped };
76
+ }
9
77
 
10
78
  export async function lookForComputerApps({ cwd, env = process.env, platform = process.platform,
11
79
  home = homedir(), read = readFile, probe = execProbe, codex = prepareCodexApps,
12
80
  resolve = resolveAgentBinary } = {}) {
13
81
  const apps = [];
14
82
  const failed = new Set();
15
- const add = (name, source, state) => {
83
+ // A Viewable board server is never one of the person's apps (#7550).
84
+ const add = (name, source, state, entry) => {
16
85
  if (typeof name !== 'string' || !name.trim() || name.length > 120 || /[\x00-\x1f\x7f]/.test(name)) return;
86
+ if (isBoardServer(name, entry, { env })) return;
17
87
  if (!apps.some((a) => a.name === name && a.source === source)) apps.push({ name, source, state });
18
88
  };
19
89
  const config = async (path, source, key = 'mcpServers') => {
@@ -25,13 +95,13 @@ export async function lookForComputerApps({ cwd, env = process.env, platform = p
25
95
  if (errors.length) throw new Error("invalid");
26
96
  const servers = data?.[key] ?? {};
27
97
  if (!servers || typeof servers !== 'object' || Array.isArray(servers)) throw new Error('invalid');
28
- return { data, names: Object.keys(servers) };
98
+ return { data, names: Object.keys(servers), servers };
29
99
  } catch (error) {
30
100
  if (error?.code !== 'ENOENT') failed.add(source);
31
- return { data: {}, names: [] };
101
+ return { data: {}, names: [], servers: {} };
32
102
  }
33
103
  };
34
- const claude = await config(join(home, '.claude.json'), 'Claude Code');
104
+ const claude = await config(claudeGlobalConfigPath(env, home), 'Claude Code');
35
105
  const project = await config(join(cwd, '.mcp.json'), 'Claude Code');
36
106
  const names = [...new Set([...claude.names, ...project.names,
37
107
  ...Object.keys(claude.data?.projects?.[cwd]?.mcpServers ?? {})])];
@@ -42,19 +112,24 @@ export async function lookForComputerApps({ cwd, env = process.env, platform = p
42
112
  if (!checked.ok) failed.add('Claude Code');
43
113
  const lines = checked.stdout.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '').split(/\r?\n/);
44
114
  for (const line of lines) {
115
+ // Plugins and claude.ai connectors do not load in a run (#7550), so
116
+ // they are not listed as its apps.
117
+ if (/^(?:plugin:|claude\.ai\s)/i.test(line)) continue;
45
118
  const match = /^([^:]{1,120}):.+(?:Connected|Failed to connect|Needs authentication)\s*$/.exec(line);
46
119
  if (match && !names.includes(match[1])) names.push(match[1]);
47
120
  }
121
+ const entries = { ...claude.servers, ...project.servers, ...(claude.data?.projects?.[cwd]?.mcpServers ?? {}) };
48
122
  for (const name of names) {
49
123
  const line = lines.find((line) => line.startsWith(`${name}:`));
50
- add(name, 'Claude Code', checked.ok && /(?:✓|✔) Connected\s*$/.test(line ?? '') ? 'available' : 'unanswered');
124
+ if (line && isBoardServer(name, listedEntry(line, name), { env })) continue;
125
+ add(name, 'Claude Code', checked.ok && /(?:✓|✔) Connected\s*$/.test(line ?? '') ? 'available' : 'unanswered', entries[name]);
51
126
  }
52
127
  }
53
128
  try {
54
129
  const bin = await resolve(env.PM_CODEX_BIN || 'codex', { env, platform });
55
130
  if (bin.found) {
56
- const plan = await codex({ bin: bin.path, cwd, env, timeoutMs: 15_000 }, { on: true, isDraft: false });
57
- for (const source of plan.sources) add(source.name, 'Codex', source.enabled && source.tools?.length > 0 ? 'available' : 'unanswered');
131
+ const plan = await codex({ bin: bin.path, cwd, env, boardEnv: env, timeoutMs: 15_000 }, { on: true, isDraft: false });
132
+ for (const source of plan.sources) if (!source.board) add(source.name, 'Codex', source.enabled && source.tools?.length > 0 ? 'available' : 'unanswered', null);
58
133
  }
59
134
  } catch { failed.add('Codex'); }
60
135
 
@@ -68,8 +143,8 @@ export async function lookForComputerApps({ cwd, env = process.env, platform = p
68
143
  [join(home, '.cursor', 'mcp.json'), 'Cursor', 'mcpServers'],
69
144
  [join(cwd, '.cursor', 'mcp.json'), 'Cursor', 'mcpServers'],
70
145
  ]) {
71
- const { names } = await config(path, source, key);
72
- for (const name of names) add(name, source, 'unsupported');
146
+ const { names, servers } = await config(path, source, key);
147
+ for (const name of names) add(name, source, 'unsupported', servers[name]);
73
148
  }
74
149
  if (apps.length > 200) throw new Error('Too many computer apps.');
75
150
  return { apps, failed: [...failed] };
@@ -71,18 +71,52 @@ export function otherAppsRule() {
71
71
  );
72
72
  }
73
73
 
74
+ // A TABLE ASK NEEDS A DRAWN TABLE (#8102). A run asked for a table reported
75
+ // "Made the table of all ten customer feedback items" with no table on the
76
+ // board: nothing told it that the board shows a table only as a drawn card.
77
+ // The board tools now refuse that line (board-mcp claimCheck.mjs); this says
78
+ // what to do first. `propose` is the engine's own tool name.
79
+ export function drawnCardRule(propose) {
80
+ return (
81
+ "When the person asks for a table, chart, list, timeline or kanban, put it " +
82
+ `on the board as a drawn card: ${propose} an addIdea with a snippet (x-table, ` +
83
+ `x-chart, x-list, x-timeline; get_library lists them). ` +
84
+ "Never say you made one you did not draw; if you could not, say so.\n\n"
85
+ );
86
+ }
87
+
88
+ // A REFUSAL STOPS THE RUN AND ASKS (#6995). A read-only key that was refused
89
+ // sent a run to the Supabase CLI's full-rights login instead. Every engine is
90
+ // told this, in an idea's preamble and in a chat turn's prefix; the tools it
91
+ // names are also barred outright where the engine allows it (otherLogins.mjs).
92
+ // `ask` is the engine's own name for the board's ask_user.
93
+ export function refusalRule(ask) {
94
+ return (
95
+ "When a read or a write is refused (a key that only reads, a permission " +
96
+ "error, a 401 or 403, a tool or app that says no), stop that part of the " +
97
+ `task and ask the person with ${ask}: say what was refused and why, in ` +
98
+ "the words of the error, and what they could change. Never get round a " +
99
+ "refusal with another login, CLI session, token or key on this computer: " +
100
+ "no Supabase CLI, no gh token, no keychain or password manager, no key " +
101
+ "from a file or a setting, and no other account. If you cannot ask, say " +
102
+ "what was refused in your reply and stop there.\n\n"
103
+ );
104
+ }
105
+
74
106
  // USE MY COMPUTER'S APPS IS OFF (#481). A run without the switch has no way
75
107
  // to the person's own apps, so rather than hunt for one it says so in its
76
108
  // closing message, in these words: the app finds the sentence and offers
77
- // Open Manage agent under it.
78
- export const APPS_OFF_SENTENCE = "Turn on **Use my computer's apps** in Manage agent and I will try again.";
109
+ // Open Settings under it, which lands on the switch (#7333). The agent window
110
+ // that held it said "in Manage agent"; a sidecar not yet updated still does, so
111
+ // the readers take both.
112
+ export const APPS_OFF_SENTENCE = "Turn on **Use my computer's apps** in Settings and I will try again.";
79
113
  /** Closing words that ask for Use my computer's apps (#6552): the sentence
80
114
  * above, bold, quoted or plain, as a model writes it back. The app's own
81
115
  * reader is src/nodes/sessionWords.ts `offersComputerApps`. A run whose
82
116
  * closing asks for the apps could not do its job; runnerCompletion.mjs says
83
117
  * so on the row (`sidecar.unable`), and an automation counts it as failed. */
84
118
  export function asksForComputerApps(text) {
85
- return /Turn on [*'"\u2018\u201c]*Use my computer['\u2019]s apps[*'"\u2019\u201d]* in Manage agent/i.test(String(text ?? ""));
119
+ return /Turn on [*'"\u2018\u201c]*Use my computer['\u2019]s apps[*'"\u2019\u201d]* in (?:Manage agent|Settings)/i.test(String(text ?? ""));
86
120
  }
87
121
 
88
122
  export function computerAppsOffRule() {
package/lib/detect.mjs CHANGED
@@ -361,6 +361,24 @@ export const runInteractive = (
361
361
  child.on("close", (code) => settle({ ok: code === 0, stdout: "", stderr, code }));
362
362
  });
363
363
 
364
+ /** Where Claude Code keeps its config: `CLAUDE_CONFIG_DIR` when set, else
365
+ * `~/.claude`. The ONE place this package answers that (#7516); every read of
366
+ * Claude Code's own files goes through it or `claudeGlobalConfigPath`. */
367
+ export const claudeConfigDir = (env = process.env, home) => {
368
+ const configDir = env.CLAUDE_CONFIG_DIR?.trim();
369
+ if (configDir) return configDir;
370
+ return join(home || env.HOME?.trim() || homedir(), ".claude");
371
+ };
372
+
373
+ /** Claude Code's global settings file (the `mcpServers` list the computer's
374
+ * app list reads). Claude Code keeps it INSIDE `CLAUDE_CONFIG_DIR` when that
375
+ * is set, and at `~/.claude.json` (beside, not inside, `~/.claude`) when not. */
376
+ export const claudeGlobalConfigPath = (env = process.env, home) => {
377
+ const configDir = env.CLAUDE_CONFIG_DIR?.trim();
378
+ if (configDir) return join(configDir, ".claude.json");
379
+ return join(home || env.HOME?.trim() || homedir(), ".claude.json");
380
+ };
381
+
364
382
  /** Claude Code's login marker ON THE PLATFORMS THAT KEEP ONE AS A FILE.
365
383
  *
366
384
  * `CLAUDE_CONFIG_DIR` moves the whole config directory, and the file with it
@@ -370,11 +388,8 @@ export const runInteractive = (
370
388
  *
371
389
  * Its PRESENCE is the whole check. Reading its CONTENTS would mean this
372
390
  * package handling someone's credentials, which it will not do. */
373
- export const claudeCredentialsPath = (env = process.env) => {
374
- const configDir = env.CLAUDE_CONFIG_DIR?.trim();
375
- if (configDir) return join(configDir, ".credentials.json");
376
- return join(env.HOME?.trim() || homedir(), ".claude", ".credentials.json");
377
- };
391
+ export const claudeCredentialsPath = (env = process.env) =>
392
+ join(claudeConfigDir(env), ".credentials.json");
378
393
 
379
394
  /** The macOS Keychain item Claude Code writes its login into.
380
395
  *
package/lib/doctor.mjs CHANGED
@@ -46,7 +46,7 @@ import { projectMcpServerKey } from "./project-mcp.mjs";
46
46
  import { syncFolder } from "./sync.mjs";
47
47
  import { readAgentSelection } from "./agent-selection.mjs";
48
48
  import { compareVersions, latestFromNpm, packageVersion, verifyInstalledCli } from "./update.mjs";
49
- import { authDisplayPath, PERSONAL_TOKEN_REJECTED_HINT, REAUTH_REQUIRED_HINT, hostedStatus } from "./auth.mjs";
49
+ import { authDisplayPath, PERSONAL_TOKEN_REJECTED_HINT, REAUTH_REQUIRED_HINT, RENEWAL_NO_ANSWER_HINT, hostedStatus } from "./auth.mjs";
50
50
  import { presence as hostedPresence } from "./runnerApi.mjs";
51
51
 
52
52
  // `row` is imported from cli-output.mjs (brief 31 review, 2026-09-12 - it
@@ -230,7 +230,7 @@ export async function doctorRows(
230
230
  // "board sign-in" row further down. No network call of its own
231
231
  // (hostedStatus's own header): a doctor row read constantly should not
232
232
  // cost one just to learn whether there is a credential on file at all.
233
- const boardAuth = await hostedStatus(env);
233
+ let boardAuth = await hostedStatus(env);
234
234
 
235
235
  // The daemon, in two halves that fail differently: the OS holding the
236
236
  // registration, and the runner actually writing its mark. Ruling 1A chose
@@ -279,6 +279,11 @@ export async function doctorRows(
279
279
  rows.push(row("beat", "daemon beating", true, "unknown", "sign in to see the heartbeat"));
280
280
  } else {
281
281
  const presenceResult = await presence({ paths: [root] }, { env, ...(fetchImpl ? { fetchImpl } : {}) });
282
+ // The presence call may itself renew a sign-in whose last renewal got no
283
+ // answer, and that retry can end in a refusal. Read the mark again so the
284
+ // sign-in row below never says "trying again" about a sign-in that is
285
+ // over (#8221).
286
+ boardAuth = await hostedStatus(env);
282
287
  if (presenceResult.ok) boardAccount = presenceResult.account ?? null;
283
288
  if (!presenceResult.ok) {
284
289
  rows.push(row("beat", "daemon beating", true, "unknown", `could not reach the board to check: ${presenceResult.error}`));
@@ -380,6 +385,17 @@ export async function doctorRows(
380
385
  `the personal token in ${authDisplayPath(env)} was rejected by the board${boardAuth.deadSince ? ` (since ${boardAuth.deadSince})` : ""}`,
381
386
  PERSONAL_TOKEN_REJECTED_HINT,
382
387
  )
388
+ // A renewal that got no answer was never refused (#8221): the runner
389
+ // is still trying, so neither "expired" nor "refused" is true yet.
390
+ : boardAuth.deadReason === "refresh_uncertain"
391
+ ? row(
392
+ "boardAuth",
393
+ "board sign-in",
394
+ false,
395
+ "renewing",
396
+ `the last renewal of the credential in ${authDisplayPath(env)} got no answer${boardAuth.deadSince ? ` (since ${boardAuth.deadSince})` : ""}`,
397
+ RENEWAL_NO_ANSWER_HINT,
398
+ )
383
399
  : row(
384
400
  "boardAuth",
385
401
  "board sign-in",
@@ -2,13 +2,14 @@
2
2
  // connected folder's file list, or one file's bytes, and the runner answers
3
3
  // from disk. Read only: nothing here writes, runs or follows a link out of
4
4
  // the folder. The same files the browser's own folder link lists
5
- // (src/folder/folder.ts levelOf): no dot or build folders, only files the app
6
- // can read.
5
+ // (src/folder/folder.ts levelOf): no dot or build folders, no secret files
6
+ // (.env, keys), only files the app can read. The skip rules mirror
7
+ // src/folder/skipRules.ts by hand: the bridge cannot import src (#8538).
7
8
  import { lstat, readdir, readFile, realpath } from "node:fs/promises";
8
9
  import { join, relative, resolve, sep } from "node:path";
9
10
 
10
11
  const SKIP_DIRS = new Set(["node_modules", "dist"]);
11
- // src/folder/import.ts TEXT_EXTENSIONS plus the documents docReader.ts reads.
12
+ // src/folder/textExtensions.ts TEXT_EXTENSIONS plus the documents docReader.ts reads.
12
13
  const READABLE = new Set([
13
14
  "txt", "md", "markdown", "csv", "tsv", "json", "yaml", "yml", "toml",
14
15
  "js", "jsx", "ts", "tsx", "py", "rb", "go", "rs", "java", "kt", "swift",
@@ -24,6 +25,16 @@ const readable = (name) => {
24
25
  return dot >= 0 && READABLE.has(name.slice(dot + 1).toLowerCase());
25
26
  };
26
27
  const skipped = (name) => name.startsWith(".") || SKIP_DIRS.has(name);
28
+ const SECRET_EXTENSIONS = new Set(["pem", "key", "p12", "pfx", "keystore"]);
29
+ const SECRET_NAMES = new Set([".npmrc", ".netrc", ".pgpass", ".env", "credentials"]);
30
+ const SECRET_PREFIXES = [".env.", "id_rsa", "id_ecdsa", "id_ed25519", "credentials."];
31
+ const isSecretFile = (name) => {
32
+ const lower = name.toLowerCase();
33
+ if (SECRET_NAMES.has(lower)) return true;
34
+ if (SECRET_PREFIXES.some((prefix) => lower.startsWith(prefix))) return true;
35
+ const dot = lower.lastIndexOf(".");
36
+ return dot > 0 && SECRET_EXTENSIONS.has(lower.slice(dot + 1));
37
+ };
27
38
 
28
39
  /** Every readable file under `root`, with the directories that hold one,
29
40
  * depth first, directories before files. Links are not followed. */
@@ -45,7 +56,7 @@ export async function listFolder(root, max = FOLDER_LIST_MAX) {
45
56
  await walk(join(dir, child.name), `${prefix}${child.name}/`);
46
57
  // A directory holding nothing readable is dropped, as listFolderDeep does.
47
58
  if (entries.length === at + 1) entries.pop();
48
- } else if (child.isFile() && readable(child.name)) {
59
+ } else if (child.isFile() && readable(child.name) && !isSecretFile(child.name)) {
49
60
  entries.push({ path: `${prefix}${child.name}`, dir: false });
50
61
  }
51
62
  }
@@ -34,7 +34,7 @@
34
34
  // are seams, every test asserts the argv sequence, and NOTHING in the suite
35
35
  // runs claude, codex, opencode or a browser on the machine running it.
36
36
 
37
- import { authDisplayPath, hostedStatus, login as hostedLogin, readAuthFile } from "./auth.mjs";
37
+ import { authDisplayPath, hostedStatus, isMixedRecord, login as hostedLogin, readAuthFile } from "./auth.mjs";
38
38
  import { projectMcpServerKey } from "./project-mcp.mjs";
39
39
  import { execProbe, runInteractive } from "./detect.mjs";
40
40
  import { compareVersions } from "./update.mjs";
@@ -102,13 +102,15 @@ export const AGENT_CONNECT_HINT = {
102
102
  * Mirrors the order `hostedToken` (lib/auth.mjs) checks in, but returns the
103
103
  * raw token rather than a possibly-refreshed OAuth pair: what this needs is
104
104
  * a bearer worth handing an agent's OWN config, not this process's own call.
105
+ * A record an older bridge left holding a browser sign-in too hands out
106
+ * nothing (#8324): its personal token may be another account's.
105
107
  * `readAuth` is the injection point every test in this file uses. */
106
108
  export async function personalBoardToken({ env = process.env, readAuth = readAuthFile } = {}) {
107
109
  // Compatibility read: old installs may still set GLYTCH_BOARD_TOKEN (#2196).
108
110
  const scripted = typeof (env.VIEWABLE_BOARD_TOKEN ?? env.GLYTCH_BOARD_TOKEN) === "string" ? (env.VIEWABLE_BOARD_TOKEN ?? env.GLYTCH_BOARD_TOKEN).trim() : "";
109
111
  if (scripted !== "") return scripted;
110
112
  const stored = await readAuth(env);
111
- if (stored?.personal === true && typeof stored.accessToken === "string" && stored.accessToken.trim() !== "") {
113
+ if (stored?.personal === true && !isMixedRecord(stored) && typeof stored.accessToken === "string" && stored.accessToken.trim() !== "") {
112
114
  return stored.accessToken.trim();
113
115
  }
114
116
  return null;
@@ -216,7 +218,13 @@ export async function signInStep({
216
218
  }
217
219
 
218
220
  const current = await status(env);
219
- if (current?.signedIn) {
221
+ // A sign-in that cannot reach the board is not "already signed in": a
222
+ // refused or expired one, or a record an older bridge left holding two
223
+ // kinds of sign-in that hostedToken never uses (#8324). Each needs a new
224
+ // sign-in. A renewal that got no answer is still being retried by the
225
+ // runner itself and was never refused (#8221), so it stands.
226
+ const usable = current?.signedIn && !(current.dead === true && current.deadReason !== "refresh_uncertain");
227
+ if (usable) {
220
228
  return settle("ok", `already signed in (${current.via ?? "credential on file"})`);
221
229
  }
222
230
  if (skip) {
@@ -103,7 +103,10 @@ export async function resumeLateMessages(project, settings, log = () => {}) {
103
103
  try {
104
104
  const callTool = (name, args, opts) => (settings.hostedCallTool ?? callRunnerTool)(name, args, { ...opts, sessionBoardId: run.board_id });
105
105
  await promoteLateRows(project.path, run.id, {
106
- poller: { since: () => 0, hasDelivered: () => true }, // question answers belong to their existing consumer
106
+ // Question answers belong to their existing consumer: the session while it
107
+ // runs, then the app (an answer it never took starts the agent there,
108
+ // resumeAnswered.ts untakenAnswers, #8122), never a late resume.
109
+ poller: { since: () => 0, hasDelivered: () => true },
107
110
  callTool, sessionKey: run.session_key ?? run.id, env: settings.env,
108
111
  messageLimit: 1,
109
112
  promote: async (root, id, reply, logger, promotionId) => {
package/lib/mcpjson.mjs CHANGED
@@ -191,10 +191,108 @@ export function moveRetiredUrl(entry, env) {
191
191
  * same "is this ours" answer the merge itself does. */
192
192
  export function boardEntryIsOurs(entry, env) {
193
193
  if (!isObject(entry)) return false;
194
- if (isLegacyBoardCommand(entry.command, entry.args)) return true;
194
+ // opencode spells a spawned command as one array (#7550: one copy of this
195
+ // check, read by .mcp.json, Codex and opencode alike).
196
+ const [command, args] = Array.isArray(entry.command) ? [entry.command[0], entry.command.slice(1)] : [entry.command, entry.args];
197
+ if (isLegacyBoardCommand(command, args)) return true;
195
198
  return typeof entry.url === "string" && (entry.url === BOARD_MCP_URL(env) || RETIRED_BOARD_MCP_URLS.includes(entry.url));
196
199
  }
197
200
 
201
+ // ANOTHER VIEWABLE BOARD SERVER IS NEVER LOADED BESIDE A RUN'S OWN (#7550).
202
+ // A person's own Claude Code, Codex or opencode may hold a board server of
203
+ // its own (a `viewable init` entry, a claude.ai connector, a plugin), signed
204
+ // in to the same account or another one. With the person's apps on, that
205
+ // server loaded next to the run's, offered the same tools, and the model
206
+ // picked it: an ask never reached the run's board, and one Allow wrote to
207
+ // another account's boards. Every engine asks this one question before a
208
+ // server loads, and Claude's permission step asks it again of every call.
209
+ export const BOARD_SERVER_NAMES = ["glytch", "viewable", "board"];
210
+ /** Tools only the board offers (supabase/functions/board-mcp/tools.mjs). A
211
+ * call to one on any server but the run's own is refused. `search`, `fetch`,
212
+ * `mark` and `send_message` are left out: other apps have tools by those names. */
213
+ export const BOARD_ONLY_TOOLS = [
214
+ "get_board", "get_node", "get_library", "propose", "open_session", "close_session", "collect_session",
215
+ "set_brief_status", "ask_user", "check_answer", "list_sessions", "report", "get_log", "import_chats",
216
+ "send_review", "check_review", "list_reviews", "reply_review", "prepare_page_upload", "prepare_picture_upload",
217
+ "set_live_card", "put_on_hub", "get_hub", "create_board",
218
+ ];
219
+ const BOARD_HOSTS = ["viewable.one", ...RETIRED_APP_URLS.map((origin) => new URL(origin).hostname)];
220
+
221
+ /** A server name with the prefixes the engines add taken off and folded to
222
+ * one case: `claude.ai Viewable` (a connector), `claude_ai_Viewable` (the
223
+ * same in a tool name), `plugin:x:glytch` and `plugin_x_glytch` (a plugin's). */
224
+ function plainServerName(name) {
225
+ return String(name ?? "").trim().toLowerCase()
226
+ .replace(/^claude[._\s-]ai[._\s-]+/, "")
227
+ .replace(/^plugin[:_][^:]*[:_]/, "");
228
+ }
229
+
230
+ /** Is this name one a board server goes by? */
231
+ export function isBoardServerName(name) {
232
+ return BOARD_SERVER_NAMES.includes(plainServerName(name));
233
+ }
234
+
235
+ /** Is this address a Viewable board endpoint: any viewable.one or retired
236
+ * host, the address this run is pointed at, or the board function's path? */
237
+ export function isBoardAddress(value, env = process.env) {
238
+ if (typeof value !== "string" || value.trim() === "") return false;
239
+ let url;
240
+ try { url = new URL(value.trim()); } catch { return false; }
241
+ const host = url.hostname.toLowerCase().replace(/\.+$/, "");
242
+ if (BOARD_HOSTS.some((board) => host === board || host.endsWith(`.${board}`))) return true;
243
+ if (/\/board-mcp\/*$/i.test(url.pathname)) return true;
244
+ try {
245
+ const ours = new URL(BOARD_MCP_URL(env));
246
+ return ours.host === url.host && ours.pathname.replace(/\/+$/, "") === url.pathname.replace(/\/+$/, "");
247
+ } catch { return false; }
248
+ }
249
+
250
+ /** Do these tool names have the board's shape (its three core tools)? */
251
+ export function hasBoardTools(tools) {
252
+ const names = new Set((Array.isArray(tools) ? tools : Object.keys(tools ?? {})).map((name) => String(name).split("__").at(-1)));
253
+ return ["get_board", "ask_user", "report"].every((name) => names.has(name));
254
+ }
255
+
256
+ /** Is this server a Viewable board server, by its name, its address or
257
+ * command, or (when its tools are known) their shape? `entry` is the
258
+ * server's config in any engine's shape (`url`, `command`/`args`, or
259
+ * opencode's command array); `tools` its tool names when listed. The run's
260
+ * own server is the caller's to exempt, by its key. */
261
+ export function isBoardServer(name, entry, { env = process.env, tools } = {}) {
262
+ if (isBoardServerName(name)) return true;
263
+ if (isObject(entry)) {
264
+ if (boardEntryIsOurs(entry, env) || isBoardAddress(entry.url, env) || isBoardAddress(entry.serverUrl, env)) return true;
265
+ const [command, args] = Array.isArray(entry.command) ? [entry.command[0], entry.command.slice(1)] : [entry.command, entry.args];
266
+ const words = [command, ...(Array.isArray(args) ? args : [])].filter((word) => typeof word === "string");
267
+ // `viewable mcp`, `npx viewable-one mcp`: the package's own server, spawned.
268
+ if (words.some((word) => /(^|[\\/])(viewable|viewable-one|glytch)(\.mjs|\.cmd)?$/i.test(word)) && words.includes("mcp")) return true;
269
+ if (words.some((word) => isBoardAddress(word, env))) return true;
270
+ }
271
+ return tools !== undefined && hasBoardTools(tools);
272
+ }
273
+
274
+ /** Claude's name for a call's server: `mcp__<server>__<tool>`, or the
275
+ * `server` a resource tool names in its input. Null for any other tool. */
276
+ function calledServer(toolName, input) {
277
+ const name = String(toolName ?? "");
278
+ const match = /^mcp__(.+?)__(.+)$/.exec(name);
279
+ if (match) return { server: match[1], tool: match[2] };
280
+ if (/^(ReadMcpResourceTool|ListMcpResourcesTool)$/.test(name) && typeof input?.server === "string") return { server: input.server, tool: "" };
281
+ return null;
282
+ }
283
+
284
+ /** Why a Claude tool call reaches another board server, or null when it does
285
+ * not (#7550). `own` is the run's board server key. A call is refused when
286
+ * its server is not `own` and the server goes by a board name or the tool is
287
+ * one only the board has; a resource read naming such a server too. */
288
+ export function otherBoardCall(toolName, input, { own } = {}) {
289
+ const called = calledServer(toolName, input);
290
+ if (!called || (own && called.server === own)) return null;
291
+ if (isBoardServerName(called.server)) return { server: called.server, tool: called.tool };
292
+ if (called.tool && BOARD_ONLY_TOOLS.includes(called.tool)) return { server: called.server, tool: called.tool };
293
+ return null;
294
+ }
295
+
198
296
  /** Decide what to write, given whatever is on disk (null = no file).
199
297
  *
200
298
  * Returns one of:
@@ -41,9 +41,10 @@ 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
- import { readRegistryChecked, registryPath } from "./registry.mjs";
47
+ import { readRegistryChecked, registryPath, withoutRemoved } from "./registry.mjs";
47
48
  import { watch, newRunnerId } from "./runner.mjs";
48
49
  import { RUNNER_BEAT_MS } from "./spawn.mjs";
49
50
  import { makeHeartbeatHub, makeRegistrar, REGISTER_REFRESH_MS } from "./runnerPace.mjs";
@@ -93,7 +94,7 @@ export async function watchRegistered({
93
94
  folders,
94
95
  sweep = sweepAll,
95
96
  sync = syncFolder,
96
- updater = makeUpdateChecker({ log }),
97
+ updater: injectedUpdater,
97
98
  // WHAT CODING AGENTS THIS MACHINE HAS (brief 19 stage 2). Same shape as
98
99
  // `updater`: a cache with its own clock, so the liveness beat never waits
99
100
  // on `claude --version`. Injected for the tests, which must not spawn three
@@ -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
@@ -124,6 +129,9 @@ export async function watchRegistered({
124
129
  const restartStop = new AbortController();
125
130
  const signal = outerSignal ? AbortSignal.any([outerSignal, restartStop.signal]) : restartStop.signal;
126
131
  let restarting = false;
132
+ // The daily npm lookup stops with the watch: Ctrl-C must not leave it
133
+ // writing npm's cache after the runner is gone (#7557).
134
+ const updater = injectedUpdater ?? makeUpdateChecker({ log, signal });
127
135
  // An injected list is the whole list: a caller that says which folders to
128
136
  // watch is not asking the registry anything, so the live re-read below
129
137
  // stands down for it. Nothing in the package passes this; the tests do.
@@ -135,7 +143,9 @@ export async function watchRegistered({
135
143
  // rewrite that keeps the same folders is `glytch init` asking for a beat.
136
144
  const registryStamp = async () => (await stat(registryPath(env)).catch(() => null))?.mtimeMs ?? null;
137
145
  let stampSeen = pinned ? null : await registryStamp();
138
- const registered = folders ?? (await readRegistryChecked(env)).folders;
146
+ // A restart reads the list the same way a re-read does: a listed folder
147
+ // that has a removal mark stays unwatched (#8325).
148
+ const registered = folders ?? await withoutRemoved((await readRegistryChecked(env)).folders, env);
139
149
  const watched = [];
140
150
  const missing = [];
141
151
  const first = [];
@@ -194,6 +204,14 @@ export async function watchRegistered({
194
204
  // first mark a person sees already carries the `agents` block rather than
195
205
  // arriving bare and filling in a beat later.
196
206
  await probe.once();
207
+ // And the programs chosen for each folder, for the same reason: a board
208
+ // that files a run before this arrives would pick one the person did not
209
+ // choose (#6704).
210
+ // `joining` holds the folders a registry re-read is about to start, so their
211
+ // choice is read before their watcher's first register.
212
+ let joining = [];
213
+ const chosen = choices ?? makeChoiceMark({ folders: () => [...first, ...watched, ...joining], log });
214
+ await chosen.refresh();
197
215
 
198
216
  // The mark file gains `version`, `updateAvailable`, `agents` and (brief 21
199
217
  // session 5, ruling 3A) `platform` here, and only here: `watch()`
@@ -240,7 +258,7 @@ export async function watchRegistered({
240
258
  holdsRuns: () => selfUpdater.holdsRuns(),
241
259
  claimStarted: () => selfUpdater.claimStarted(),
242
260
  };
243
- const markExtra = () => ({ ...platform, ...updater.mark(), ...probe.mark(), ...health.mark(), ...selfUpdater.mark() });
261
+ const markExtra = () => ({ ...platform, ...updater.mark(), ...probe.mark(), ...chosen.mark(), ...health.mark(), ...selfUpdater.mark() });
244
262
 
245
263
  // ONE REGISTER AND ONE HEARTBEAT FOR THE WHOLE PROCESS (ticket e8,
246
264
  // 2026-10-03; #616, 2026-10-16). Every folder's beat registers the whole
@@ -388,7 +406,7 @@ export async function watchRegistered({
388
406
  const stamp = await registryStamp();
389
407
  const rewritten = stamp !== null && stamp !== stampSeen;
390
408
  stampSeen = stamp;
391
- const { folders: now, ok } = await readRegistryChecked(env);
409
+ const { folders: listed, ok } = await readRegistryChecked(env);
392
410
  if (!ok) {
393
411
  // A REGISTRY WE CANNOT READ IS NOT NEWS. Half-written, hand-edited
394
412
  // into invalid JSON, briefly absent: none of those mean the folders
@@ -402,6 +420,9 @@ export async function watchRegistered({
402
420
  continue;
403
421
  }
404
422
  complained = false;
423
+ // A folder the person removed stays unwatched even when a stray write
424
+ // put it back in the list (#8325): only an explicit add clears the mark.
425
+ const now = await withoutRemoved(listed, env);
405
426
  const wanted = new Set(now);
406
427
  for (const [folder, entry] of running) {
407
428
  if (wanted.has(folder) || entry.leaving) continue;
@@ -411,6 +432,7 @@ export async function watchRegistered({
411
432
  log(`${folder} left the registry - stopping its watcher`);
412
433
  entry.controller.abort();
413
434
  }
435
+ const joined = [];
414
436
  for (const folder of now) {
415
437
  if (running.has(folder)) continue;
416
438
  if (!(await isDir(folder))) {
@@ -424,8 +446,17 @@ export async function watchRegistered({
424
446
  announcedMissing.delete(folder);
425
447
  log(`${folder} joined the registry - syncing and watching it`);
426
448
  await syncOne(folder);
427
- startFolder(folder);
449
+ joined.push(folder);
428
450
  }
451
+ // The choices are read before a joining folder is watched (its first
452
+ // register would otherwise say none, and a run filed then would take
453
+ // another program), and before the beat a rewritten list asks for:
454
+ // setup choosing a program writes the list again (#6704).
455
+ if (joined.length > 0 || rewritten) {
456
+ joining = joined;
457
+ try { await chosen.refresh(); } finally { joining = []; }
458
+ }
459
+ for (const folder of joined) startFolder(folder);
429
460
  if (rewritten) askBeat();
430
461
  } while (refreshAgain);
431
462
  } catch (error) {