viewable-one 0.12.2 → 0.12.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/CHANGELOG.md +79 -0
  2. package/README.md +2 -2
  3. package/SPAWN.md +107 -53
  4. package/glytch.mjs +49 -12
  5. package/lib/acp.mjs +110 -148
  6. package/lib/admission.mjs +25 -5
  7. package/lib/agents.mjs +59 -16
  8. package/lib/answerTag.mjs +47 -0
  9. package/lib/atomic.mjs +1 -16
  10. package/lib/auth.mjs +25 -9
  11. package/lib/boardside.mjs +28 -12
  12. package/lib/child.mjs +89 -116
  13. package/lib/claudeModels.mjs +168 -0
  14. package/lib/codex-rpc.mjs +2 -2
  15. package/lib/codex.mjs +43 -63
  16. package/lib/codexApps.mjs +5 -3
  17. package/lib/codexToolInputs.mjs +98 -22
  18. package/lib/codingChecks.mjs +8 -4
  19. package/lib/conversationRules.mjs +46 -6
  20. package/lib/detect.mjs +14 -23
  21. package/lib/devserver.mjs +6 -6
  22. package/lib/doctor.mjs +4 -2
  23. package/lib/folderReads.mjs +96 -0
  24. package/lib/followUps.mjs +170 -0
  25. package/lib/hosted.mjs +13 -4
  26. package/lib/init-connect.mjs +29 -10
  27. package/lib/lateResume.mjs +135 -0
  28. package/lib/logindaemon.mjs +113 -33
  29. package/lib/mcpjson.mjs +35 -2
  30. package/lib/multiwatch.mjs +80 -45
  31. package/lib/pagePictures.mjs +14 -11
  32. package/lib/paths.mjs +0 -1
  33. package/lib/permissionAsk.mjs +341 -58
  34. package/lib/procs.mjs +73 -2
  35. package/lib/refusal.mjs +0 -2
  36. package/lib/restartPass.mjs +52 -11
  37. package/lib/rowsAnswers.mjs +18 -34
  38. package/lib/rowsEvents.mjs +20 -2
  39. package/lib/runner-health.mjs +26 -2
  40. package/lib/runner.mjs +106 -1363
  41. package/lib/runnerAdmission.mjs +33 -12
  42. package/lib/runnerApi.mjs +28 -12
  43. package/lib/runnerBeat.mjs +398 -0
  44. package/lib/runnerCompletion.mjs +5 -2
  45. package/lib/runnerExecute.mjs +227 -0
  46. package/lib/runnerGates.mjs +338 -0
  47. package/lib/runnerLaunch.mjs +351 -0
  48. package/lib/runnerLease.mjs +31 -9
  49. package/lib/runnerOps.mjs +226 -0
  50. package/lib/runnerPace.mjs +10 -6
  51. package/lib/runnerRecovery.mjs +457 -0
  52. package/lib/runnerRegister.mjs +29 -8
  53. package/lib/runnerSettlement.mjs +29 -9
  54. package/lib/selfUninstall.mjs +239 -0
  55. package/lib/spawn.mjs +0 -5
  56. package/lib/sync.mjs +26 -14
  57. package/lib/update.mjs +184 -0
  58. package/lib/viewableFolder.mjs +8 -2
  59. package/lib/worktree.mjs +66 -13
  60. package/lib/writePolicy.mjs +90 -10
  61. package/package.json +1 -1
@@ -11,12 +11,31 @@ export function conversationRules(spec, ask) {
11
11
  "A person can write to you while you work. Their note arrives as " +
12
12
  "`[message from <name>] <text>`. Answer them by calling " +
13
13
  `${spec.boardTool("propose")} with an addComment op and no id: it lands in the ` +
14
- "conversation on your own idea as your reply. Do that only for an answer " +
15
- "the person is waiting on. When you finish, your closing message is filed " +
16
- "for you, with the figures, and do not file a second reply of your own. " +
17
- "Start it with one sentence of what changed, then at most three short " +
14
+ "conversation on your own idea as your reply. Do that only to answer a " +
15
+ "note from a person, never to report progress: no \"step 1\", no \"working " +
16
+ "on it\", no status. Your plan and your session log are where progress " +
17
+ "lives. When you finish, your closing message is filed for you, with the " +
18
+ "figures, and it is the one reply of the run: do not file a second reply " +
19
+ "of your own, and never repeat the answer in a comment. The one " +
20
+ "exception is a screenshot of a change a person can see, below. " +
21
+ "If the task asks you to put something on the board (an idea, a note, a " +
22
+ "card), the text you put there holds the answer itself, such as " +
23
+ "\"12 x 34 = 408\", never a line that says where the answer is or why " +
24
+ "you could not show it. " +
25
+ "Put the complete answer for the person inside <viewable-answer> and " +
26
+ "</viewable-answer> in your final response. The runner puts only that " +
27
+ "answer on the idea card. Keep any repository-required session sign-off, " +
28
+ "test notes or handoff outside those tags; they stay in the session log. " +
29
+ "For a question or research request, give the actual answer, preserving " +
30
+ "its requested format (such as Steps, a Table or a Chart), not a report " +
31
+ "about having answered it. For a code change, start the answer with one " +
32
+ "sentence of what changed, then at most three short " +
18
33
  "lines as a `- ` list that someone who does not write code can read: no " +
19
- "file names, no code.\n\n" +
34
+ "file names, no code. The answer and every comment hold at most 280 " +
35
+ "characters: longer text is split into linked ideas beside the card, one " +
36
+ "more for each 280, so keep to the point and leave detail in the session " +
37
+ "log. Every piece holds part of the answer itself, never a line that " +
38
+ "says where the answer is.\n\n" +
20
39
  "When you change something a person can see, attach a screenshot of it to " +
21
40
  "an addComment (it takes `images`, up to 6 data URLs of PNG, JPEG, GIF or " +
22
41
  `WebP). When you are choosing between looks, ask with ${ask} and pass ` +
@@ -25,7 +44,28 @@ export function conversationRules(spec, ask) {
25
44
  "of the folder you work in, naming that page's address and what a person " +
26
45
  "calls it, like `{\"path\": \"/settings\", \"name\": \"settings page\"}`. " +
27
46
  "The runner opens that page for its Before and After pictures; the file " +
28
- "is never committed.\n\n"
47
+ "is never committed.\n\n" +
48
+ otherAppsRule()
49
+ );
50
+ }
51
+
52
+ // A RUN NEVER CLICKS OR TYPES INSIDE ANOTHER APP (#4204, #4273). It opens
53
+ // apps, runs commands and works on files; a task that needs a button pressed
54
+ // gets this plain answer. Words alone do not stop it, so agents.mjs also bars
55
+ // the click and screen commands for Claude Code (CLAUDE_CLICK_AND_SCREEN_TOOLS).
56
+ // This sits beside computerAppsOffRule without overlapping it: that rule is
57
+ // about reaching the person's own data (email, calendar) through the apps
58
+ // switch; this one is about driving a window, and opening an app
59
+ // (`open -a <App>`) is a command that neither rule covers or forbids.
60
+ export const OTHER_APPS_SENTENCE = "I can't press buttons inside other apps.";
61
+ export function otherAppsRule() {
62
+ return (
63
+ "Never click, type into or drive another app's window, and never take a " +
64
+ "picture of the screen to do it: no osascript, cliclick or screencapture, " +
65
+ "and no other way to press buttons or send keystrokes. You may open an app " +
66
+ "(`open -a <App>`), run commands and work on files. If the task needs a " +
67
+ `button pressed inside another app, say "${OTHER_APPS_SENTENCE}" and do ` +
68
+ "what can be done with commands or files.\n\n"
29
69
  );
30
70
  }
31
71
 
package/lib/detect.mjs CHANGED
@@ -23,6 +23,7 @@
23
23
  // list is what a PERSON would install, and AGENTS stays what a runner can
24
24
  // spawn. They are different questions.
25
25
 
26
+ import { discoverClaudeModels, readClaudeModels } from "./claudeModels.mjs";
26
27
  import { discoverCodex } from "./codex-rpc.mjs";
27
28
  import { execFile, spawn } from "node:child_process";
28
29
  import { existsSync } from "node:fs";
@@ -133,31 +134,12 @@ function lastUsablePath(stdout, { exists }) {
133
134
  return null;
134
135
  }
135
136
 
136
- /** `command -v <bin>` under the person's own login shell, asked at most ONCE
137
- * PER (shell, bin) FOR THE LIFE OF THIS PROCESS: a login shell can be slow
138
- * to start (nvm, a heavy `.zshrc`), a daemon asks this for at most a small
139
- * handful of names (one per engine it ever tries to spawn), and every
140
- * request after the first must not pay for a shell spawn it already has the
141
- * answer to. Returns `null` on any failure - no `$SHELL` in this
142
- * environment, the shell exits non-zero, the binary really is not on that
143
- * PATH either - never throws: "could not resolve" is the caller's fact to
144
- * report, not this function's to raise.
145
- *
146
- * TWO SHELLS, NOT ONE (2026-09-21, review): `$SHELL -lc` runs a login shell
147
- * but NOT an interactive one, and a non-interactive login zsh does not read
148
- * `.zshrc` - which is exactly where most macOS PATH additions (nvm, `npm
149
- * install -g`, bun) live. `-lc` alone answered `null` on the machine this
150
- * whole file was written for. When `-lc` comes back with nothing usable,
151
- * this retries once with `-ilc` (interactive login), which does read
152
- * `.zshrc`. Both spawns carry the same `timeoutMs` guard - an interactive
153
- * shell is the slower of the two to start, not a reason to wait longer for
154
- * it. */
155
- const loginShellCache = new Map();
137
+ /** Ask the current login profile each time. Updates can move either engine
138
+ * between Node versions while this process keeps running. Retry interactively
139
+ * for nvm/fnm configured in .zshrc; both attempts retain the probe timeout. */
156
140
  export async function loginShellWhich(bin, { env = process.env, execImpl = execFile, timeoutMs = PROBE_TIMEOUT_MS, exists = existsSync } = {}) {
157
141
  const shell = env.SHELL?.trim();
158
142
  if (!shell) return null;
159
- const key = `${shell}::${bin}`;
160
- if (loginShellCache.has(key)) return loginShellCache.get(key);
161
143
 
162
144
  const runShell = (flag) => new Promise((resolve) => {
163
145
  try {
@@ -174,7 +156,6 @@ export async function loginShellWhich(bin, { env = process.env, execImpl = execF
174
156
 
175
157
  let found = await runShell("-lc");
176
158
  if (!found) found = await runShell("-ilc");
177
- loginShellCache.set(key, found);
178
159
  return found;
179
160
  }
180
161
 
@@ -588,6 +569,7 @@ export const PROBE_INTERVAL_MS = 5 * 60_000;
588
569
  */
589
570
  export function makeAgentProbe({
590
571
  detect = detectAgents,
572
+ claudeDiscover = detect === detectAgents ? discoverClaudeModels : null,
591
573
  env = process.env,
592
574
  intervalMs = PROBE_INTERVAL_MS,
593
575
  now = () => Date.now(),
@@ -604,6 +586,14 @@ export function makeAgentProbe({
604
586
  checkedAt = now();
605
587
  try {
606
588
  known = await detect({ env });
589
+ if (claudeDiscover && known.claude) {
590
+ // Model checks can take a minute. Start watching now so setup's
591
+ // health check sees the first heartbeat; mark() reads results later.
592
+ const claude = known.claude;
593
+ void resolveAgentBinary(env.PM_CLAUDE_BIN?.trim() || "claude", { env })
594
+ .then((resolved) => claudeDiscover(claude, { bin: resolved.path, env, log }))
595
+ .catch((error) => log(`Claude model discovery failed: ${error instanceof Error ? error.message : String(error)}`));
596
+ }
607
597
  } catch (error) {
608
598
  // Never take the beat down for a probe. An empty block is honest here:
609
599
  // nothing was learned, so nothing is claimed.
@@ -618,6 +608,7 @@ export function makeAgentProbe({
618
608
  /** What goes into the mark file, plus a refresh when one is due. */
619
609
  mark() {
620
610
  if (!running && (checkedAt === null || now() - checkedAt >= intervalMs)) void run();
611
+ if (claudeDiscover && known?.claude?.found) known.claude.resolvedModels = readClaudeModels(known.claude.version, env);
621
612
  return known === null ? {} : { agents: { ...known } };
622
613
  },
623
614
  /** Await one probe. The daemon's start, `doctor`, and the tests use this. */
package/lib/devserver.mjs CHANGED
@@ -227,7 +227,7 @@ const cimRowFor = async (pid) => parseCimProcess(await run("powershell.exe", cim
227
227
 
228
228
  const netstatListeners = async (port) => parseNetstatListeners(await run("netstat", ["-ano"], 15_000), port);
229
229
 
230
- const defaultPs = (pid) => (process.platform === "win32" ? cimRowFor(pid) : psRowFor(pid));
230
+ export const readProcessIdentity = (pid) => (process.platform === "win32" ? cimRowFor(pid) : psRowFor(pid));
231
231
  const defaultListeners = (port) => (process.platform === "win32" ? netstatListeners(port) : lsofListeners(port));
232
232
 
233
233
  const parentPidFor = async (pid) => {
@@ -244,7 +244,7 @@ const parentPidFor = async (pid) => {
244
244
  * takes its port. Every listener must belong to this recorded process tree;
245
245
  * missing process inspection is a refusal, never a command-line fallback. */
246
246
  export async function verifyPreviewServer(record, {
247
- ps = defaultPs, listeners = defaultListeners, parentPid = parentPidFor,
247
+ ps = readProcessIdentity, listeners = defaultListeners, parentPid = parentPidFor,
248
248
  } = {}) {
249
249
  const pid = Number(record?.pid);
250
250
  const port = Number(record?.port);
@@ -313,7 +313,7 @@ const normaliseCommand = (value) =>
313
313
  *
314
314
  * `ps` and `listeners` are injected so the decision can be tested without a
315
315
  * machine's process table under it. */
316
- export async function verifyRecordedServer(record, { ps = defaultPs, listeners = defaultListeners } = {}) {
316
+ export async function verifyRecordedServer(record, { ps = readProcessIdentity, listeners = defaultListeners } = {}) {
317
317
  const pid = Number(record?.pid);
318
318
  if (!Number.isFinite(pid) || pid <= 1) return { ours: false, reason: "no usable pid in the record" };
319
319
 
@@ -388,7 +388,7 @@ export async function stopRecordedServer(record, { graceMs = 3_000, sleep = (ms)
388
388
  // OVER ROWS, 2026-09-11 (brief 30 Move 2b): the app asks with a `run_ops` row
389
389
  // of `kind:"relaunch"` now, surfaced by `heartbeat`'s `ops`, claimed with
390
390
  // `opTake`, answered with `opResult` (updatable - the button can be pressed
391
- // again) - `bridge/lib/runner.mjs`'s `serviceRowOps` is the runner's half.
391
+ // again) - `bridge/lib/runnerOps.mjs`'s `serviceRowOps` is the runner's half.
392
392
  // `relaunchServer` below is the pure core, unchanged in what it decides;
393
393
  // what moved is where the RECORD comes from and where the OUTCOME goes.
394
394
  // Before this pass both were the mailbox: `<id>.server` (a mirror of the
@@ -493,7 +493,7 @@ const stillAlive = (pid) => {
493
493
  *
494
494
  * `record` is the run row's own `server` column, or `null` when the row has
495
495
  * none yet (a session that started no server) - the caller
496
- * (`bridge/lib/runner.mjs`'s `serviceRowOps`) falls back to
496
+ * (`bridge/lib/runnerOps.mjs`'s `serviceRowOps`) falls back to
497
497
  * `readWorktreeRecord(hinted)` when the row is empty but the op's payload
498
498
  * carries a `worktreePath` hint, exactly as the file-based signal used to.
499
499
  *
@@ -521,7 +521,7 @@ export async function relaunchServer(
521
521
  spawn = defaultSpawn,
522
522
  exists = defaultExists,
523
523
  listeners = defaultListeners,
524
- ps = defaultPs,
524
+ ps = readProcessIdentity,
525
525
  settleMs = RELAUNCH_SETTLE_MS,
526
526
  sleep = (ms) => new Promise((r) => setTimeout(r, ms)),
527
527
  now = () => new Date(),
package/lib/doctor.mjs CHANGED
@@ -338,7 +338,7 @@ export async function doctorRows(
338
338
  // and whose reason is wrong is worse than one that just says the
339
339
  // state: it sends someone looking for a file that was never written.
340
340
  ? row("login", "Claude Code login", true, "logged in", "a stored credential was found: the login Keychain on macOS, ~/.claude/.credentials.json elsewhere")
341
- : row("login", "Claude Code login", false, "logged out", "run `claude` once and log in, or sessions fail at spawn"),
341
+ : row("login", "Claude Code login", false, "logged out", "run `claude auth login` to sign in, or sessions fail at spawn"),
342
342
  );
343
343
 
344
344
  // ONE ROW (brief 30, W2a): the local stdio MCP server is retired, and
@@ -441,7 +441,9 @@ export async function doctorRows(
441
441
 
442
442
  const newestPublished = await latest().catch(() => null);
443
443
  rows.push(
444
- newestPublished === null
444
+ compareVersions(version, "0.12.0") < 0
445
+ ? row("version", "version", false, "too old", `${version} installed; the board requires 0.12.0 or newer. Run npm i -g viewable-one@latest --force, then viewable update to restart and reconnect.`, "Run npm i -g viewable-one@latest --force, then viewable update.")
446
+ : newestPublished === null
445
447
  ? row("version", "version", true, "unknown", `${version} installed; npm did not answer (offline?)`)
446
448
  : compareVersions(newestPublished, version) > 0
447
449
  ? row("version", "version", true, "update available", `${version} installed, ${newestPublished} on npm: npm i -g viewable-one@latest --force`)
@@ -0,0 +1,96 @@
1
+ // #3703 (ruling #3847): one folder link. The Folder panel asks for a
2
+ // connected folder's file list, or one file's bytes, and the runner answers
3
+ // from disk. Read only: nothing here writes, runs or follows a link out of
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.
7
+ import { lstat, readdir, readFile, realpath } from "node:fs/promises";
8
+ import { join, relative, resolve, sep } from "node:path";
9
+
10
+ const SKIP_DIRS = new Set(["node_modules", "dist"]);
11
+ // src/folder/import.ts TEXT_EXTENSIONS plus the documents docReader.ts reads.
12
+ const READABLE = new Set([
13
+ "txt", "md", "markdown", "csv", "tsv", "json", "yaml", "yml", "toml",
14
+ "js", "jsx", "ts", "tsx", "py", "rb", "go", "rs", "java", "kt", "swift",
15
+ "c", "h", "cpp", "hpp", "cs", "php", "sh", "zsh", "bash", "sql",
16
+ "html", "htm", "css", "scss", "xml", "svg", "ini", "env", "cfg", "conf",
17
+ "log", "tex", "rst", "org", "pdf", "docx", "xlsx",
18
+ ]);
19
+ export const FOLDER_LIST_MAX = 20_000;
20
+ export const FOLDER_FILE_MAX_BYTES = 4_000_000;
21
+
22
+ const readable = (name) => {
23
+ const dot = name.lastIndexOf(".");
24
+ return dot >= 0 && READABLE.has(name.slice(dot + 1).toLowerCase());
25
+ };
26
+ const skipped = (name) => name.startsWith(".") || SKIP_DIRS.has(name);
27
+
28
+ /** Every readable file under `root`, with the directories that hold one,
29
+ * depth first, directories before files. Links are not followed. */
30
+ export async function listFolder(root, max = FOLDER_LIST_MAX) {
31
+ const entries = [];
32
+ let truncated = false;
33
+ const walk = async (dir, prefix) => {
34
+ let children;
35
+ try { children = await readdir(dir, { withFileTypes: true }); }
36
+ catch { return; }
37
+ children.sort((a, b) => a.isDirectory() === b.isDirectory()
38
+ ? a.name.localeCompare(b.name) : a.isDirectory() ? -1 : 1);
39
+ for (const child of children) {
40
+ if (entries.length >= max) { truncated = true; return; }
41
+ if (child.isDirectory()) {
42
+ if (skipped(child.name)) continue;
43
+ const at = entries.length;
44
+ entries.push({ path: `${prefix}${child.name}/`, dir: true });
45
+ await walk(join(dir, child.name), `${prefix}${child.name}/`);
46
+ // A directory holding nothing readable is dropped, as listFolderDeep does.
47
+ if (entries.length === at + 1) entries.pop();
48
+ } else if (child.isFile() && readable(child.name)) {
49
+ entries.push({ path: `${prefix}${child.name}`, dir: false });
50
+ }
51
+ }
52
+ };
53
+ await walk(root, "");
54
+ return { entries, truncated };
55
+ }
56
+
57
+ /** One file's bytes, refused when it is outside `root`, a link, unreadable
58
+ * by the app or too large. The answer's `error` is one sentence. */
59
+ export async function readFolderFileBytes(root, path, maxBytes = FOLDER_FILE_MAX_BYTES) {
60
+ if (typeof path !== "string" || path === "" || path.startsWith("/") || /(^|\/)\.\.(\/|$)/.test(path) || path.includes("\\")) {
61
+ return { error: "That file is not in this folder." };
62
+ }
63
+ const name = path.split("/").pop() ?? path;
64
+ if (!readable(name)) return { error: `${name} is not a text, PDF, Word or Excel file.` };
65
+ try {
66
+ const base = await realpath(root);
67
+ const target = resolve(base, ...path.split("/"));
68
+ const info = await lstat(target);
69
+ if (!info.isFile()) return { error: `${name} is not a file in this folder.` };
70
+ const real = await realpath(target);
71
+ const inside = relative(base, real);
72
+ if (inside === "" || inside.startsWith("..") || inside.startsWith(sep)) return { error: "That file is not in this folder." };
73
+ if (info.size > maxBytes) return { error: `${name} is over ${Math.round(maxBytes / 1_000_000)}MB, too large to read from your computer.` };
74
+ const bytes = await readFile(real);
75
+ return { base64: bytes.toString("base64"), modified: Math.round(info.mtimeMs) };
76
+ } catch (error) {
77
+ if (error?.code === "ENOENT") return { error: `${path} was moved or deleted.` };
78
+ return { error: `Could not read ${path}. Try again.` };
79
+ }
80
+ }
81
+
82
+ /** Take one `folder-read` op from the heartbeat and write its answer. */
83
+ export async function serviceFolderRead(root, project, op, api, options) {
84
+ if (op.project_id !== project.id) return false;
85
+ const args = { projectId: project.id, requestId: op.id };
86
+ const taken = await api.folderReadTake(args, options);
87
+ if (!taken.ok || !taken.taken) return taken.ok;
88
+ const path = typeof taken.path === "string" ? taken.path : "";
89
+ let result;
90
+ try { result = path === "" ? await listFolder(root) : await readFolderFileBytes(root, path); }
91
+ catch { result = { error: "Could not read this folder. Try again." }; }
92
+ try {
93
+ const saved = await api.folderReadResult({ ...args, result }, options);
94
+ return saved.ok;
95
+ } catch { return false; }
96
+ }
@@ -0,0 +1,170 @@
1
+ // FOLLOW-UP MESSAGES FOR A RUNNING SESSION, ONE COPY FOR ALL THREE ENGINES (#4625).
2
+ //
3
+ // A person (or a peer session) can write to a run that is already going. Two
4
+ // doors carry those words, and every engine - the Claude stream-json child
5
+ // (child.mjs), the ACP adapter (acp.mjs) and Codex (codex.mjs) - used to carry
6
+ // its own copy of both. A fix to one (#3273: images lost, a reply marked
7
+ // delivered that the model never heard) did not reach the other two, so the
8
+ // steps live here and each engine passes only "how do I put one message into
9
+ // MY session".
10
+ //
11
+ // watchAnswers the board door: `answerPoll()` returns ready-made messages
12
+ // ({ text, images, onDelivered, deliveryKey }) and the
13
+ // subscription wakes a pass when a new one lands.
14
+ // watchReplyFiles the file door: JSON files named `<prefix>*.json` in a
15
+ // folder, consumed in name order, each with a `message`, an
16
+ // optional `from` label and optional `images`.
17
+ //
18
+ // What stays shared on purpose, because each was a real bug in one copy:
19
+ // - one pass at a time (setInterval does not wait for an async callback, so
20
+ // a slow read would let two passes see the same message);
21
+ // - a message in flight is never offered twice (poll objects are rebuilt on
22
+ // every collection, so identity is `deliveryKey ?? the object itself`);
23
+ // - `onDelivered` runs only AFTER the engine accepted the message, never
24
+ // before, or a ruling is marked delivered to a session that never heard it;
25
+ // - the busy flag is cleared in `finally`, so a throwing acknowledgement can
26
+ // not wedge every later pass;
27
+ // - a reply file is consumed BEFORE it is sent (an unlink that fails after a
28
+ // successful write is how a message arrives twice), and a peer's words
29
+ // carry the `[message from <from>]` label so they are never mistaken for
30
+ // the person's.
31
+ import { readdir, readFile, unlink } from "node:fs/promises";
32
+ import { join } from "node:path";
33
+
34
+ /** What an engine's `send` tells `watchAnswers` about one answer.
35
+ * DELIVERED: the engine has the words; acknowledge now and carry on.
36
+ * QUEUED: the engine will call `acknowledge()` itself once its turn ends
37
+ * (ACP waits for the previous turn); carry on with the next one.
38
+ * SKIP: this one cannot be sent (leave it unacknowledged, retried later);
39
+ * carry on with the next one.
40
+ * STOP: leave it unacknowledged and end this pass. */
41
+ export const DELIVERED = "delivered";
42
+ export const QUEUED = "queued";
43
+ export const SKIP = "skip";
44
+ export const STOP = "stop";
45
+
46
+ /**
47
+ * Collect board follow-ups for as long as the run lives.
48
+ *
49
+ * @param {object} o
50
+ * @param {object} o.handle the child handle (`every`, `settled`)
51
+ * @param {Function} [o.answerPoll] returns the answers waiting; may carry `.subscribe(fn)`
52
+ * @param {number} o.pollMs
53
+ * @param {Function} [o.active] extra "may I collect right now" test (engine state);
54
+ * checked before the pass and before each answer
55
+ * @param {Function} o.send async (answer, acknowledge) => DELIVERED | QUEUED | SKIP | STOP.
56
+ * `acknowledge()` runs `answer.onDelivered` and frees the answer.
57
+ * @param {Function} [o.onSendError] (error, answer) when `send` throws; the pass then ends
58
+ * @param {Function} [o.onPassEnd] runs after every pass, success or not
59
+ * @returns {{ busy: () => boolean }|undefined} whether a pass is running (an engine
60
+ * that closes its input when idle asks), or undefined with no poll
61
+ */
62
+ export function watchAnswers({ handle, answerPoll, pollMs, active = () => true, send, onSendError, onPassEnd }) {
63
+ if (!answerPoll || handle.settled()) return undefined;
64
+ const mayCollect = () => !handle.settled() && active();
65
+ // Identity of the answers in flight: offered once, until acknowledged or given up.
66
+ const inFlight = new Set();
67
+ let busy = false;
68
+ const collect = async () => {
69
+ if (!mayCollect() || busy) return;
70
+ busy = true;
71
+ try {
72
+ for (const answer of await answerPoll()) {
73
+ if (!mayCollect()) break;
74
+ const key = answer.deliveryKey ?? answer;
75
+ if (inFlight.has(key)) continue;
76
+ inFlight.add(key);
77
+ const acknowledge = async () => {
78
+ try { await answer.onDelivered?.(); }
79
+ finally { inFlight.delete(key); }
80
+ };
81
+ let verdict;
82
+ try { verdict = await send(answer, acknowledge); }
83
+ catch (error) {
84
+ inFlight.delete(key);
85
+ try { onSendError?.(error, answer); } catch { /* the engine's own reporting must not wedge the pass */ }
86
+ break;
87
+ }
88
+ if (verdict === DELIVERED) {
89
+ try { await acknowledge(); }
90
+ catch (error) {
91
+ // The words were delivered; only the receipt failed. The source
92
+ // keeps the row and can retry its ack, which is the engines' old
93
+ // behaviour, so treat it like a failed send for reporting.
94
+ try { onSendError?.(error, answer); } catch { /* as above */ }
95
+ break;
96
+ }
97
+ } else if (verdict === QUEUED) {
98
+ // The engine owns the acknowledgement now.
99
+ } else {
100
+ inFlight.delete(key);
101
+ if (verdict === STOP) break;
102
+ }
103
+ }
104
+ } catch { /* a poll that throws is not an answer either way */ }
105
+ finally {
106
+ busy = false;
107
+ try { onPassEnd?.(); } catch { /* never wedge the loop */ }
108
+ }
109
+ };
110
+ handle.every(collect, pollMs);
111
+ answerPoll.subscribe?.(collect);
112
+ return { busy: () => busy };
113
+ }
114
+
115
+ const attribute = (text, from) => (from ? `[message from ${from}] ${text}` : text);
116
+
117
+ /**
118
+ * Consume reply files for as long as the run lives.
119
+ *
120
+ * @param {object} o
121
+ * @param {object} o.handle
122
+ * @param {string} [o.replyDir]
123
+ * @param {string} [o.replyPrefix]
124
+ * @param {number} o.pollMs
125
+ * @param {Function} [o.active] engine state test, as for `watchAnswers`
126
+ * @param {Function} [o.validate] (text, images) throws if the images cannot be sent; the file
127
+ * is then left alone and `onInvalid` runs
128
+ * @param {Function} o.onInvalid (error) the engine ends the run with its own truthful error
129
+ * @param {Function} o.send async ({ text, from, images, attributed, data, path }) for one
130
+ * consumed reply; the file is already gone when this runs.
131
+ * Messages without a text are consumed and never sent.
132
+ * @param {Function} [o.onPassEnd]
133
+ * @returns {{ busy: () => boolean }|undefined}
134
+ */
135
+ export function watchReplyFiles({ handle, replyDir, replyPrefix, pollMs, active = () => true, validate, onInvalid, send, onPassEnd }) {
136
+ if (!replyDir || !replyPrefix || handle.settled()) return undefined;
137
+ let busy = false;
138
+ const mayCollect = () => !handle.settled() && active();
139
+ const watcher = handle.every(async () => {
140
+ if (handle.settled()) { clearInterval(watcher); return; }
141
+ if (busy || !mayCollect()) return;
142
+ busy = true;
143
+ try {
144
+ // Sorted by name (timestamp-based) and consumed in order.
145
+ const files = (await readdir(replyDir))
146
+ .filter((f) => f.startsWith(replyPrefix) && f.endsWith(".json"))
147
+ .sort();
148
+ for (const file of files) {
149
+ if (!mayCollect()) break;
150
+ const path = join(replyDir, file);
151
+ let data;
152
+ try { data = JSON.parse(await readFile(path, "utf8")); } catch { continue; /* skip malformed reply files */ }
153
+ const text = typeof data?.message === "string" ? data.message : null;
154
+ const images = data?.images;
155
+ // A `from` label names the sender (another session, a human); the
156
+ // receiver wraps it so a peer's words are not taken for the user's.
157
+ const from = typeof data?.from === "string" && data.from.trim() !== "" ? data.from.trim() : null;
158
+ try { validate?.(text, images); } catch (error) { onInvalid(error); return; }
159
+ // CONSUME BEFORE SENDING (see the header).
160
+ try { await unlink(path); } catch { continue; }
161
+ if (text) await send({ text, from, images, attributed: attribute(text, from), data, path });
162
+ }
163
+ } catch { /* replyDir may not exist yet, or vanish while disconnecting */ }
164
+ finally {
165
+ busy = false;
166
+ try { onPassEnd?.(); } catch { /* never wedge the loop */ }
167
+ }
168
+ }, pollMs);
169
+ return { busy: () => busy };
170
+ }
package/lib/hosted.mjs CHANGED
@@ -23,7 +23,7 @@ let nextId = 1;
23
23
  export async function callRunnerTool(name, args, options = {}) {
24
24
  const env = options.env ?? process.env;
25
25
  const config = await hostedConfig({ env });
26
- return callTool(name, args, { ...options, mcpUrl: runnerMcpUrlFrom(config, env) });
26
+ return callTool(name, args, { ...options, mcpUrl: runnerMcpUrlFrom(config, env, options.warn) });
27
27
  }
28
28
 
29
29
  /**
@@ -31,11 +31,13 @@ export async function callRunnerTool(name, args, options = {}) {
31
31
  *
32
32
  * @param {string} name the tool, e.g. "get_board"
33
33
  * @param {object} args
34
- * @param {{sessionKey?: string, boardId?: string, mcpUrl?: string, env?: object, fetchImpl?: Function, forceRefresh?: boolean}} [options]
34
+ * @param {{sessionKey?: string, boardId?: string, sessionBoardId?: string, mcpUrl?: string, env?: object, fetchImpl?: Function, forceRefresh?: boolean}} [options]
35
35
  * `sessionKey`, when given, rides as `X-Glytch-Session` - the board-mcp
36
36
  * endpoint (2026-09-11) lets it replace the token-derived session key, so a
37
37
  * spawned child's tool calls land under the same run key its report(),
38
38
  * ask_user and everything else on this run already use.
39
+ * `sessionBoardId` pins runner permission calls to X-Glytch-Board; the
40
+ * server still checks board membership and the run origin.
39
41
  * For `get_node`, `boardId` selects a board in the same sequential JSON-RPC
40
42
  * batch. Separate requests do not retain the server's board selection. This
41
43
  * option is read-only: the server continues a batch after selection errors,
@@ -43,7 +45,7 @@ export async function callRunnerTool(name, args, options = {}) {
43
45
  * @returns {Promise<{text: string, isError: boolean}>}
44
46
  */
45
47
  export async function callTool(name, args, options = {}) {
46
- const { sessionKey, boardId, env = process.env } = options;
48
+ const { sessionKey, boardId, sessionBoardId, env = process.env } = options;
47
49
  if (boardId !== undefined && (name !== "get_node" || typeof boardId !== "string" || boardId.trim() === "")) {
48
50
  return { text: "A board-scoped read requires get_node and a non-empty boardId.", isError: true };
49
51
  }
@@ -57,6 +59,7 @@ export async function callTool(name, args, options = {}) {
57
59
  params: { name: "get_board", arguments: { board_id: boardId, limit: 1 } },
58
60
  };
59
61
  const headers = typeof sessionKey === "string" && sessionKey.trim() !== "" ? { "X-Glytch-Session": sessionKey.trim() } : {};
62
+ if (typeof sessionBoardId === "string" && sessionBoardId.trim()) headers["X-Glytch-Board"] = sessionBoardId.trim();
60
63
  let result;
61
64
  try {
62
65
  result = await authenticatedJsonPost(mcpUrl, select ? [select, request] : request, { ...options, headers });
@@ -108,5 +111,11 @@ export async function callTool(name, args, options = {}) {
108
111
  const images = content
109
112
  .filter((part) => part?.type === "image" && typeof part.data === "string")
110
113
  .map((part) => ({ mediaType: part.mimeType ?? part.mediaType ?? "image/png", data: part.data }));
111
- return { text: joined, isError: payload?.result?.isError === true, ...(images.length > 0 ? { images } : {}) };
114
+ // `refused`: the endpoint was reached and the tool itself said no, unlike
115
+ // the transport failures above, which a caller may simply retry. A tool
116
+ // that crashed, timed out or lost a board race is marked `_meta.fault` by
117
+ // supabase/functions/_shared/mcp.mjs and is not a refusal either (#5106).
118
+ const isError = payload?.result?.isError === true;
119
+ const refused = isError && payload?.result?._meta?.fault !== true;
120
+ return { text: joined, isError, ...(refused ? { refused: true } : {}), ...(images.length > 0 ? { images } : {}) };
112
121
  }
@@ -88,11 +88,12 @@ export const AGENT_VERBS = {
88
88
  * `init`'s own last lines print instead of leaving a warn row buried mid
89
89
  * output (2026-09-19, persona walk finding 1b). Claude Code's own in-chat
90
90
  * verb is `/mcp`; codex and opencode have no chat-native equivalent, so
91
- * theirs names the same CLI verb AGENT_VERBS already runs from a terminal. */
91
+ * theirs names the same CLI verb AGENT_VERBS already runs. Since #4205 none
92
+ * says "from a terminal": the pasting agent runs it, never the person. */
92
93
  export const AGENT_CONNECT_HINT = {
93
94
  claude: "Type /mcp in this tab and sign in to Viewable.",
94
- codex: "Run `codex mcp login viewable` from a terminal, then restart this session, to connect the board.",
95
- opencode: "Run `opencode mcp auth viewable` from a terminal to connect the board.",
95
+ codex: "Run `codex mcp login viewable` yourself, then start a new Codex session, to connect the board.",
96
+ opencode: "Run `opencode mcp auth viewable` yourself to connect the board.",
96
97
  };
97
98
 
98
99
  /** A personal `pmb_` token this machine can already reach the board with -
@@ -243,9 +244,10 @@ export async function signInStep({
243
244
  * (the redirect to app.viewable.one drops the Authorization header). The answer
244
245
  * is `{ retired: { scope, bearer } }` when that entry lives in a scope this
245
246
  * file may replace (local or user), for the caller to move, and `false` for
246
- * one in the project file. Any other answer is true, false or null as
247
- * before. */
248
- async function alreadyConnected(key, { exec, env, serverKey = INIT_SERVER_KEY }) {
247
+ * one in the project file. A current entry with a replacement token returns
248
+ * `{ refresh: found }` so its connected status cannot hide a stale bearer.
249
+ * Any other answer is true, false or null as before. */
250
+ async function alreadyConnected(key, { exec, env, serverKey = INIT_SERVER_KEY, token, boardUrl }) {
249
251
  // The ASKING commands are probes, not browser flows: they keep execProbe's
250
252
  // own short timeout rather than LOGIN_TIMEOUT_MS.
251
253
  const run = (bin, args) => exec(bin, args, { env });
@@ -257,6 +259,7 @@ async function alreadyConnected(key, { exec, env, serverKey = INIT_SERVER_KEY })
257
259
  if (entryIsAtRetiredUrl(found, env)) {
258
260
  return found.scope === "local" || found.scope === "user" ? { retired: found } : false;
259
261
  }
262
+ if (token && found.url === boardUrl && found.bearer && found.bearer !== token) return { refresh: found };
260
263
  return !text.includes("Needs authentication");
261
264
  }
262
265
  if (key === "opencode") {
@@ -330,8 +333,8 @@ export async function agentLoginStep({
330
333
 
331
334
  // A registration at the retired address is replaced, not kept, and before
332
335
  // the gates below: skipping sign-in must not leave it on prompt.glytch.ai.
333
- let connected = key === "claude" ? await alreadyConnected(key, { exec, env, serverKey }) : undefined;
334
- if (connected !== null && typeof connected === "object") {
336
+ let connected = key === "claude" ? await alreadyConnected(key, { exec, env, serverKey, token, boardUrl }) : undefined;
337
+ if (connected?.retired) {
335
338
  const moved = await moveClaudeRegistration({
336
339
  exec, bin, env, serverKey, ...connected.retired, token, boardUrl,
337
340
  addArgs: (url, bearer, scope) => claudeAddArgs(url, bearer, scope, serverKey), stderrOf: lastStderrLine,
@@ -343,6 +346,22 @@ export async function agentLoginStep({
343
346
  log(hint(moved.message, options));
344
347
  connected = false;
345
348
  }
349
+ if (connected?.refresh) {
350
+ // A successful probe can still use the token the setup retry replaced.
351
+ // Refresh the local override, never a shared project's bearer. Other
352
+ // agents use their own OAuth credentials and never receive this token.
353
+ const existing = connected.refresh;
354
+ if (existing.scope === "local") {
355
+ const refreshed = await moveClaudeRegistration({
356
+ exec, bin, env, serverKey, ...existing, token, boardUrl,
357
+ addArgs: (url, bearer, scope) => claudeAddArgs(url, bearer, scope, serverKey), stderrOf: lastStderrLine,
358
+ });
359
+ settle(refreshed.status, refreshed.status === "ok" ? "connected" : refreshed.message);
360
+ continue;
361
+ }
362
+ // A user/project entry stays in its own scope; a local entry overrides it.
363
+ connected = false;
364
+ }
346
365
  if (skip) {
347
366
  settle("warn", "skipped (--no-agent-login)", `Run \`${command}\` when you want it connected.`);
348
367
  continue;
@@ -368,7 +387,7 @@ export async function agentLoginStep({
368
387
  continue;
369
388
  }
370
389
 
371
- if (!isTTY) {
390
+ if (!isTTY || (key === "claude" && token && connected === false)) {
372
391
  // THE PASTING AGENT HAS NO TTY EITHER (fix 1a, 2026-09-19 persona
373
392
  // walk): OAuth needs a browser AND a terminal to wait on the redirect
374
393
  // in, and `glytch init --yes` run BY a coding agent's own shell tool
@@ -392,7 +411,7 @@ export async function agentLoginStep({
392
411
  }
393
412
  continue;
394
413
  }
395
- settle("warn", "skipped (no terminal)", `Run \`${command}\` from a terminal to connect it.`);
414
+ settle("warn", "skipped (no terminal)", `Run \`${command}\` yourself to connect it.`);
396
415
  continue;
397
416
  }
398
417