@phren/cli 0.3.11 → 0.3.13

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 (182) hide show
  1. package/dist/bridge/account-usage.d.ts +124 -0
  2. package/dist/bridge/account-usage.js +258 -0
  3. package/dist/bridge/agent-hook-stores.d.ts +3 -0
  4. package/dist/bridge/agent-hook-stores.js +5 -0
  5. package/dist/bridge/agent-hooks.d.ts +162 -5
  6. package/dist/bridge/agent-hooks.js +682 -49
  7. package/dist/bridge/approval-summary.d.ts +16 -0
  8. package/dist/bridge/approval-summary.js +133 -0
  9. package/dist/bridge/authority-command.d.ts +20 -0
  10. package/dist/bridge/authority-command.js +120 -0
  11. package/dist/bridge/authority.d.ts +223 -0
  12. package/dist/bridge/authority.js +231 -0
  13. package/dist/bridge/claude-account-setup.d.ts +14 -0
  14. package/dist/bridge/claude-account-setup.js +69 -0
  15. package/dist/bridge/claude-accounts.d.ts +49 -0
  16. package/dist/bridge/claude-accounts.js +195 -0
  17. package/dist/bridge/code-routes.js +2 -2
  18. package/dist/bridge/codex-app-server.d.ts +144 -0
  19. package/dist/bridge/codex-app-server.js +319 -0
  20. package/dist/bridge/codex-auth-refresh.d.ts +33 -0
  21. package/dist/bridge/codex-auth-refresh.js +71 -0
  22. package/dist/bridge/codex-hook-trust.d.ts +27 -0
  23. package/dist/bridge/codex-hook-trust.js +237 -0
  24. package/dist/bridge/codex-question-reply.d.ts +16 -0
  25. package/dist/bridge/codex-question-reply.js +57 -0
  26. package/dist/bridge/codex-review-mode.d.ts +10 -0
  27. package/dist/bridge/codex-review-mode.js +74 -0
  28. package/dist/bridge/codex-servers.d.ts +217 -0
  29. package/dist/bridge/codex-servers.js +636 -0
  30. package/dist/bridge/command.js +97 -4
  31. package/dist/bridge/computer-identity.d.ts +75 -0
  32. package/dist/bridge/computer-identity.js +166 -0
  33. package/dist/bridge/conductor-group.d.ts +91 -8
  34. package/dist/bridge/conductor-group.js +105 -9
  35. package/dist/bridge/conductor-role.d.ts +94 -0
  36. package/dist/bridge/conductor-role.js +176 -0
  37. package/dist/bridge/conductor-sets.d.ts +20 -0
  38. package/dist/bridge/conductor-sets.js +59 -0
  39. package/dist/bridge/dispatch-command.d.ts +3 -0
  40. package/dist/bridge/dispatch-command.js +82 -12
  41. package/dist/bridge/dispatch-returns.d.ts +128 -19
  42. package/dist/bridge/dispatch-returns.js +371 -54
  43. package/dist/bridge/dispatch.d.ts +128 -3
  44. package/dist/bridge/dispatch.js +303 -42
  45. package/dist/bridge/fanouts.d.ts +7 -1
  46. package/dist/bridge/fanouts.js +39 -4
  47. package/dist/bridge/folder-trust.d.ts +56 -0
  48. package/dist/bridge/folder-trust.js +195 -0
  49. package/dist/bridge/grants.d.ts +22 -1
  50. package/dist/bridge/grants.js +57 -9
  51. package/dist/bridge/hand-off-queue.d.ts +74 -0
  52. package/dist/bridge/hand-off-queue.js +235 -0
  53. package/dist/bridge/hand-off.d.ts +30 -10
  54. package/dist/bridge/hand-off.js +79 -46
  55. package/dist/bridge/harness-status.d.ts +11 -0
  56. package/dist/bridge/harness-status.js +32 -0
  57. package/dist/bridge/harnesses.d.ts +39 -0
  58. package/dist/bridge/harnesses.js +65 -0
  59. package/dist/bridge/health.d.ts +2 -0
  60. package/dist/bridge/health.js +1 -1
  61. package/dist/bridge/herdr.d.ts +11 -2
  62. package/dist/bridge/herdr.js +98 -23
  63. package/dist/bridge/hook-fast.d.ts +4 -0
  64. package/dist/bridge/hook-fast.js +68 -0
  65. package/dist/bridge/install.d.ts +16 -1
  66. package/dist/bridge/install.js +102 -21
  67. package/dist/bridge/launch-brief.d.ts +96 -0
  68. package/dist/bridge/launch-brief.js +164 -0
  69. package/dist/bridge/model-switch.d.ts +3 -0
  70. package/dist/bridge/model-switch.js +17 -1
  71. package/dist/bridge/models.d.ts +8 -4
  72. package/dist/bridge/models.js +24 -8
  73. package/dist/bridge/mux-wire.d.ts +9 -0
  74. package/dist/bridge/mux-wire.js +19 -0
  75. package/dist/bridge/opencode-pane-server.d.ts +113 -0
  76. package/dist/bridge/opencode-pane-server.js +332 -0
  77. package/dist/bridge/opencode-panes.d.ts +111 -0
  78. package/dist/bridge/opencode-panes.js +295 -0
  79. package/dist/bridge/pane-accounts.d.ts +8 -0
  80. package/dist/bridge/pane-accounts.js +46 -0
  81. package/dist/bridge/pane-status.d.ts +12 -0
  82. package/dist/bridge/pane-status.js +50 -1
  83. package/dist/bridge/prompt-startup.d.ts +5 -0
  84. package/dist/bridge/prompt-startup.js +24 -0
  85. package/dist/bridge/protocol.d.ts +5 -0
  86. package/dist/bridge/protocol.js +4 -0
  87. package/dist/bridge/push.d.ts +11 -4
  88. package/dist/bridge/push.js +27 -4
  89. package/dist/bridge/questions.d.ts +37 -2
  90. package/dist/bridge/questions.js +158 -15
  91. package/dist/bridge/resources.d.ts +9 -3
  92. package/dist/bridge/resources.js +24 -8
  93. package/dist/bridge/schedule-format.d.ts +2 -0
  94. package/dist/bridge/schedule-format.js +3 -0
  95. package/dist/bridge/schedule-launch.d.ts +2 -1
  96. package/dist/bridge/schedule-launch.js +27 -53
  97. package/dist/bridge/schedule-watch.d.ts +24 -1
  98. package/dist/bridge/schedule-watch.js +89 -2
  99. package/dist/bridge/server-launch.d.ts +22 -5
  100. package/dist/bridge/server-launch.js +238 -32
  101. package/dist/bridge/server-overview.d.ts +10 -3
  102. package/dist/bridge/server-overview.js +32 -15
  103. package/dist/bridge/server-pane-routes.d.ts +3 -0
  104. package/dist/bridge/server-pane-routes.js +150 -18
  105. package/dist/bridge/server-routes.d.ts +11 -0
  106. package/dist/bridge/server-routes.js +214 -36
  107. package/dist/bridge/server-stream.d.ts +2 -0
  108. package/dist/bridge/server-stream.js +22 -8
  109. package/dist/bridge/server.d.ts +6 -1
  110. package/dist/bridge/server.js +58 -13
  111. package/dist/bridge/session-activity.d.ts +93 -0
  112. package/dist/bridge/session-activity.js +139 -0
  113. package/dist/bridge/session-rename.d.ts +48 -0
  114. package/dist/bridge/session-rename.js +190 -0
  115. package/dist/bridge/session-servers.js +2 -2
  116. package/dist/bridge/settings-switch.d.ts +60 -0
  117. package/dist/bridge/settings-switch.js +287 -0
  118. package/dist/bridge/speech-voice.d.ts +55 -0
  119. package/dist/bridge/speech-voice.js +132 -0
  120. package/dist/bridge/speech.d.ts +70 -11
  121. package/dist/bridge/speech.js +169 -41
  122. package/dist/bridge/stalls.d.ts +22 -0
  123. package/dist/bridge/stalls.js +57 -0
  124. package/dist/bridge/sudo.d.ts +209 -0
  125. package/dist/bridge/sudo.js +501 -0
  126. package/dist/bridge/terminal-herdr.js +9 -3
  127. package/dist/bridge/terminal-tmux.d.ts +15 -3
  128. package/dist/bridge/terminal-tmux.js +103 -13
  129. package/dist/bridge/terminal.d.ts +27 -4
  130. package/dist/bridge/terminal.js +8 -1
  131. package/dist/bridge/transcript-claude.d.ts +4 -0
  132. package/dist/bridge/transcript-claude.js +186 -16
  133. package/dist/bridge/transcript-codex.d.ts +0 -2
  134. package/dist/bridge/transcript-codex.js +29 -4
  135. package/dist/bridge/transcript-preview.d.ts +1 -0
  136. package/dist/bridge/transcript-preview.js +24 -4
  137. package/dist/bridge/transcripts.d.ts +15 -2
  138. package/dist/bridge/transcripts.js +47 -16
  139. package/dist/bridge/turn-records.d.ts +85 -0
  140. package/dist/bridge/turn-records.js +143 -0
  141. package/dist/bridge/uploads.d.ts +3 -0
  142. package/dist/bridge/uploads.js +14 -0
  143. package/dist/bridge/usage.d.ts +56 -10
  144. package/dist/bridge/usage.js +190 -45
  145. package/dist/bridge-hook.mjs +27975 -20636
  146. package/dist/cli/claude-unmanaged.d.ts +12 -0
  147. package/dist/cli/claude-unmanaged.js +105 -0
  148. package/dist/cli/schedules.js +2 -1
  149. package/dist/cli/session-start.js +10 -1
  150. package/dist/cli/session-stop.js +9 -1
  151. package/dist/cli-registry.js +31 -6
  152. package/dist/data/task-receipts.d.ts +19 -0
  153. package/dist/data/task-receipts.js +68 -0
  154. package/dist/data/tasks.js +4 -1
  155. package/dist/generated/memory-ui-graph.browser.js +63 -63
  156. package/dist/graph-core/model.js +24 -3
  157. package/dist/graph-core/types.d.ts +4 -1
  158. package/dist/graph-core/types.js +1 -0
  159. package/dist/init/init-preset.js +7 -3
  160. package/dist/init/init-uninstall.js +2 -11
  161. package/dist/init/teardown.d.ts +3 -0
  162. package/dist/init/teardown.js +47 -0
  163. package/dist/link/context.js +21 -9
  164. package/dist/mcp/plugin-mode.js +1 -1
  165. package/dist/memory-ui-graph.runtime.js +63 -63
  166. package/dist/modules/code-package.d.ts +1 -0
  167. package/dist/modules/code-package.js +36 -7
  168. package/dist/modules/registry.js +17 -16
  169. package/dist/profile-store.d.ts +6 -0
  170. package/dist/profile-store.js +25 -1
  171. package/dist/shell/graph/glyphs.js +4 -0
  172. package/dist/shell/graph/graph-view.js +2 -0
  173. package/dist/status.js +7 -1
  174. package/dist/sync/task-claim.js +3 -2
  175. package/dist/task/lifecycle.js +25 -4
  176. package/dist/test-global-setup.js +5 -0
  177. package/dist/tools/dispatch.js +52 -4
  178. package/dist/tools/tasks.js +10 -1
  179. package/package.json +1 -1
  180. package/plugins/opencode/phren-transcript.js +87 -4
  181. package/starter/global/AGENTS.md +4 -0
  182. package/starter/global/skills/conductor/SKILL.md +51 -4
@@ -18,7 +18,8 @@ import { hostname, userInfo } from "node:os";
18
18
  import path from "node:path";
19
19
  import { BridgeError, objects, serverName } from "./protocol.js";
20
20
  import { harnessStatus } from "./harness-status.js";
21
- import { dialogStatus, notePaneStatus, paneStatus } from "./pane-status.js";
21
+ import { dialogStatus, notePaneStatus, paneStatus, startupStatus } from "./pane-status.js";
22
+ import { plainTitle } from "./session-activity.js";
22
23
  import { herdrPanes } from "./terminal-herdr.js";
23
24
  /** The owner's own tmux server (the default socket). */
24
25
  export const TMUX_DEFAULT = "tmux";
@@ -123,7 +124,9 @@ const defaultDeps = {
123
124
  reject(new BridgeError(503, "tmux is not installed on this computer."));
124
125
  return;
125
126
  }
126
- const child = execFile(binary, [...socketFlags(socket), ...args], { timeout: options.timeoutMs ?? 5_000, maxBuffer: 4_194_304, env: tmuxEnvironment(), signal: options.signal }, (error, stdout, stderr) => { if (error)
127
+ // -u: without a UTF-8 locale (launchd and systemd services often have
128
+ // none) tmux 3.7 prints a format's tabs as "_" and no pane parses.
129
+ const child = execFile(binary, ["-u", ...socketFlags(socket), ...args], { timeout: options.timeoutMs ?? 5_000, maxBuffer: 4_194_304, env: tmuxEnvironment(), signal: options.signal }, (error, stdout, stderr) => { if (error)
127
130
  reject(tmuxError(String(stderr), error));
128
131
  else
129
132
  resolve(String(stdout)); });
@@ -218,7 +221,7 @@ function foreground(processes, paneTty) {
218
221
  return processes.filter(p => (p.tty === tty || `tty${p.tty}` === tty) && p.tpgid > 0 && p.pgid === p.tpgid).sort((a, b) => a.pid - b.pid);
219
222
  }
220
223
  const FIELDS = ["session_id", "session_name", "session_attached", "session_activity", "window_id", "window_name", "window_active",
221
- "pane_id", "pane_pid", "pane_tty", "pane_active", "pane_current_path", "pane_current_command", "@phren_agent", "pane_title"];
224
+ "pane_id", "pane_pid", "pane_tty", "pane_active", "pane_current_path", "pane_current_command", "@phren_agent", "pane_title", "@phren_label"];
222
225
  const FORMAT = FIELDS.map(field => `#{${field}}`).join("\t");
223
226
  export function parsePanes(text) {
224
227
  return text.split("\n").flatMap(line => {
@@ -251,7 +254,9 @@ async function agentStatus(server, pane, terminal, agent, pids) {
251
254
  }
252
255
  else
253
256
  status = await paneStatus(server, pane, terminal);
254
- return dialogStatus(server, pane, terminal, agent, status, () => tmuxTerminal.readScreen(server, pane, { scope: "pane", source: "visible", lines: 40, format: "ansi", timeoutMs: 2_000 }));
257
+ const read = () => tmuxTerminal.readScreen(server, pane, { scope: "pane", source: "visible", lines: 40, format: "ansi", timeoutMs: 2_000 });
258
+ // Codex runs SessionStart only with its first turn; until then its screen says.
259
+ return await dialogStatus(server, pane, terminal, agent, status, read) ?? startupStatus(server, pane, terminal, agent, read);
255
260
  }
256
261
  const STATUS_RANK = ["blocked", "waiting", "working", "done", "idle"];
257
262
  /** One tmux server in the shape of the Hook's pane snapshot (the shape
@@ -280,9 +285,10 @@ export async function tmuxSnapshot(server) {
280
285
  // others count as idle until their own records say otherwise.
281
286
  const hooked = agent === "claude" || agent === "codex";
282
287
  const name = row["@phren_agent"] || undefined;
283
- const title = row.pane_title && row.pane_title !== host && row.pane_title !== short ? row.pane_title : undefined;
288
+ // A harness spins a glyph in front of its title while it works.
289
+ const title = row.pane_title && row.pane_title !== host && row.pane_title !== short ? plainTitle(row.pane_title) : undefined;
284
290
  panes.push({ pane_id: pane, tab_id: tab, workspace_id: workspace, terminal_id: terminal, cwd: row.pane_current_path || undefined,
285
- foreground_cwd: row.pane_current_path || undefined, title,
291
+ foreground_cwd: row.pane_current_path || undefined, title, ...(row["@phren_label"] ? { label: row["@phren_label"] } : {}),
286
292
  ...(agent ? { agent, agent_status: status?.status ?? (hooked ? "unknown" : "idle"), ...(status?.seq ? { state_change_seq: status.seq } : {}) } : {}),
287
293
  ...(agent && name ? { agent_name: name } : {}) });
288
294
  if (agent && name)
@@ -304,7 +310,7 @@ export async function tmuxSnapshot(server) {
304
310
  /** The Hook's key names as tmux key names; undefined for a literal character. */
305
311
  export function tmuxKey(key) {
306
312
  const named = { enter: "Enter", esc: "Escape", escape: "Escape", up: "Up", down: "Down", left: "Left", right: "Right",
307
- tab: "Tab", space: "Space", backspace: "BSpace", home: "Home", end: "End", pageup: "PPage", pagedown: "NPage" };
313
+ tab: "Tab", "shift+tab": "BTab", space: "Space", backspace: "BSpace", home: "Home", end: "End", pageup: "PPage", pagedown: "NPage" };
308
314
  if ([...key].length === 1)
309
315
  return undefined;
310
316
  const lower = key.toLowerCase();
@@ -427,7 +433,7 @@ export const tmuxTerminal = {
427
433
  const taken = new Set((await tmux(server, ["list-sessions", "-F", "#{session_name}"]).catch(() => "")).split("\n").filter(Boolean));
428
434
  await tmux(server, ["new-session", "-d", "-s", sessionName(label, taken), "-x", "200", "-y", "50", ...directory, ...name]);
429
435
  },
430
- async startAgent(server, pane, { name, kind, args, timeoutMs }) {
436
+ async startAgent(server, pane, { name, kind, args, timeoutMs, env }) {
431
437
  if (!["claude", "codex", "copilot", "opencode"].includes(kind))
432
438
  throw new BridgeError(400, "This agent cannot be started in tmux.");
433
439
  await requireDirectExec();
@@ -440,7 +446,9 @@ export const tmuxTerminal = {
440
446
  // the pane falls back to that shell when it exits. The harness and its
441
447
  // arguments are the script's positional parameters, never script text.
442
448
  const shell = loginShell();
443
- await tmux(server, ["respawn-pane", "-k", "-t", target, ...(row.pane_current_path ? ["-c", row.pane_current_path] : []),
449
+ // Variables for the agent alone (a dispatch id) ride on the respawn.
450
+ const variables = Object.entries(env ?? {}).flatMap(([key, value]) => ["-e", `${key}=${value}`]);
451
+ await tmux(server, ["respawn-pane", "-k", "-t", target, ...(row.pane_current_path ? ["-c", row.pane_current_path] : []), ...variables,
444
452
  "--", shell, "-l", "-c", 'shell="$1"; shift; "$@"; exec "$shell" -l', "phren", shell, kind, ...args]);
445
453
  // Started once the harness is the pane's foreground program.
446
454
  const deadline = Date.now() + Math.min(timeoutMs, 30_000);
@@ -456,6 +464,17 @@ export const tmuxTerminal = {
456
464
  await deps.sleep(250);
457
465
  }
458
466
  },
467
+ // tmuxPaneFromEnv reads the socket from TMUX's first field and the pane
468
+ // from TMUX_PANE; the server pid and session index are not used.
469
+ paneEnv(server, { pane }) {
470
+ const socket = socketOf(server), folder = tmuxSocketFolders()[0];
471
+ const file = socketPaths.get(socket) ?? (folder ? path.join(folder, socket) : undefined);
472
+ return file ? { TMUX: `${file},0,0`, TMUX_PANE: toTmuxId(pane, "p") } : undefined;
473
+ },
474
+ // A pane user option, not `select-pane -T`: agents overwrite the pane title.
475
+ async renamePane(server, pane, label) {
476
+ await tmux(server, ["set-option", "-p", "-t", toTmuxId(pane, "p"), "@phren_label", label.replace(/[\x00-\x1f\x7f]/g, " ")]);
477
+ },
459
478
  async focusPane(server, pane) {
460
479
  const target = toTmuxId(pane, "p");
461
480
  await tmux(server, ["select-window", "-t", target]);
@@ -495,13 +514,15 @@ async function ownerServers() {
495
514
  }
496
515
  /** The tmux servers the Hook drives, as `/v1/muxes` lists servers: the owner's
497
516
  * servers that answer, and (unless `hidden: false`) the hidden server whenever
498
- * tmux is installed (a launch starts it). `kind` stays "herdr", the phone's name for the Hook's
499
- * session protocol; `terminal` names the multiplexer. */
517
+ * tmux is installed (a launch starts it). An already running hidden server
518
+ * remains discoverable beside Herdr too. `kind` names the actual multiplexer. */
500
519
  export async function tmuxServers(options = {}) {
501
520
  if (!deps.binary())
502
521
  return [];
503
- return [...await ownerServers(), ...(options.hidden ?? true ? [TMUX_HIDDEN] : [])]
504
- .map(name => ({ id: `tmux:${name}`, kind: "herdr", terminal: "tmux", session: name, running: true }));
522
+ const includeHidden = options.hidden ?? true;
523
+ const hiddenRunning = includeHidden || await tmux(TMUX_HIDDEN, ["list-sessions", "-F", "#{session_id}"], { timeoutMs: 3_000 }).then(() => true, () => false);
524
+ return [...await ownerServers(), ...(hiddenRunning ? [TMUX_HIDDEN] : [])]
525
+ .map(name => ({ id: `tmux:${name}`, kind: "tmux", terminal: "tmux", session: name, running: true }));
505
526
  }
506
527
  export async function tmuxHealth() {
507
528
  if (process.env.PHREN_TMUX === "off")
@@ -539,6 +560,75 @@ export async function tmuxPaneFromEnv(env = process.env) {
539
560
  return undefined;
540
561
  }
541
562
  }
563
+ /** The pane of the client that last did anything on `server`: the phone's
564
+ * attach, when it names no pane. */
565
+ async function activeClientPane(server) {
566
+ const rows = (await tmux(server, ["list-clients", "-F", "#{client_activity}\t#{pane_id}"])).split("\n").filter(Boolean).map(row => row.split("\t"));
567
+ const newest = rows.sort((a, b) => Number(b[0]) - Number(a[0]))[0]?.[1];
568
+ if (!newest || !fromTmuxId(newest))
569
+ throw new BridgeError(409, "No terminal is attached to this tmux server.");
570
+ return newest;
571
+ }
572
+ /**
573
+ * Scrolls one pane for a phone whose terminal gets no wheel events of its
574
+ * own: a server with `mouse off` (tmux's default) never turns on the phone's
575
+ * mouse reporting, and tmux draws on the alternate screen, so the phone has
576
+ * no local history either. Does what tmux's default WheelUpPane binding does:
577
+ * an app tracking the mouse (Claude, Codex) gets wheel events, and anything
578
+ * else scrolls in `copy-mode -e`, which ends by itself at the bottom.
579
+ * `lines` > 0 is older output; 0 leaves copy mode so typing reaches the pane.
580
+ */
581
+ export async function tmuxScroll(server, pane, lines) {
582
+ const target = pane ? toTmuxId(pane, "p") : await activeClientPane(server);
583
+ // One scroll per pane at a time: two overlapping swipes could otherwise
584
+ // enter and cancel copy mode out of order and leave the pane in it, where
585
+ // it would swallow the next typed prompt.
586
+ const key = `${server}\0${target}`;
587
+ const run = (scrollQueues.get(key) ?? Promise.resolve()).then(() => scrollPane(server, target, lines), () => scrollPane(server, target, lines));
588
+ const settled = run.catch(() => undefined);
589
+ scrollQueues.set(key, settled);
590
+ void settled.then(() => { if (scrollQueues.get(key) === settled)
591
+ scrollQueues.delete(key); });
592
+ return run;
593
+ }
594
+ const scrollQueues = new Map();
595
+ async function scrollPane(server, target, lines) {
596
+ const state = async () => {
597
+ const [mode, mouse, sgr, width, height] = (await tmux(server, ["display-message", "-p", "-t", target,
598
+ "#{pane_mode}\t#{mouse_any_flag}\t#{mouse_sgr_flag}\t#{pane_width}\t#{pane_height}"])).replace(/\n$/, "").split("\t");
599
+ return { mode, mouse: mouse === "1", sgr: sgr === "1", width: Number(width) || 80, height: Number(height) || 24 };
600
+ };
601
+ const before = await state();
602
+ const copy = before.mode === "copy-mode";
603
+ if (lines === 0) {
604
+ if (copy)
605
+ await tmux(server, ["send-keys", "-t", target, "-X", "cancel"]);
606
+ return { history: false };
607
+ }
608
+ // Another mode (the tree chooser, the clock) is the owner's; leave it.
609
+ if (before.mode && !copy)
610
+ return { history: false };
611
+ if (!copy && before.mouse) {
612
+ // tmux's `send -M`, as raw bytes: a paste without brackets reaches the
613
+ // app as typed input. The pane's middle keeps X10 coordinates ASCII.
614
+ const button = lines > 0 ? 64 : 65;
615
+ const x = Math.min(95, Math.ceil(before.width / 2)), y = Math.min(95, Math.ceil(before.height / 2));
616
+ const event = before.sgr ? `\x1b[<${button};${x};${y}M` : `\x1b[M${String.fromCharCode(32 + button, 32 + x, 32 + y)}`;
617
+ const buffer = `phren-scroll-${process.pid}-${Date.now().toString(36)}`;
618
+ await tmux(server, ["load-buffer", "-b", buffer, "-"], { input: event.repeat(Math.abs(lines)) });
619
+ // Newer tmux shows a paste's control characters as text (ESC as "^[")
620
+ // unless -S, a flag older tmux, which pastes them as they are, refuses.
621
+ const paste = (flags) => tmux(server, ["paste-buffer", ...flags, "-d", "-r", "-b", buffer, "-t", target]);
622
+ await paste(["-S"]).catch(error => /unknown flag|invalid option/i.test(String(error?.message)) ? paste([]) : Promise.reject(error));
623
+ return { history: false };
624
+ }
625
+ if (lines < 0 && !copy)
626
+ return { history: false };
627
+ if (!copy)
628
+ await tmux(server, ["copy-mode", "-e", "-t", target]);
629
+ await tmux(server, ["send-keys", "-t", target, "-X", "-N", String(Math.abs(lines)), lines > 0 ? "scroll-up" : "scroll-down"]);
630
+ return { history: (await state()).mode === "copy-mode" };
631
+ }
542
632
  /** The command that attaches the phone's SSH terminal to a tmux server. */
543
633
  export function tmuxAttach(server) {
544
634
  const binary = deps.binary();
@@ -50,22 +50,28 @@ export interface ScreenRead {
50
50
  format?: "ansi";
51
51
  timeoutMs?: number;
52
52
  }
53
- /** A new pane: a tab in `workspace`, or a new workspace when it is absent. */
53
+ /** A new pane: a tab in `workspace`, or a new workspace when it is absent.
54
+ * `env` is added to the pane's shell environment, so an agent started there
55
+ * inherits it (Herdr takes variables only here, at pane creation). */
54
56
  export interface PanePlacement {
55
57
  workspace?: string;
56
58
  label?: string;
57
59
  cwd?: string;
60
+ env?: Record<string, string>;
58
61
  }
59
- /** Starts an agent in an existing, empty pane. */
62
+ /** Starts an agent in an existing, empty pane. `env` is the same variables as
63
+ * the pane's placement, for a provider that starts the agent in a fresh
64
+ * process of its own (tmux respawns the pane). */
60
65
  export interface AgentStart {
61
66
  name: string;
62
67
  kind: string;
63
68
  args: string[];
64
69
  timeoutMs: number;
70
+ env?: Record<string, string>;
65
71
  }
66
72
  /**
67
73
  * Key names are the Hook's vocabulary: "enter", "esc", "up", "down", "tab",
68
- * "space", "alt+Up" and single characters. A provider maps them to its own.
74
+ * "space", "shift+tab", "alt+Up" and single characters. A provider maps them to its own.
69
75
  *
70
76
  * Every method rejects with a BridgeError when the multiplexer refuses or is
71
77
  * unreachable; the message is shown to the phone.
@@ -89,12 +95,23 @@ export interface TerminalProvider {
89
95
  processes(server: string, pane: string): Promise<PaneProcesses>;
90
96
  readScreen(server: string, pane: string, read: ScreenRead): Promise<string>;
91
97
  sendKeys(server: string, pane: string, keys: string[]): Promise<void>;
92
- /** Types `text` into the pane's agent and submits it. */
98
+ /** Types `text` and sends the submit key. Success acknowledges transport,
99
+ * not a submitted turn; the harness must confirm that separately. */
93
100
  prompt(server: string, pane: string, text: string, signal?: AbortSignal): Promise<void>;
94
101
  /** Opens a pane; the caller finds it in the next `listPanes`. */
95
102
  create(server: string, placement: PanePlacement): Promise<void>;
96
103
  startAgent(server: string, pane: string, agent: AgentStart): Promise<void>;
104
+ /** The variables a process started for `pane` outside it needs to be
105
+ * recognized as running there (a Codex app-server whose hooks report the
106
+ * pane). Absent where the multiplexer has none. */
107
+ paneEnv?(server: string, place: {
108
+ workspace: string;
109
+ tab: string;
110
+ pane: string;
111
+ }): Record<string, string> | undefined;
97
112
  focusPane(server: string, pane: string): Promise<void>;
113
+ /** Sets the pane's own label (Herdr's pane label, a tmux pane option), shown by the Hook as the session's name. */
114
+ renamePane(server: string, pane: string, label: string): Promise<void>;
98
115
  /** Focuses, renames or closes a whole tab (when `tab` is set) or workspace. */
99
116
  groupAction(server: string, operation: "focus" | "rename" | "close", group: {
100
117
  workspace?: string;
@@ -107,6 +124,12 @@ export interface TerminalProvider {
107
124
  export declare function terminalKind(server: string): "herdr" | "tmux";
108
125
  /** The multiplexer's name as the phone shows it in messages. */
109
126
  export declare function terminalName(server: string): string;
127
+ /** Stable source identity for overview/pane replies; agent source remains its harness. */
128
+ export declare function terminalMux(server: string): {
129
+ id: string;
130
+ kind: "herdr" | "tmux";
131
+ session: string;
132
+ };
110
133
  /** The provider for each server by its name: Herdr's or tmux's. */
111
134
  export declare const routedTerminal: TerminalProvider;
112
135
  /** True when a start or prompt was refused because the agent is still
@@ -1,5 +1,5 @@
1
1
  // What the Hook needs from the terminal multiplexer its agents run in: Herdr
2
- // (terminal-herdr.ts) or, on a computer without it, tmux (terminal-tmux.ts).
2
+ // (terminal-herdr.ts) and tmux (terminal-tmux.ts), including both on one computer.
3
3
  // Nothing Herdr- or tmux-specific may leak past a provider's own file.
4
4
  //
5
5
  // Identity (which conversation a pane runs) and agent status are not the
@@ -33,6 +33,11 @@ export function terminalKind(server) {
33
33
  }
34
34
  /** The multiplexer's name as the phone shows it in messages. */
35
35
  export function terminalName(server) { return terminalKind(server) === "tmux" ? "tmux" : "Herdr"; }
36
+ /** Stable source identity for overview/pane replies; agent source remains its harness. */
37
+ export function terminalMux(server) {
38
+ const kind = terminalKind(server);
39
+ return { id: `${kind}:${server}`, kind, session: server };
40
+ }
36
41
  const route = (server) => terminalKind(server) === "tmux" ? tmuxTerminal : herdrTerminal;
37
42
  /** The provider for each server by its name: Herdr's or tmux's. */
38
43
  export const routedTerminal = {
@@ -46,7 +51,9 @@ export const routedTerminal = {
46
51
  prompt: (server, pane, text, signal) => route(server).prompt(server, pane, text, signal),
47
52
  create: (server, placement) => route(server).create(server, placement),
48
53
  startAgent: (server, pane, agent) => route(server).startAgent(server, pane, agent),
54
+ paneEnv: (server, place) => route(server).paneEnv?.(server, place),
49
55
  focusPane: (server, pane) => route(server).focusPane(server, pane),
56
+ renamePane: (server, pane, label) => route(server).renamePane(server, pane, label),
50
57
  groupAction: (server, operation, group, label) => route(server).groupAction(server, operation, group, label),
51
58
  };
52
59
  /** True when a start or prompt was refused because the agent is still
@@ -7,6 +7,10 @@ import type { ChildAgentRelation } from "./transcripts.js";
7
7
  * and a worktree already removed is not offered. */
8
8
  export declare function claudeChildCheckout(file: string): Promise<Pick<ChildAgentRelation, "cwd" | "worktreeName" | "branch">>;
9
9
  export declare function claudeChildAgents(file: string, session: string): Promise<ChildAgentRelation[]>;
10
+ /** How long a background skill's transcript may sit unchanged before it is
11
+ * taken as finished: the parent records no end for it, and a session that
12
+ * exited mid-skill leaves it without a final reply. */
13
+ export declare const CLAUDE_SKILL_QUIET_MS: number;
10
14
  export declare const harnessPreamble: (text: string) => boolean;
11
15
  export declare function unwrapPastedContent(text: string): string;
12
16
  /** A thinking block Claude marks as narration for the person watching: its
@@ -92,6 +92,13 @@ export async function claudeChildAgents(file, session) {
92
92
  return cached.relations;
93
93
  }
94
94
  const launches = new Map();
95
+ const stops = new Map();
96
+ // A background skill (`/code-review` run as `@code-review`) is announced in
97
+ // a local-command row, not a tool result, and its end is read from its own
98
+ // transcript (claudeSkillFinished).
99
+ const skills = new Set();
100
+ // A Workflow run, by its task id: its agents are in the run's journal.
101
+ const workflows = new Map();
95
102
  // Named teammates (the Agent tool with a `name`) run as their own session
96
103
  // and never post a task-notification: they announce themselves idle in a
97
104
  // teammate-message instead, and may be woken again later. Their file is
@@ -101,15 +108,38 @@ export async function claudeChildAgents(file, session) {
101
108
  for await (const line of lines) {
102
109
  try {
103
110
  const raw = object(JSON.parse(line)), result = object(raw.toolUseResult);
111
+ const blocks = objects(object(raw.message).content);
104
112
  const agentId = String(result.agentId ?? ""), status = String(result.status ?? "");
105
113
  if (/^[A-Za-z0-9._-]{1,128}$/.test(agentId) && ["async_launched", "running"].includes(status)) {
106
- const blocks = objects(object(raw.message).content), callId = String(blocks.find(b => b.type === "tool_result")?.tool_use_id ?? "");
114
+ const callId = String(blocks.find(b => b.type === "tool_result")?.tool_use_id ?? "");
107
115
  if (callId)
108
116
  launches.set(agentId, { path: String(result.description || result.name || "Agent").slice(0, 200), callId, state: "running" });
109
117
  }
118
+ // SendMessage to a finished agent resumes it until its next final notification.
119
+ const resumed = typeof result.resumedAgentId === "string" ? launches.get(result.resumedAgentId) : undefined;
120
+ if (resumed && typeof result.message === "string" && /^Resuming agent\b/i.test(result.message))
121
+ resumed.state = "running";
122
+ if (result.taskType === "local_workflow" && status === "async_launched" && typeof result.taskId === "string"
123
+ && typeof result.runId === "string" && /^wf_[A-Za-z0-9-]{1,64}$/.test(result.runId)) {
124
+ const callId = String(blocks.find(b => b.type === "tool_result")?.tool_use_id ?? "");
125
+ workflows.set(result.taskId, { runId: result.runId, name: String(result.workflowName || "Workflow").slice(0, 200), callId, state: "running" });
126
+ }
127
+ if (raw.type === "system" && typeof raw.content === "string" && raw.content.includes("<forked-skill-launch>")) {
128
+ const launch = object(JSON.parse(/<forked-skill-launch>([\s\S]*?)<\/forked-skill-launch>/.exec(raw.content)?.[1] ?? "{}"));
129
+ const id = String(launch.agentId ?? "");
130
+ if (/^[A-Za-z0-9._-]{1,128}$/.test(id)) {
131
+ launches.set(id, { path: String(launch.description || (launch.skillName ? `/${launch.skillName}` : "Skill")).slice(0, 200), callId: `skill:${id}`, state: "running" });
132
+ skills.add(id);
133
+ }
134
+ }
110
135
  if (raw.type === "assistant") {
111
- for (const block of objects(object(raw.message).content)) {
112
- if (block.type !== "tool_use" || block.name !== "Agent")
136
+ for (const block of blocks) {
137
+ if (block.type !== "tool_use")
138
+ continue;
139
+ if (block.name === "TaskStop" && typeof block.id === "string" && typeof object(block.input).task_id === "string") {
140
+ stops.set(block.id, String(object(block.input).task_id));
141
+ }
142
+ if (block.name !== "Agent")
113
143
  continue;
114
144
  const input = object(block.input), name = String(input.name ?? "");
115
145
  if (!/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(name) || typeof block.id !== "string")
@@ -117,14 +147,35 @@ export async function claudeChildAgents(file, session) {
117
147
  teammates.set(name, { path: String(input.description || name).slice(0, 200), callId: block.id.slice(0, 200), state: "running" });
118
148
  }
119
149
  }
150
+ // A stop request alone proves nothing. Its successful, matching result
151
+ // ends the child even when no later task notification is recorded.
152
+ if (raw.type === "user") {
153
+ for (const block of blocks) {
154
+ if (block.type !== "tool_result" || typeof block.tool_use_id !== "string")
155
+ continue;
156
+ const task = stops.get(block.tool_use_id);
157
+ if (!task)
158
+ continue;
159
+ stops.delete(block.tool_use_id);
160
+ const previous = launches.get(task) ?? workflows.get(task);
161
+ if (previous && block.is_error !== true && result.task_id === task && typeof result.message === "string"
162
+ && /^Successfully stopped task\b/i.test(result.message))
163
+ previous.state = "completed";
164
+ }
165
+ }
120
166
  const content = typeof raw.content === "string" ? raw.content : typeof object(raw.message).content === "string" ? String(object(raw.message).content) : "";
121
- if (content.includes("<task-notification>")) {
122
- const child = /<task-id>([^<>]{1,128})<\/task-id>/.exec(content)?.[1], taskStatus = /<status>([^<>]+)<\/status>/.exec(content)?.[1];
123
- // A stopped agent's notification says "killed"; it is finished as
124
- // much as a completed one and must leave the running count.
125
- const previous = child && launches.get(child);
126
- if (previous && ["completed", "failed", "cancelled", "killed"].includes(taskStatus ?? ""))
127
- previous.state = "completed";
167
+ const attachment = object(raw.attachment);
168
+ const notices = [raw.type === "queue-operation" || raw.type === "user" ? content : "",
169
+ ...(raw.type === "user" ? blocks.filter(block => block.type === "text" && typeof block.text === "string").map(block => String(block.text)) : []),
170
+ raw.type === "attachment" && attachment.type === "queued_command" && attachment.commandMode === "task-notification" && typeof attachment.prompt === "string" ? attachment.prompt : ""];
171
+ for (const notice of notices) {
172
+ for (const match of notice.matchAll(/<task-notification>([\s\S]*?)<\/task-notification>/g)) {
173
+ const child = /<task-id>([^<>]{1,128})<\/task-id>/.exec(match[1])?.[1], taskStatus = /<status>([^<>]+)<\/status>/.exec(match[1])?.[1].trim();
174
+ // Terminal notifications end only the child named in that envelope.
175
+ const previous = child && (launches.get(child) ?? workflows.get(child));
176
+ if (previous && ["completed", "failed", "cancelled", "canceled", "killed", "stopped"].includes(taskStatus ?? ""))
177
+ previous.state = "completed";
178
+ }
128
179
  }
129
180
  if (content.includes("<teammate-message")) {
130
181
  const from = /<teammate-message teammate_id="([A-Za-z0-9][A-Za-z0-9_-]{0,63})"/.exec(content)?.[1];
@@ -139,7 +190,9 @@ export async function claudeChildAgents(file, session) {
139
190
  // Claude Code records the launch in the parent before the child's own
140
191
  // file exists. A launch without a transcript yet is looked for again
141
192
  // shortly, rather than being missed until the parent next changes.
142
- let awaiting = false;
193
+ // Children whose end the parent does not record (background skills,
194
+ // workflow agents) are looked at again on a timer too.
195
+ let awaiting = false, live = false;
143
196
  const root = await realpath(path.join(path.dirname(file), session, "subagents")).catch(() => undefined);
144
197
  for (const [agentId, launch] of launches) {
145
198
  const childFile = root && await realpath(path.join(root, `agent-${agentId}.jsonl`)).catch(() => undefined);
@@ -148,6 +201,12 @@ export async function claudeChildAgents(file, session) {
148
201
  awaiting = true;
149
202
  continue;
150
203
  }
204
+ if (skills.has(agentId) && launch.state === "running") {
205
+ if (await claudeSkillFinished(childFile).catch(() => false))
206
+ launch.state = "completed";
207
+ else
208
+ live = true;
209
+ }
151
210
  const model = await claudeChildModel(childFile).catch(() => undefined);
152
211
  const checkout = await claudeChildCheckout(childFile).catch(() => ({}));
153
212
  relations.push({ id: createHash("sha256").update(`claude\0${session}\0${agentId}`).digest("hex").slice(0, 32),
@@ -155,10 +214,21 @@ export async function claudeChildAgents(file, session) {
155
214
  ...(model !== undefined ? { model } : {}), ...checkout, children: [] });
156
215
  }
157
216
  if (teammates.size && root) {
158
- const names = (await readdir(root).catch(() => [])).filter(n => /^agent-a[A-Za-z0-9][A-Za-z0-9_-]{0,63}-[0-9a-f]{8,32}\.jsonl$/.test(n));
217
+ const entries = await readdir(root).catch(() => []);
218
+ const names = entries.filter(n => /^agent-a[A-Za-z0-9][A-Za-z0-9_-]{0,63}-[0-9a-f]{8,32}\.jsonl$/.test(n));
219
+ // Claude Code 2.1.2xx names a teammate's file by id and keeps its name in
220
+ // the `.meta.json` beside it.
221
+ let named;
159
222
  for (const [name, launch] of teammates) {
160
- const fileName = names.find(n => n.startsWith(`agent-a${name}-`));
223
+ let fileName = names.find(n => n.startsWith(`agent-a${name}-`));
224
+ if (!fileName) {
225
+ named ??= await claudeChildNames(root, entries);
226
+ fileName = named.get(name);
227
+ }
161
228
  const agentId = fileName?.slice("agent-".length, -".jsonl".length);
229
+ // A named agent launched in the background is already listed by its launch.
230
+ if (agentId && launches.has(agentId))
231
+ continue;
162
232
  const childFile = agentId && await realpath(path.join(root, fileName)).catch(() => undefined);
163
233
  if (!agentId || !childFile || !childFile.startsWith(root + path.sep) || !await claudeChildBelongsTo(childFile, session, agentId)) {
164
234
  if (launch.state === "running")
@@ -175,11 +245,94 @@ export async function claudeChildAgents(file, session) {
175
245
  ...(model !== undefined ? { model } : {}), ...checkout, children: [] });
176
246
  }
177
247
  }
178
- claudeRelationCache.set(file, { signature, relations, ...(awaiting ? { recheckAt: Date.now() + 2_000 } : {}) });
248
+ if (workflows.size && root) {
249
+ const seen = new Set(relations.map(relation => relation.session));
250
+ for (const workflow of workflows.values()) {
251
+ for (const child of await claudeWorkflowAgents(root, session, workflow)) {
252
+ if (seen.has(child.session))
253
+ continue;
254
+ seen.add(child.session);
255
+ relations.push(child);
256
+ if (child.state === "running")
257
+ live = true;
258
+ }
259
+ }
260
+ }
261
+ claudeRelationCache.set(file, { signature, relations, ...(awaiting || live ? { recheckAt: Date.now() + (awaiting ? 2_000 : 5_000) } : {}) });
179
262
  while (claudeRelationCache.size > 64)
180
263
  claudeRelationCache.delete(claudeRelationCache.keys().next().value);
181
264
  return relations;
182
265
  }
266
+ /** How long a background skill's transcript may sit unchanged before it is
267
+ * taken as finished: the parent records no end for it, and a session that
268
+ * exited mid-skill leaves it without a final reply. */
269
+ export const CLAUDE_SKILL_QUIET_MS = 30 * 60 * 1000;
270
+ /** A background skill is done once its transcript ends on a finished reply,
271
+ * or has not changed for CLAUDE_SKILL_QUIET_MS. */
272
+ async function claudeSkillFinished(file, now = Date.now()) {
273
+ const metadata = await stat(file);
274
+ if (now - metadata.mtimeMs >= CLAUDE_SKILL_QUIET_MS)
275
+ return true;
276
+ const start = Math.max(0, metadata.size - 65_536), chunks = [];
277
+ for await (const chunk of createReadStream(file, { start }))
278
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
279
+ const last = Buffer.concat(chunks).toString("utf8").split("\n").filter(line => line.trim()).at(-1);
280
+ try {
281
+ const raw = object(JSON.parse(last ?? ""));
282
+ return raw.type === "assistant" && object(raw.message).stop_reason === "end_turn";
283
+ }
284
+ catch {
285
+ return false;
286
+ }
287
+ }
288
+ /** Sub-agent files by the name their `.meta.json` gives them. */
289
+ async function claudeChildNames(root, entries) {
290
+ const names = new Map();
291
+ for (const entry of entries) {
292
+ if (!/^agent-[A-Za-z0-9._-]{1,128}\.meta\.json$/.test(entry))
293
+ continue;
294
+ const meta = await readFile(path.join(root, entry), "utf8").then(v => object(JSON.parse(v))).catch(() => ({}));
295
+ if (typeof meta.name === "string" && /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(meta.name))
296
+ names.set(meta.name, entry.slice(0, -".meta.json".length) + ".jsonl");
297
+ }
298
+ return names;
299
+ }
300
+ /** A Workflow run's agents from its journal: each `started` agent runs until
301
+ * the journal records another row for it or the run itself finishes. */
302
+ async function claudeWorkflowAgents(root, session, workflow) {
303
+ const directory = await realpath(path.join(root, "workflows", workflow.runId)).catch(() => undefined);
304
+ if (!directory || !directory.startsWith(root + path.sep))
305
+ return [];
306
+ const journal = path.join(directory, "journal.jsonl");
307
+ const info = await stat(journal).catch(() => undefined);
308
+ if (!info?.isFile() || info.size > 16 * 1024 * 1024)
309
+ return [];
310
+ const agents = new Map();
311
+ for (const line of (await readFile(journal, "utf8")).split("\n")) {
312
+ try {
313
+ const row = object(JSON.parse(line)), id = String(row.agentId ?? "");
314
+ if (!/^[A-Za-z0-9._-]{1,128}$/.test(id))
315
+ continue;
316
+ agents.set(id, row.type === "started" ? agents.get(id) ?? false : true);
317
+ }
318
+ catch { /* A row still being written. */ }
319
+ }
320
+ const relations = [];
321
+ for (const [agentId, done] of agents) {
322
+ const childFile = await realpath(path.join(directory, `agent-${agentId}.jsonl`)).catch(() => undefined);
323
+ if (!childFile || !childFile.startsWith(directory + path.sep) || !await claudeChildBelongsTo(childFile, session, agentId))
324
+ continue;
325
+ const meta = await readFile(childFile.slice(0, -".jsonl".length) + ".meta.json", "utf8").then(v => object(JSON.parse(v))).catch(() => ({}));
326
+ const model = await claudeChildModel(childFile).catch(() => undefined);
327
+ const checkout = await claudeChildCheckout(childFile).catch(() => ({}));
328
+ relations.push({ id: createHash("sha256").update(`claude\0${session}\0${agentId}`).digest("hex").slice(0, 32),
329
+ session: agentId, transcript: childFile, provider: "claude",
330
+ path: String(meta.description || workflow.name).slice(0, 200), callId: workflow.callId || `workflow:${workflow.runId}`,
331
+ state: done || workflow.state === "completed" ? "completed" : "running",
332
+ ...(model !== undefined ? { model } : {}), ...checkout, children: [] });
333
+ }
334
+ return relations;
335
+ }
183
336
  async function claudeChildBelongsTo(file, parent, agentId) {
184
337
  let bytes = Buffer.alloc(0);
185
338
  for await (const chunk of createReadStream(file, { start: 0, end: 1_048_575 })) {
@@ -199,7 +352,10 @@ async function claudeChildBelongsTo(file, parent, agentId) {
199
352
  return false;
200
353
  }
201
354
  }
202
- const CLAUDE_KEYS = new Set(["type", "uuid", "parentUuid", "timestamp", "message", "gitBranch", "cwd", "requestId", "isMeta", "isSidechain", "isCompactSummary", "phrenQueued", "phrenQueueKey", "phrenBackground", "phrenCompacted"]);
355
+ // `effort` rides on each assistant row (Claude Code 2.1): with `message.model`
356
+ // it is what the phone's model chip shows as in effect. `permissionMode` on a
357
+ // user row is the mode that turn ran in (the phone's permission chip).
358
+ const CLAUDE_KEYS = new Set(["type", "uuid", "parentUuid", "timestamp", "message", "gitBranch", "cwd", "requestId", "isMeta", "isSidechain", "isCompactSummary", "phrenQueued", "phrenQueueKey", "phrenBackground", "phrenCompacted", "effort", "permissionMode"]);
203
359
  export const harnessPreamble = (text) => /^<(?:environment_context>|user_instructions>|permission_profile|system-reminder>|turn_context>)/.test(text.trimStart());
204
360
  function taskNotification(content) {
205
361
  const envelope = /<task-notification>([\s\S]*?)<\/task-notification>/.exec(content)?.[1];
@@ -273,6 +429,11 @@ export function skillBody(raw) {
273
429
  return { type: "user", timestamp: raw.timestamp, ...(typeof raw.uuid === "string" ? { uuid: raw.uuid } : {}),
274
430
  message: { role: "user", content: [{ type: "tool_result", tool_use_id: raw.sourceToolUseID, content: text.slice(0, 32_768), phrenSkillBody: true }] } };
275
431
  }
432
+ /** Claude Code's label where a pasted picture path was, and the footer the
433
+ * phone puts above the paths of the files it attached. */
434
+ const QUEUED_IMAGE_LABEL = /\[Image #\d+\]/;
435
+ const QUEUED_IMAGE_LABELS = /\[Image #\d+\]/g;
436
+ const ATTACHED_FILES_FOOTER = /Attached files on this computer:\s*$/;
276
437
  /** A phren UserPromptSubmit injection, as `{ type: "phren_hook_context",
277
438
  * parentUuid, content }`, or undefined for any other row. */
278
439
  export function phrenHookContext(raw, includeSidechain = false) {
@@ -336,8 +497,13 @@ export function visibleClaudeEvent(raw, includeSidechain = false) {
336
497
  // tool envelope, private metadata, or reasoning is exported.
337
498
  if (raw.operation === "remove")
338
499
  return { type: "phren_queue_consumed", key, timestamp: raw.timestamp };
500
+ // A picture sent mid-turn queues as "[Image #7]Attached files on this
501
+ // computer:": the pixels never reach this row. Words-free, it matched no
502
+ // receipt, and the phone warned "Not confirmed in chat" about a picture
503
+ // the agent had taken. Name it the way a picture-only turn reads.
504
+ const pictureOnly = QUEUED_IMAGE_LABEL.test(text) && !text.replace(QUEUED_IMAGE_LABELS, "").replace(ATTACHED_FILES_FOOTER, "").trim();
339
505
  return { type: "user", phrenQueued: true, phrenQueueKey: key, timestamp: raw.timestamp,
340
- message: { role: "user", content: text } };
506
+ message: { role: "user", content: pictureOnly ? "[Image attachment]" : text } };
341
507
  }
342
508
  // Claude Code appends a boundary marker and then the summary it hands the
343
509
  // model as a user turn. The phone shows the marker and a bounded preview,
@@ -359,6 +525,10 @@ export function visibleClaudeEvent(raw, includeSidechain = false) {
359
525
  const skill = skillBody(raw);
360
526
  if (skill)
361
527
  return skill;
528
+ // The row Claude writes when the permission mode changes; nothing else of it.
529
+ if (raw.type === "permission-mode" && typeof raw.permissionMode === "string" && /^[A-Za-z]{1,30}$/.test(raw.permissionMode)) {
530
+ return { type: "permission-mode", permissionMode: raw.permissionMode, ...(typeof raw.timestamp === "string" ? { timestamp: raw.timestamp } : {}) };
531
+ }
362
532
  if (raw.isMeta || (raw.isSidechain && !includeSidechain) || !["user", "assistant", "system"].includes(String(raw.type)))
363
533
  return undefined;
364
534
  raw = Object.fromEntries(Object.entries(raw).filter(([key]) => CLAUDE_KEYS.has(key)));
@@ -5,8 +5,6 @@ import type { Entry, LocalChildAgentRelation } from "./transcripts.js";
5
5
  export type DirectRelation = Pick<LocalChildAgentRelation, "session" | "path" | "callId" | "state">;
6
6
  export declare function directChildAgents(file: string): Promise<DirectRelation[]>;
7
7
  export declare function childTranscriptBelongsTo(file: string, parent: string): Promise<boolean>;
8
- /** Codex rows the phone may see: public messages, tool calls and their
9
- * outputs, the answering model, and turn/usage events. */
10
8
  export declare function visibleCodexEvent(raw: Json): Json | undefined;
11
9
  export interface CodeModeWrapper {
12
10
  callId: string;