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
@@ -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
 
@@ -0,0 +1,135 @@
1
+ // Finished-session messages use the existing permission ask and resume doors
2
+ // (#5101, #5103). No child runs while an answer waits, and no message is acked
3
+ // until declined or durably filed. Permission memory stays per linked folder.
4
+ import { acquireAdmission } from "./admission.mjs";
5
+ import { basename, join } from "node:path";
6
+ import { mkdir, readFile } from "node:fs/promises";
7
+ import { askUserOnBoard } from "./boardside.mjs";
8
+ import { ALLOW, NOT_THIS, alwaysLabel, readAnswer, readRules, rememberRule, verdictFor } from "./permissionAsk.mjs";
9
+ import { writeFileAtomic } from "./atomic.mjs";
10
+ import { viewableHome } from "./registry.mjs";
11
+ import { callRunnerTool } from "./hosted.mjs";
12
+ import * as runnerApi from "./runnerApi.mjs";
13
+ import { promoteLateRows } from "./rowsAnswers.mjs";
14
+
15
+ /** One nonblocking look at a permission. The receipt survives watcher restarts;
16
+ * the account/project scope prevents a different sign-in inheriting a grant. */
17
+ export async function allowLateResume(root, run, promotionId, settings, log = () => {}) {
18
+ const env = settings.env;
19
+ const key = `Continue(${run.user_id}:${run.project_id})`;
20
+ const directory = join(viewableHome(env), "resume-asks");
21
+ const path = join(directory, `${promotionId}.json`);
22
+ let saved;
23
+ try { saved = JSON.parse(await readFile(path, "utf8")); }
24
+ catch (error) { if (error.code !== "ENOENT") throw error; }
25
+ const callTool = (name, args, options) => (settings.hostedCallTool ?? callRunnerTool)(name, args, { ...options, sessionBoardId: run.board_id });
26
+ const options = { sessionKey: run.session_key ?? run.id, env };
27
+ const folderName = basename(root) || root;
28
+ // A prior explicit refusal stays refused even if another ask saves Always.
29
+ if (saved?.decision) return saved.decision;
30
+ if (!saved && (await readRules(env, root)).includes(key)) return "allow";
31
+ if (!saved) {
32
+ // Keyed on the promotion id: a lost reply or a receipt that did not save
33
+ // gets the same question back on the next beat, never a second one (#5106).
34
+ const filed = await askUserOnBoard({ key: options.sessionKey }, "Allow the agent to continue with the new answer?", {
35
+ fromId: run.from_id, purpose: "permission", askKey: promotionId,
36
+ why: "The agent finished before this answer arrived. Allow continues its session. Always allow lets later answers continue agents in this folder without asking.",
37
+ options: [ALLOW, NOT_THIS, alwaysLabel(folderName)],
38
+ recommendation: { answer: ALLOW, why: "Let the agent use the answer to continue its work." },
39
+ }, { callTool, env });
40
+ if (!filed.ok || !filed.questionId) {
41
+ // A refused ask (its idea deleted, the run stopped) never succeeds on
42
+ // a later beat; a transport failure may, so only that one retries.
43
+ throw Object.assign(new Error(filed.detail ?? "Could not ask to continue."), { refused: filed.refused === true });
44
+ }
45
+ saved = { questionId: filed.questionId };
46
+ await mkdir(directory, { recursive: true, mode: 0o700 });
47
+ await writeFileAtomic(path, JSON.stringify(saved));
48
+ }
49
+ const result = await callTool("check_answer", { question_id: saved.questionId, wait_s: 0 }, options);
50
+ if (result.isError && readAnswer(result.text).state !== "gone") throw new Error(result.text);
51
+ const answer = readAnswer(result.text);
52
+ // ALWAYS ALLOW RELEASES ASKS ALREADY WAITING (#5106). An open ask on this
53
+ // run lets go once another run's ask saved Always for the folder. An answer
54
+ // given on this ask itself is read first, so its own "Not this" still wins.
55
+ const released = answer.state === "open" && (await readRules(env, root)).includes(key);
56
+ if (answer.state === "open" && !released) return "waiting";
57
+ const verdict = released ? { behavior: "allow" } : verdictFor(answer, folderName);
58
+ if (verdict.remember) await rememberRule(env, root, key);
59
+ saved.decision = verdict.behavior;
60
+ await writeFileAtomic(path, JSON.stringify(saved));
61
+ log(`[${run.id}] continuation ${saved.decision}`);
62
+ return saved.decision;
63
+ }
64
+
65
+ /** The statuses board-runner's resume accepts; the heartbeat covers each. */
66
+ const FINISHED = ["done", "error", "stopped"];
67
+
68
+ /** Whether resume could carry this run on at all, by the same conversation
69
+ * id board-runner's resume reads. The server re-checks. */
70
+ const continuable = run => run.approved === true && !run.stop_requested_at
71
+ && Boolean(run.request?.agent === "codex" ? run.sidecar?.codexThreadId : run.sidecar?.claudeSessionId);
72
+
73
+ /** Mark a message on the run's sidecar before it is acknowledged, so the app
74
+ * shows "did not reach the session" with Try again. Throws if the mark could
75
+ * not be saved, so the message stays unacknowledged and the next beat retries. */
76
+ async function markUndelivered(api, run, message, options) {
77
+ if (!message) return;
78
+ const list = Array.isArray(run.sidecar?.undelivered) ? run.sidecar.undelivered : [];
79
+ if (list.some(m => m.from === message.from && m.text === message.text)) return;
80
+ const sidecar = { ...(run.sidecar ?? {}), undelivered: [...list, { from: message.from, text: message.text }] };
81
+ const out = await api.update({ runId: run.id, patch: { sidecar } }, options);
82
+ if (!out.ok) throw new Error(out.error);
83
+ run.sidecar = out.run?.sidecar ?? sidecar;
84
+ }
85
+
86
+ /** The heartbeat revisits undelivered messages, including reviews decided long
87
+ * after exit. The server lists this account's finished app runs in every
88
+ * status resume accepts. A run that can continue asks first; a message that
89
+ * cannot be asked about or carried on is declined and marked undelivered,
90
+ * never left unread. Returns how many runs the server listed. */
91
+ export async function resumeLateMessages(project, settings, log = () => {}) {
92
+ if (settings.enabled !== true) return 0;
93
+ const held = await acquireAdmission(project.path, { directory: join(viewableHome(settings.env), "resume-asks") });
94
+ if (!held.ok) return 0;
95
+ try {
96
+ const api = settings.runnerApi ?? runnerApi;
97
+ const options = { env: settings.env, fetchImpl: settings.fetchImpl };
98
+ const listed = await api.runs({ projectIds: [project.id], lateMessages: true }, options);
99
+ if (!listed.ok) throw new Error(listed.error);
100
+ const waiting = listed.runs ?? [];
101
+ for (const run of waiting) {
102
+ if (!FINISHED.includes(run.status) || (!run.from_id && !run.request?.roomId)) continue;
103
+ try {
104
+ const callTool = (name, args, opts) => (settings.hostedCallTool ?? callRunnerTool)(name, args, { ...opts, sessionBoardId: run.board_id });
105
+ await promoteLateRows(project.path, run.id, {
106
+ poller: { since: () => 0, hasDelivered: () => true }, // question answers belong to their existing consumer
107
+ callTool, sessionKey: run.session_key ?? run.id, env: settings.env,
108
+ messageLimit: 1,
109
+ promote: async (root, id, reply, logger, promotionId) => {
110
+ const decline = async why => {
111
+ await markUndelivered(api, run, reply.message, options);
112
+ logger(`[${id}] late message not carried on: ${why}`);
113
+ return { declined: true };
114
+ };
115
+ if (!continuable(run)) return decline("this session cannot be continued");
116
+ let decision;
117
+ try { decision = await allowLateResume(root, run, promotionId, settings, logger); }
118
+ catch (error) { if (error?.refused) return decline(error.message); throw error; }
119
+ if (decision === "waiting") return { waiting: true };
120
+ if (decision === "deny") return decline("not allowed");
121
+ const out = await api.resume({ runId: id, message: reply.text, images: reply.images, promotionId }, options);
122
+ if (!out.ok && out.refused && !out.retry) return decline(out.error);
123
+ if (!out.ok) throw new Error(out.error);
124
+ return out.run?.id ?? out.id ?? null;
125
+ },
126
+ }, log);
127
+ } catch (error) {
128
+ log(`[${run.id}] late message continuation failed: ${error?.message ?? error}`);
129
+ }
130
+ }
131
+ // How many runs still had messages waiting: the heartbeat looks again
132
+ // soon while any do, and rarely while none do (runnerBeat.mjs).
133
+ return waiting.length;
134
+ } finally { await held.release(); }
135
+ }
@@ -51,7 +51,7 @@ import { execFile } from "node:child_process";
51
51
  import { homedir } from "node:os";
52
52
  import { fileURLToPath } from "node:url";
53
53
  import { dirname, join, win32 } from "node:path";
54
- import { glytchHome } from "./registry.mjs";
54
+ import { viewableHome } from "./registry.mjs";
55
55
  import { logDir, logPath } from "./logs.mjs";
56
56
 
57
57
  /** One name on all three platforms: the launchd label, the scheduled task
@@ -108,10 +108,10 @@ export const PLATFORM_LABEL = {
108
108
  * loaded), and a global npm bin is a symlink to exactly this file anyway. On
109
109
  * Windows the same argument is stronger: the global bin is `glytch.cmd`, and
110
110
  * a `.cmd` is exactly what Node refuses to spawn without a shell. */
111
- export const glytchScriptPath = () => fileURLToPath(new URL("../glytch.mjs", import.meta.url));
111
+ export const viewableScriptPath = () => fileURLToPath(new URL("../glytch.mjs", import.meta.url));
112
112
 
113
113
  /** The script path the INSTALLED daemon file on this machine actually runs,
114
- * or null - never glytchScriptPath() above, which is what THIS running
114
+ * or null - never viewableScriptPath() above, which is what THIS running
115
115
  * package would install, not what a plist, launcher or unit written by some
116
116
  * earlier `viewable init` still points at. Null covers both "there is no file"
117
117
  * (impl.read already returns null, and the plist/scheduled-task/systemd row
@@ -232,6 +232,85 @@ async function ensureLogDir(env) {
232
232
  await mkdir(logDir(env), { recursive: true });
233
233
  }
234
234
 
235
+ /** Stable entry point: the OS can start this even after Node's versioned
236
+ * directory disappears. The existing installer still owns installation. */
237
+ export const posixLauncherPath = (env = process.env) => join(viewableHome(env), "runner-launcher.sh");
238
+ const shQuote = (value) => "'" + String(value).replace(/'/g, "'\\''") + "'";
239
+
240
+ export function renderPosixLauncher({ nodePath = process.execPath, env = process.env, shellTimeoutSeconds = 5 } = {}) {
241
+ return `#!/bin/sh
242
+ # Viewable launcher v1
243
+ SHELL=${shQuote(env.SHELL || "/bin/sh")}
244
+ export SHELL
245
+ node_bin=
246
+ # Read the current profile, including nvm/fnm configuration. Ignore banners.
247
+ for mode in -lc -ilc; do
248
+ # Redirect to a file so a profile's descendants cannot hold a substitution
249
+ # pipe open after the shell itself times out. No external timeout on macOS.
250
+ lookup_dir=$(/usr/bin/mktemp -d "\${TMPDIR:-/tmp}/viewable-node.XXXXXX") || continue
251
+ "$SHELL" "$mode" 'command -v node' >"$lookup_dir/path" 2>/dev/null &
252
+ lookup_pid=$!
253
+ (
254
+ trap 'kill "$sleeper" 2>/dev/null; exit' TERM INT
255
+ /bin/sleep ${shQuote(shellTimeoutSeconds)} &
256
+ sleeper=$!
257
+ wait "$sleeper"
258
+ kill -KILL "$lookup_pid" 2>/dev/null
259
+ ) >/dev/null 2>&1 &
260
+ watchdog=$!
261
+ wait "$lookup_pid" 2>/dev/null
262
+ kill "$watchdog" 2>/dev/null
263
+ wait "$watchdog" 2>/dev/null
264
+ found=$(/bin/cat "$lookup_dir/path")
265
+ /bin/rm -rf "$lookup_dir"
266
+ while IFS= read -r candidate; do
267
+ case "$candidate" in /*)
268
+ if [ -x "$candidate" ] && "$candidate" -e 'process.exit(+process.versions.node.split(".")[0]>=22?0:1)' 2>/dev/null; then node_bin=$candidate; fi
269
+ ;; esac
270
+ done <<EOF
271
+ $found
272
+ EOF
273
+ [ -z "$node_bin" ] || break
274
+ done
275
+ if [ -z "$node_bin" ]; then
276
+ for candidate in ${shQuote(nodePath)} \
277
+ "$HOME/.local/share/fnm/aliases/default/bin/node" \
278
+ "$HOME/Library/Application Support/fnm/aliases/default/bin/node" \
279
+ "\${FNM_DIR:-$HOME/.local/share/fnm}"/node-versions/*/installation/bin/node \
280
+ "\${NVM_DIR:-$HOME/.nvm}"/versions/node/*/bin/node \
281
+ /opt/homebrew/bin/node /usr/local/bin/node /usr/bin/node; do
282
+ if [ -x "$candidate" ] && "$candidate" -e 'process.exit(+process.versions.node.split(".")[0]>=22?0:1)' 2>/dev/null; then node_bin=$candidate; break; fi
283
+ done
284
+ fi
285
+ if [ -z "$node_bin" ]; then
286
+ echo "Your computer could not reconnect. Open Claude Code or Codex and ask it to repair the computer connection." >&2
287
+ exit 1
288
+ fi
289
+ PATH="\${node_bin%/*}:$PATH"
290
+ export PATH
291
+ script=$1
292
+ shift
293
+ if [ ! -f "$script" ]; then
294
+ script="\${node_bin%/*}/../lib/node_modules/viewable-one/glytch.mjs"
295
+ fi
296
+ exec "$node_bin" "$script" "$@"
297
+ `;
298
+ }
299
+
300
+ /** Report legacy or broken service launchers through the same sync doctor uses. */
301
+ export async function launcherNeedsRepair(text, { env = process.env, impl } = {}) {
302
+ if (impl.kind === "schtasks" || !impl.programScriptPath(text)) return false;
303
+ const launcher = posixLauncherPath(env);
304
+ const expected = impl.kind === "launchd" ? xml(launcher) : launcher;
305
+ if (!text.includes(expected)) return true;
306
+ const content = await readFile(launcher, "utf8").catch(() => "");
307
+ return !content.startsWith("#!/bin/sh\n# Viewable launcher v1\n");
308
+ }
309
+
310
+ async function writePosixLauncher(env, nodePath, force) {
311
+ await writeIfAbsent(posixLauncherPath(env), renderPosixLauncher({ env, nodePath }), force);
312
+ }
313
+
235
314
  // ---------------------------------------------------------------- launchd --
236
315
 
237
316
  const xml = (text) =>
@@ -240,21 +319,24 @@ const xml = (text) =>
240
319
  .replace(/</g, "&lt;")
241
320
  .replace(/>/g, "&gt;");
242
321
 
322
+ const unxml = (text) => String(text).replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
323
+
243
324
  /** Where the plist goes. ~/Library/LaunchAgents on a real machine; under
244
325
  * GLYTCH_HOME when it is set, which is what keeps the suite off this Mac. */
245
326
  export const plistPath = (env = process.env) =>
246
327
  (env.VIEWABLE_HOME ?? env.GLYTCH_HOME)?.trim()
247
- ? join(glytchHome(env), "LaunchAgents", PLIST_NAME)
328
+ ? join(viewableHome(env), "LaunchAgents", PLIST_NAME)
248
329
  : join(homedir(), "Library", "LaunchAgents", PLIST_NAME);
249
330
 
250
331
  /** The plist, rendered. Kept a pure function of its inputs so the test reads
251
332
  * the same string launchd would. */
252
333
  export function renderPlist({
253
334
  nodePath = process.execPath,
254
- scriptPath = glytchScriptPath(),
335
+ scriptPath = viewableScriptPath(),
255
336
  path = process.env.PATH ?? "",
256
337
  out = logPath(),
257
338
  home,
339
+ launcher,
258
340
  } = {}) {
259
341
  const env = [
260
342
  // The switch. A daemon is still not consent by itself: this is the same
@@ -263,7 +345,7 @@ export function renderPlist({
263
345
  ["PM_SPAWN_RUNNER", "on"],
264
346
  // The captured shell PATH. See the launchd PATH trap above.
265
347
  ["PATH", path],
266
- ...(home ? [["GLYTCH_HOME", home]] : []),
348
+ ...(home ? [["VIEWABLE_HOME", home]] : []),
267
349
  ];
268
350
  return `<?xml version="1.0" encoding="UTF-8"?>
269
351
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
@@ -273,8 +355,8 @@ export function renderPlist({
273
355
  <string>${xml(DAEMON_LABEL)}</string>
274
356
  <key>ProgramArguments</key>
275
357
  <array>
276
- <string>${xml(nodePath)}</string>
277
- <string>${xml(scriptPath)}</string>
358
+ <string>${xml(launcher ? "/bin/sh" : nodePath)}</string>
359
+ ${launcher ? ` <string>${xml(launcher)}</string>\n` : ""} <string>${xml(scriptPath)}</string>
278
360
  <string>runner</string>
279
361
  <string>watch</string>
280
362
  </array>
@@ -300,7 +382,7 @@ ${env.map(([k, v]) => ` <key>${xml(k)}</key>\n <string>${xml(v)}</string>`
300
382
  * installed is a daemon that cannot find the engine the app is offering. */
301
383
  export function capturedPlistPath(text) {
302
384
  const match = /<key>PATH<\/key>\s*<string>([^<]*)<\/string>/.exec(String(text ?? ""));
303
- return match ? match[1] : null;
385
+ return match ? unxml(match[1]) : null;
304
386
  }
305
387
 
306
388
  /** The script path a plist's ProgramArguments carries - the SECOND
@@ -313,8 +395,8 @@ export function capturedPlistPath(text) {
313
395
  export function scriptPathFromPlist(text) {
314
396
  const args = /<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/.exec(String(text ?? ""));
315
397
  if (!args) return null;
316
- const strings = [...args[1].matchAll(/<string>([^<]*)<\/string>/g)].map((m) => m[1]);
317
- return strings[1] ?? null;
398
+ const strings = [...args[1].matchAll(/<string>([^<]*)<\/string>/g)].map((m) => unxml(m[1]));
399
+ return strings[strings[0] === "/bin/sh" ? 2 : 1] ?? null;
318
400
  }
319
401
 
320
402
  const launchd = {
@@ -344,7 +426,7 @@ const launchd = {
344
426
  env = process.env,
345
427
  exec = execLaunchctl,
346
428
  nodePath = process.execPath,
347
- scriptPath = glytchScriptPath(),
429
+ scriptPath = viewableScriptPath(),
348
430
  path = env.PATH ?? "",
349
431
  force = false,
350
432
  load = true,
@@ -356,9 +438,11 @@ const launchd = {
356
438
  return exec(args, env);
357
439
  };
358
440
  await ensureLogDir(env);
441
+ await writePosixLauncher(env, nodePath, force);
359
442
  const wrote = await writeIfAbsent(
360
443
  file,
361
444
  renderPlist({
445
+ launcher: posixLauncherPath(env),
362
446
  nodePath,
363
447
  scriptPath,
364
448
  path,
@@ -395,7 +479,10 @@ const launchd = {
395
479
  }
396
480
  calls.push(["unload", "-w", file]);
397
481
  const result = await exec(["unload", "-w", file], env);
398
- if (removeFile) await rm(file, { force: true }).catch(() => {});
482
+ if (removeFile) {
483
+ await rm(file, { force: true }).catch(() => {});
484
+ await rm(posixLauncherPath(env), { force: true }).catch(() => {});
485
+ }
399
486
  return {
400
487
  file,
401
488
  unloaded: result.ok === true,
@@ -425,7 +512,7 @@ const launchd = {
425
512
  * PATH trap at the top) and a place to send stdout, since a scheduled task
426
513
  * has no StandardOutPath. It also keeps `/tr` a single unquoted argument,
427
514
  * which is the one part of schtasks that is genuinely hard to get right. */
428
- export const launcherPath = (env = process.env) => join(glytchHome(env), LAUNCHER_NAME);
515
+ export const launcherPath = (env = process.env) => join(viewableHome(env), LAUNCHER_NAME);
429
516
 
430
517
  /** The launcher, rendered. Pure, so the test reads the same text Task
431
518
  * Scheduler would run.
@@ -434,7 +521,7 @@ export const launcherPath = (env = process.env) => join(glytchHome(env), LAUNCHE
434
521
  * not allow one in a path anyway, so it is dropped rather than escaped. */
435
522
  export function renderLauncher({
436
523
  nodePath = process.execPath,
437
- scriptPath = glytchScriptPath(),
524
+ scriptPath = viewableScriptPath(),
438
525
  path = process.env.PATH ?? "",
439
526
  out = logPath(),
440
527
  home,
@@ -446,7 +533,7 @@ rem onlogon task (brief 21, ruling 1A of 2026-09-07). Written by
446
533
  rem \`viewable init\`; edit it and \`viewable init\` will leave your copy alone.
447
534
  set "PM_SPAWN_RUNNER=on"
448
535
  set "PATH=${q(path)}"
449
- ${home ? `set "GLYTCH_HOME=${q(home)}"\n` : ""}if not exist "${q(win32.dirname(out))}" mkdir "${q(win32.dirname(out))}"
536
+ ${home ? `set "VIEWABLE_HOME=${q(home)}"\n` : ""}if not exist "${q(win32.dirname(out))}" mkdir "${q(win32.dirname(out))}"
450
537
  "${q(nodePath)}" "${q(scriptPath)}" runner watch >> "${q(out)}" 2>&1
451
538
  `;
452
539
  }
@@ -490,7 +577,7 @@ export function scriptPathFromLauncher(text) {
490
577
  * queryable with `/query /tn`, so ruling 1A is untouched - only the spelling
491
578
  * of the registration changed, and the command-line form stays as the
492
579
  * fallback for a schtasks that will not take the file. */
493
- export const taskXmlPath = (env = process.env) => join(glytchHome(env), TASK_XML_NAME);
580
+ export const taskXmlPath = (env = process.env) => join(viewableHome(env), TASK_XML_NAME);
494
581
 
495
582
  /** `DOMAIN\user`, or null when the environment does not say who we are (a
496
583
  * stripped env, or a test). Null is what sends install back to the
@@ -590,26 +677,15 @@ async function writeTaskXml(file, text) {
590
677
 
591
678
  /** Is this Task Scheduler refusing US, rather than a task that is not there?
592
679
  * Told apart because the two need opposite answers: a missing task is
593
- * installed, and a refused one is a person opening an elevated terminal. */
680
+ * installed, and a refused one needs help repairing the connection. */
594
681
  export const schtasksDenied = (result) =>
595
682
  /access is denied|do(es)? not have permission|requires elevation/i.test(
596
683
  `${result?.stderr ?? ""} ${result?.stdout ?? ""}`,
597
684
  );
598
685
 
599
- /** What to type on Windows when the daemon cannot be registered.
600
- * POWERSHELL'S SPELLING, because that is the shell VS Code and Windows
601
- * Terminal open - `PM_SPAWN_RUNNER=on viewable runner watch` is POSIX syntax
602
- * that neither PowerShell nor cmd.exe has, so RUNNER_BY_HAND pasted there is
603
- * an error rather than a runner. cmd.exe's own is `set PM_SPAWN_RUNNER=on &&
604
- * viewable runner watch`; the README carries both. */
605
- export const RUNNER_BY_HAND_WINDOWS = '$env:PM_SPAWN_RUNNER="on"; viewable runner watch';
606
-
607
- /** The one next step a denied registration leaves. It travels on the row as
608
- * `action`, so doctor prints THIS under "Next steps" instead of its default
609
- * "run viewable init", which is the advice that looped. */
610
- export const ELEVATED_INIT =
611
- 'Task Scheduler refused the registration. Open a terminal with "Run as administrator" and run viewable init once from this project folder' +
612
- ` - or skip the daemon and run the runner by hand: ${RUNNER_BY_HAND_WINDOWS}`;
686
+ /** One repair instruction for service registration and startup failures. */
687
+ export const COMPUTER_REPAIR = "Open Claude Code or Codex and ask it to install or repair the computer connection.";
688
+ export const ELEVATED_INIT = `Your computer could not connect in the background. ${COMPUTER_REPAIR}`;
613
689
 
614
690
  const schtasks = {
615
691
  kind: "schtasks",
@@ -632,7 +708,7 @@ const schtasks = {
632
708
  env = process.env,
633
709
  exec = execSchtasks,
634
710
  nodePath = process.execPath,
635
- scriptPath = glytchScriptPath(),
711
+ scriptPath = viewableScriptPath(),
636
712
  path = env.PATH ?? env.Path ?? "",
637
713
  force = false,
638
714
  load = true,
@@ -773,15 +849,16 @@ const schtasks = {
773
849
  * GLYTCH_HOME when it is set so the suite writes nowhere systemd reads. */
774
850
  export const unitPath = (env = process.env) =>
775
851
  (env.VIEWABLE_HOME ?? env.GLYTCH_HOME)?.trim()
776
- ? join(glytchHome(env), "systemd", "user", UNIT_NAME)
852
+ ? join(viewableHome(env), "systemd", "user", UNIT_NAME)
777
853
  : join(env.XDG_CONFIG_HOME?.trim() || join(homedir(), ".config"), "systemd", "user", UNIT_NAME);
778
854
 
779
855
  /** The unit, rendered. Every value is quoted: systemd splits ExecStart and
780
856
  * Environment on whitespace otherwise, and a home directory with a space in
781
857
  * it is ordinary. */
782
858
  export function renderUnit({
859
+ launcher,
783
860
  nodePath = process.execPath,
784
- scriptPath = glytchScriptPath(),
861
+ scriptPath = viewableScriptPath(),
785
862
  path = process.env.PATH ?? "",
786
863
  out = logPath(),
787
864
  home,
@@ -794,10 +871,10 @@ After=default.target
794
871
 
795
872
  [Service]
796
873
  Type=simple
797
- ExecStart="${q(nodePath)}" "${q(scriptPath)}" runner watch
874
+ ExecStart="${q(launcher ? "/bin/sh" : nodePath)}" ${launcher ? `"${q(launcher)}" ` : ""}"${q(scriptPath)}" runner watch
798
875
  Environment="PM_SPAWN_RUNNER=on"
799
876
  Environment="PATH=${q(path)}"
800
- ${home ? `Environment="GLYTCH_HOME=${q(home)}"\n` : ""}# KeepAlive, in systemd's words. The mac's plist asks for the same thing.
877
+ ${home ? `Environment="VIEWABLE_HOME=${q(home)}"\n` : ""}# KeepAlive, in systemd's words. The mac's plist asks for the same thing.
801
878
  Restart=always
802
879
  RestartSec=5
803
880
  StandardOutput=append:${out}
@@ -811,14 +888,14 @@ WantedBy=default.target
811
888
  /** The PATH the unit carries, or null. */
812
889
  export function capturedUnitPath(text) {
813
890
  const match = /^Environment="PATH=(.*)"$/m.exec(String(text ?? ""));
814
- return match ? match[1] : null;
891
+ return match ? match[1].replace(/\\"/g, '"') : null;
815
892
  }
816
893
 
817
894
  /** The script path a systemd unit's ExecStart runs - the second quoted
818
895
  * argument, after the node binary - or null. The Linux/WSL half of the same
819
896
  * daemon-version check (brief 31, Move 5). */
820
897
  export function scriptPathFromUnit(text) {
821
- const match = /^ExecStart="[^"]*"\s+"([^"]*)"\s+runner watch\b/m.exec(String(text ?? ""));
898
+ const match = /^ExecStart="[^"]*"\s+(?:"[^"]*runner-launcher\.sh"\s+)?"([^"]*)"\s+runner watch\b/m.exec(String(text ?? ""));
822
899
  return match ? match[1] : null;
823
900
  }
824
901
 
@@ -832,9 +909,6 @@ export const systemctlUnavailable = (result) =>
832
909
  `${result?.stderr ?? ""}`,
833
910
  ) || result?.code === "ENOENT";
834
911
 
835
- /** What to type when there is no systemd to install into. */
836
- export const RUNNER_BY_HAND = "PM_SPAWN_RUNNER=on viewable runner watch";
837
-
838
912
  const systemd = {
839
913
  kind: "systemd",
840
914
  platforms: ["wsl", "linux"],
@@ -854,7 +928,7 @@ const systemd = {
854
928
  env = process.env,
855
929
  exec = execSystemctl,
856
930
  nodePath = process.execPath,
857
- scriptPath = glytchScriptPath(),
931
+ scriptPath = viewableScriptPath(),
858
932
  path = env.PATH ?? "",
859
933
  force = false,
860
934
  load = true,
@@ -866,9 +940,11 @@ const systemd = {
866
940
  return exec(args, env);
867
941
  };
868
942
  await ensureLogDir(env);
943
+ await writePosixLauncher(env, nodePath, force);
869
944
  const wrote = await writeIfAbsent(
870
945
  file,
871
946
  renderUnit({
947
+ launcher: posixLauncherPath(env),
872
948
  nodePath,
873
949
  scriptPath,
874
950
  path,
@@ -877,7 +953,7 @@ const systemd = {
877
953
  }),
878
954
  force,
879
955
  );
880
- if (!load) return { file, wrote, loaded: false, why: "not asked to load", calls };
956
+ if (!load && !wrote) return { file, wrote, loaded: false, why: "not asked to load", calls };
881
957
  // DAEMON-RELOAD FIRST, ALWAYS. systemd caches unit files, so a rewritten
882
958
  // unit that is never re-read keeps running the OLD one - the same failure
883
959
  // the plist's unload-then-load prevents. `enable --now` then both
@@ -886,9 +962,10 @@ const systemd = {
886
962
  const reloaded = await run(["--user", "daemon-reload"]);
887
963
  if (!reloaded.ok) {
888
964
  const unavailable = systemctlUnavailable(reloaded);
889
- return { file, wrote, loaded: false, unavailable,
890
- why: unavailable ? `systemctl --user is not available on your computer: run ${RUNNER_BY_HAND}` : reloaded.stderr?.trim() || "systemctl daemon-reload failed", calls };
965
+ return { file, wrote, loaded: false, reloaded: false, unavailable,
966
+ why: unavailable ? `Your computer cannot connect in the background yet. ${COMPUTER_REPAIR}` : reloaded.stderr?.trim() || "systemctl daemon-reload failed", calls };
891
967
  }
968
+ if (!load) return { file, wrote, loaded: false, reloaded: true, why: "not asked to load", calls };
892
969
  let enabled = await run(["--user", "enable", "--now", UNIT_NAME]);
893
970
  // enable --now leaves an already-running process alone, even after the
894
971
  // file at ExecStart was replaced. Explicit repair/update must reload it.
@@ -902,7 +979,7 @@ const systemd = {
902
979
  why: enabled.ok === true
903
980
  ? ""
904
981
  : unavailable
905
- ? `systemctl --user is not available on your computer: run ${RUNNER_BY_HAND}`
982
+ ? `Your computer cannot connect in the background yet. ${COMPUTER_REPAIR}`
906
983
  : enabled.stderr.trim() || `systemctl --user enable exited ${enabled.code}`,
907
984
  calls,
908
985
  };
@@ -917,7 +994,10 @@ const systemd = {
917
994
  }
918
995
  calls.push(["--user", "disable", "--now", UNIT_NAME]);
919
996
  const result = await exec(["--user", "disable", "--now", UNIT_NAME], env);
920
- if (removeFile) await rm(file, { force: true }).catch(() => {});
997
+ if (removeFile) {
998
+ await rm(file, { force: true }).catch(() => {});
999
+ await rm(posixLauncherPath(env), { force: true }).catch(() => {});
1000
+ }
921
1001
  return {
922
1002
  file,
923
1003
  unloaded: result.ok === true,
@@ -936,7 +1016,7 @@ const systemd = {
936
1016
  loaded: false,
937
1017
  unavailable,
938
1018
  why: unavailable
939
- ? `systemctl --user is not available on your computer: run ${RUNNER_BY_HAND}`
1019
+ ? `Your computer cannot connect in the background yet. ${COMPUTER_REPAIR}`
940
1020
  : result.stderr?.trim() ?? "",
941
1021
  };
942
1022
  },
package/lib/logs.mjs CHANGED
@@ -13,7 +13,7 @@
13
13
 
14
14
  import { appendFile, mkdir, rename, rm, stat } from "node:fs/promises";
15
15
  import { join } from "node:path";
16
- import { glytchHome } from "./registry.mjs";
16
+ import { viewableHome } from "./registry.mjs";
17
17
 
18
18
  /** 5 MB per file, three rotations kept: at most ~20 MB of logs on a machine,
19
19
  * which is small enough never to be noticed and large enough to hold the
@@ -21,7 +21,7 @@ import { glytchHome } from "./registry.mjs";
21
21
  export const LOG_MAX_BYTES = 5 * 1024 * 1024;
22
22
  export const LOG_KEEP = 3;
23
23
 
24
- export const logDir = (env = process.env) => join(glytchHome(env), "logs");
24
+ export const logDir = (env = process.env) => join(viewableHome(env), "logs");
25
25
  export const logPath = (env = process.env) => join(logDir(env), "runner.log");
26
26
 
27
27
  const sizeOf = async (path) => {