viewable-one 0.12.1 → 0.12.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/CHANGELOG.md +71 -1
  2. package/README.md +31 -48
  3. package/SPAWN.md +136 -79
  4. package/glytch.mjs +41 -10
  5. package/lib/acp.mjs +152 -150
  6. package/lib/admission.mjs +25 -5
  7. package/lib/agent-selection.mjs +5 -4
  8. package/lib/agents.mjs +68 -24
  9. package/lib/answerTag.mjs +47 -0
  10. package/lib/atomic.mjs +1 -16
  11. package/lib/auth.mjs +172 -52
  12. package/lib/authenticatedHttp.mjs +10 -3
  13. package/lib/boardside.mjs +28 -12
  14. package/lib/child.mjs +129 -116
  15. package/lib/claudeModels.mjs +168 -0
  16. package/lib/codex-rpc.mjs +2 -2
  17. package/lib/codex.mjs +50 -50
  18. package/lib/codexApps.mjs +17 -3
  19. package/lib/codexToolInputs.mjs +98 -22
  20. package/lib/codingChecks.mjs +8 -4
  21. package/lib/conversationRules.mjs +47 -7
  22. package/lib/detect.mjs +39 -24
  23. package/lib/devserver.mjs +30 -19
  24. package/lib/doctor.mjs +10 -8
  25. package/lib/folderReads.mjs +96 -0
  26. package/lib/followUps.mjs +170 -0
  27. package/lib/hosted.mjs +13 -4
  28. package/lib/init-connect.mjs +29 -10
  29. package/lib/lateResume.mjs +135 -0
  30. package/lib/logindaemon.mjs +129 -49
  31. package/lib/logs.mjs +2 -2
  32. package/lib/mcpjson.mjs +35 -2
  33. package/lib/memberPreview.mjs +22 -14
  34. package/lib/multiwatch.mjs +28 -41
  35. package/lib/pagePictures.mjs +15 -12
  36. package/lib/pageRoutes.mjs +5 -2
  37. package/lib/paths.mjs +3 -3
  38. package/lib/permissionAsk.mjs +344 -61
  39. package/lib/previewGateway.mjs +4 -3
  40. package/lib/procs.mjs +73 -2
  41. package/lib/refusal.mjs +0 -2
  42. package/lib/registry.mjs +7 -7
  43. package/lib/repomap.mjs +4 -3
  44. package/lib/restartPass.mjs +39 -11
  45. package/lib/rowsAnswers.mjs +52 -69
  46. package/lib/rowsEvents.mjs +20 -2
  47. package/lib/runner-health.mjs +29 -5
  48. package/lib/runner.mjs +161 -1347
  49. package/lib/runnerAdmission.mjs +6 -12
  50. package/lib/runnerApi.mjs +20 -11
  51. package/lib/runnerBeat.mjs +384 -0
  52. package/lib/runnerCompletion.mjs +5 -2
  53. package/lib/runnerExecute.mjs +227 -0
  54. package/lib/runnerGates.mjs +338 -0
  55. package/lib/runnerLaunch.mjs +351 -0
  56. package/lib/runnerLease.mjs +31 -9
  57. package/lib/runnerOps.mjs +217 -0
  58. package/lib/runnerPace.mjs +10 -6
  59. package/lib/runnerRecovery.mjs +457 -0
  60. package/lib/runnerRegister.mjs +29 -8
  61. package/lib/runnerSettlement.mjs +43 -16
  62. package/lib/runnerWorkspace.mjs +19 -4
  63. package/lib/spawn.mjs +0 -5
  64. package/lib/sync.mjs +28 -16
  65. package/lib/uninstall-project.mjs +12 -11
  66. package/lib/uninstall.mjs +32 -25
  67. package/lib/update.mjs +4 -4
  68. package/lib/{glytchFolder.mjs → viewableFolder.mjs} +22 -16
  69. package/lib/worktree.mjs +83 -26
  70. package/lib/writePolicy.mjs +90 -10
  71. package/package.json +2 -2
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
 
@@ -263,7 +244,7 @@ export const execProbe = (
263
244
  resolve({ ok: false, stdout: "", stderr: String(error?.message ?? error), code: null });
264
245
  return;
265
246
  }
266
- const options = { timeout: timeoutMs, windowsHide: true, shell: resolved.shell, ...(cwd ? { cwd } : {}) };
247
+ const options = { env, timeout: timeoutMs, windowsHide: true, shell: resolved.shell, ...(cwd ? { cwd } : {}) };
267
248
  execImpl(resolved.file, resolved.args, options, (error, stdout, stderr) => {
268
249
  // `code` is part of the shape both runners answer in. execFile's error
269
250
  // carries the exit status as a number when the child ran and failed,
@@ -475,6 +456,26 @@ export function versionFrom(text) {
475
456
  return match ? match[1] : undefined;
476
457
  }
477
458
 
459
+ /** CLI syntax evidence, never a model request. Only explicit model IDs with
460
+ * documented effort support are advertised; aliases/default can be overridden.
461
+ * Checked with Claude Code 2.1.312 and code.claude.com/docs/en/model-config
462
+ * on 2026-10-28 (#3210). These are capabilities, not an availability catalog. */
463
+ export async function probeClaudeEffort(bin, { exec = execProbe, env = process.env, timeoutMs = PROBE_TIMEOUT_MS } = {}) {
464
+ const help = await exec(bin, ["--help"], { env, timeoutMs });
465
+ if (!help?.ok) return {};
466
+ const match = /--effort\s+<level>[\s\S]*?\((low,[^)]*)\)/.exec(help.stdout ?? "");
467
+ if (!match) return {};
468
+ const levels = match[1].split(",").map((s) => s.trim());
469
+ const models = Object.create(null);
470
+ for (const model of ["claude-opus-4-6", "claude-sonnet-4-6", "claude-opus-4-7", "claude-opus-4-8", "claude-opus-5", "claude-sonnet-5", "claude-fable-5", "claude-fable-5-1", "claude-opus-5-5", "claude-sonnet-5-5", "claude-haiku-5-5"]) {
471
+ models[model] = ["low", "medium", "high", ...(model.endsWith("4-6") ? [] : ["xhigh"]), "max"].filter((level) => levels.includes(level));
472
+ // Documented 1M variants share the base model's effort support. Advertise
473
+ // the exact request key so both the picker and runner preserve its suffix.
474
+ if (model === "claude-opus-4-6" || model === "claude-sonnet-4-6") models[`${model}[1m]`] = models[model];
475
+ }
476
+ return models;
477
+ }
478
+
478
479
  /** Probe every engine. Returns the `agents` block stage 2 writes into the
479
480
  * mark file:
480
481
  *
@@ -504,6 +505,10 @@ export async function detectAgents({
504
505
  // Claude exposes a local marker - a keychain item on macOS, a file
505
506
  // elsewhere; Codex is queried through app-server below.
506
507
  if (agents.claude) {
508
+ 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 });
510
+ if (Object.keys(effortModels).length) agents.claude.effortModels = effortModels;
511
+ }
507
512
  agents.claude.loggedIn = await claudeLoggedIn({ exec, env, platform, credentialsPath, fileExists });
508
513
  }
509
514
  if (agents.codex?.found && codexDiscover) {
@@ -564,6 +569,7 @@ export const PROBE_INTERVAL_MS = 5 * 60_000;
564
569
  */
565
570
  export function makeAgentProbe({
566
571
  detect = detectAgents,
572
+ claudeDiscover = detect === detectAgents ? discoverClaudeModels : null,
567
573
  env = process.env,
568
574
  intervalMs = PROBE_INTERVAL_MS,
569
575
  now = () => Date.now(),
@@ -580,6 +586,14 @@ export function makeAgentProbe({
580
586
  checkedAt = now();
581
587
  try {
582
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
+ }
583
597
  } catch (error) {
584
598
  // Never take the beat down for a probe. An empty block is honest here:
585
599
  // nothing was learned, so nothing is claimed.
@@ -594,6 +608,7 @@ export function makeAgentProbe({
594
608
  /** What goes into the mark file, plus a refresh when one is due. */
595
609
  mark() {
596
610
  if (!running && (checkedAt === null || now() - checkedAt >= intervalMs)) void run();
611
+ if (claudeDiscover && known?.claude?.found) known.claude.resolvedModels = readClaudeModels(known.claude.version, env);
597
612
  return known === null ? {} : { agents: { ...known } };
598
613
  },
599
614
  /** Await one probe. The daemon's start, `doctor`, and the tests use this. */
package/lib/devserver.mjs CHANGED
@@ -38,7 +38,7 @@
38
38
  // doubt.
39
39
 
40
40
  import { execFile, spawn as spawnProcess } from "node:child_process";
41
- import { access, mkdir, readFile, writeFile } from "node:fs/promises";
41
+ import { access, readFile, stat, writeFile } from "node:fs/promises";
42
42
  import { join } from "node:path";
43
43
 
44
44
  import { killTree } from "./kill.mjs";
@@ -46,10 +46,9 @@ import { devServerEnv } from "./child.mjs";
46
46
  import { runnableCommand } from "./windows-command.mjs";
47
47
  import { resolveContainedCwd } from "./worktree.mjs";
48
48
 
49
- /** The file a session writes in the root of its worktree. Named in the spawn
50
- * instruction (src/store/spawnPayload.ts) and in bridge/SPAWN.md; both have to
51
- * say the same string, so it is spelled once here. */
52
- export const SERVER_RECORD_FILE = ".glytch-server.json";
49
+ /** The canonical server record this runner writes in the worktree root. App instructions still name .glytch-server.json for installed
50
+ * older runners; readWorktreeRecord accepts either name. */
51
+ export const SERVER_RECORD_FILE = ".viewable-server.json";
53
52
 
54
53
  /** How far a process's real start time may sit from the record's `startedAt`
55
54
  * before the record is treated as describing a different process. The session
@@ -58,17 +57,29 @@ export const SERVER_RECORD_FILE = ".glytch-server.json";
58
57
  * that wrote the file late. */
59
58
  export const START_SLACK_MS = 10 * 60_000;
60
59
 
61
- /** The record a session left in its worktree, or null. Never throws: no file,
62
- * a half-written one and a session that never started a server are all "there
63
- * is nothing to stop", which is the ordinary case. */
60
+ /** The newest usable record across the canonical and legacy filenames. A
61
+ * resumed session can write the legacy file after a relaunch wrote the new
62
+ * one. Rank by startedAt, or file mtime when that timestamp is unavailable.
63
+ * Never throws: a missing or half-written record cannot hide the other file. */
64
64
  export async function readWorktreeRecord(sessionDir) {
65
65
  if (!sessionDir) return null;
66
- try {
67
- const parsed = JSON.parse(await readFile(join(sessionDir, SERVER_RECORD_FILE), "utf8"));
68
- return Number.isFinite(Number(parsed?.pid)) ? parsed : null;
69
- } catch {
70
- return null;
66
+ let newest = null;
67
+ let newestAt = -Infinity;
68
+ for (const name of [SERVER_RECORD_FILE, ".glytch-server.json"]) {
69
+ try {
70
+ const path = join(sessionDir, name);
71
+ const parsed = JSON.parse(await readFile(path, "utf8"));
72
+ const pid = Number(parsed?.pid);
73
+ if (!Number.isInteger(pid) || pid <= 1) continue;
74
+ const startedAt = Date.parse(parsed.startedAt ?? "");
75
+ const at = Number.isFinite(startedAt) ? startedAt : (await stat(path)).mtimeMs;
76
+ if (at > newestAt) {
77
+ newest = parsed;
78
+ newestAt = at;
79
+ }
80
+ } catch { /* Keep looking if either file is absent or invalid. */ }
71
81
  }
82
+ return newest;
72
83
  }
73
84
 
74
85
  const run = (bin, args, timeout = 5_000) =>
@@ -216,7 +227,7 @@ const cimRowFor = async (pid) => parseCimProcess(await run("powershell.exe", cim
216
227
 
217
228
  const netstatListeners = async (port) => parseNetstatListeners(await run("netstat", ["-ano"], 15_000), port);
218
229
 
219
- const defaultPs = (pid) => (process.platform === "win32" ? cimRowFor(pid) : psRowFor(pid));
230
+ export const readProcessIdentity = (pid) => (process.platform === "win32" ? cimRowFor(pid) : psRowFor(pid));
220
231
  const defaultListeners = (port) => (process.platform === "win32" ? netstatListeners(port) : lsofListeners(port));
221
232
 
222
233
  const parentPidFor = async (pid) => {
@@ -233,7 +244,7 @@ const parentPidFor = async (pid) => {
233
244
  * takes its port. Every listener must belong to this recorded process tree;
234
245
  * missing process inspection is a refusal, never a command-line fallback. */
235
246
  export async function verifyPreviewServer(record, {
236
- ps = defaultPs, listeners = defaultListeners, parentPid = parentPidFor,
247
+ ps = readProcessIdentity, listeners = defaultListeners, parentPid = parentPidFor,
237
248
  } = {}) {
238
249
  const pid = Number(record?.pid);
239
250
  const port = Number(record?.port);
@@ -302,7 +313,7 @@ const normaliseCommand = (value) =>
302
313
  *
303
314
  * `ps` and `listeners` are injected so the decision can be tested without a
304
315
  * machine's process table under it. */
305
- export async function verifyRecordedServer(record, { ps = defaultPs, listeners = defaultListeners } = {}) {
316
+ export async function verifyRecordedServer(record, { ps = readProcessIdentity, listeners = defaultListeners } = {}) {
306
317
  const pid = Number(record?.pid);
307
318
  if (!Number.isFinite(pid) || pid <= 1) return { ours: false, reason: "no usable pid in the record" };
308
319
 
@@ -377,7 +388,7 @@ export async function stopRecordedServer(record, { graceMs = 3_000, sleep = (ms)
377
388
  // OVER ROWS, 2026-09-11 (brief 30 Move 2b): the app asks with a `run_ops` row
378
389
  // of `kind:"relaunch"` now, surfaced by `heartbeat`'s `ops`, claimed with
379
390
  // `opTake`, answered with `opResult` (updatable - the button can be pressed
380
- // 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.
381
392
  // `relaunchServer` below is the pure core, unchanged in what it decides;
382
393
  // what moved is where the RECORD comes from and where the OUTCOME goes.
383
394
  // Before this pass both were the mailbox: `<id>.server` (a mirror of the
@@ -482,7 +493,7 @@ const stillAlive = (pid) => {
482
493
  *
483
494
  * `record` is the run row's own `server` column, or `null` when the row has
484
495
  * none yet (a session that started no server) - the caller
485
- * (`bridge/lib/runner.mjs`'s `serviceRowOps`) falls back to
496
+ * (`bridge/lib/runnerOps.mjs`'s `serviceRowOps`) falls back to
486
497
  * `readWorktreeRecord(hinted)` when the row is empty but the op's payload
487
498
  * carries a `worktreePath` hint, exactly as the file-based signal used to.
488
499
  *
@@ -510,7 +521,7 @@ export async function relaunchServer(
510
521
  spawn = defaultSpawn,
511
522
  exists = defaultExists,
512
523
  listeners = defaultListeners,
513
- ps = defaultPs,
524
+ ps = readProcessIdentity,
514
525
  settleMs = RELAUNCH_SETTLE_MS,
515
526
  sleep = (ms) => new Promise((r) => setTimeout(r, ms)),
516
527
  now = () => new Date(),
package/lib/doctor.mjs CHANGED
@@ -52,10 +52,10 @@ import { presence as hostedPresence } from "./runnerApi.mjs";
52
52
  // `row` is imported from cli-output.mjs (brief 31 review, 2026-09-12 - it
53
53
  // used to be a local copy, byte-identical to lib/uninstall.mjs's own and
54
54
  // lib/uninstall-project.mjs's own). `action` is the same escape hatch
55
- // sync.mjs's own `row()` carries (2026-09-11): the generic "run glytch init"
55
+ // sync.mjs's own `row()` carries (2026-09-11): the generic "run viewable init"
56
56
  // is wrong exactly when init is the thing that already failed, or fixes
57
- // nothing at all - "not signed in to the board" needs `glytch login`, not
58
- // `glytch init`, and printing the default there is the same loop ruling 6C
57
+ // nothing at all - "not signed in to the board" needs `viewable login`, not
58
+ // `viewable init`, and printing the default there is the same loop ruling 6C
59
59
  // named for Task Scheduler.
60
60
 
61
61
  /** The one-line step that turns a WRITTEN board entry into an AUTHENTICATED
@@ -270,7 +270,7 @@ export async function doctorRows(
270
270
  // NEVER RED for either "not signed in" or "offline": both are facts about
271
271
  // the world, not this install, the same rule the file's own header states
272
272
  // for every other row - a machine on a plane, or one that has not run
273
- // `glytch login` yet, is not a daemon that stopped beating.
273
+ // `viewable login` yet, is not a daemon that stopped beating.
274
274
  // WHICH ACCOUNT THE BEARER REACHES, filled from the same presence call the
275
275
  // beat row makes (2026-09-14). Null when that call did not happen or did not
276
276
  // come back: this must never turn a row red on its own.
@@ -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
@@ -371,7 +371,7 @@ export async function doctorRows(
371
371
  // revoked from Settings - so "expired and cannot be renewed" would
372
372
  // have been the wrong sentence even after the mark started being
373
373
  // written for it. "rejected" names what actually happened, and the
374
- // hint names the actual fix: a fresh token, not `glytch login`.
374
+ // hint names the actual fix: a fresh token, not `viewable login`.
375
375
  ? row(
376
376
  "boardAuth",
377
377
  "board sign-in",
@@ -441,10 +441,12 @@ 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
- ? row("version", "version", true, "update available", `${version} installed, ${newestPublished} on npm: npm i -g glytch`)
449
+ ? row("version", "version", true, "update available", `${version} installed, ${newestPublished} on npm: npm i -g viewable-one@latest --force`)
448
450
  : row("version", "version", true, "current", `${version} is the latest`),
449
451
  );
450
452
 
@@ -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
  }