@phren/cli 0.3.71 → 0.3.73

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 (164) hide show
  1. package/dist/bridge/agent-hooks.js +11 -1
  2. package/dist/bridge/browser-env.d.ts +5 -0
  3. package/dist/bridge/browser-env.js +110 -0
  4. package/dist/bridge/browser-protocol.d.ts +120 -0
  5. package/dist/bridge/browser-protocol.js +70 -0
  6. package/dist/bridge/browser-recordings.d.ts +63 -0
  7. package/dist/bridge/browser-recordings.js +148 -0
  8. package/dist/bridge/browser-registry.d.ts +64 -0
  9. package/dist/bridge/browser-registry.js +262 -0
  10. package/dist/bridge/browser-routes.d.ts +4 -0
  11. package/dist/bridge/browser-routes.js +39 -0
  12. package/dist/bridge/browser-shim/phren-playwright.cjs +184 -0
  13. package/dist/bridge/browser-socket.d.ts +2 -0
  14. package/dist/bridge/browser-socket.js +10 -0
  15. package/dist/bridge/browser-stream.d.ts +3 -0
  16. package/dist/bridge/browser-stream.js +129 -0
  17. package/dist/bridge/browser-watch.d.ts +12 -0
  18. package/dist/bridge/browser-watch.js +83 -0
  19. package/dist/bridge/claude-account-setup.js +3 -1
  20. package/dist/bridge/claude-accounts.d.ts +5 -1
  21. package/dist/bridge/claude-accounts.js +36 -6
  22. package/dist/bridge/codex-servers.d.ts +2 -0
  23. package/dist/bridge/codex-servers.js +1 -1
  24. package/dist/bridge/command.js +24 -5
  25. package/dist/bridge/dispatch-clone.d.ts +33 -0
  26. package/dist/bridge/dispatch-clone.js +176 -0
  27. package/dist/bridge/dispatch-command.d.ts +14 -0
  28. package/dist/bridge/dispatch-command.js +98 -13
  29. package/dist/bridge/dispatch-idempotency.d.ts +85 -0
  30. package/dist/bridge/dispatch-idempotency.js +235 -0
  31. package/dist/bridge/dispatch-returns.d.ts +6 -0
  32. package/dist/bridge/dispatch-returns.js +131 -1
  33. package/dist/bridge/dispatch-wait.d.ts +32 -0
  34. package/dist/bridge/dispatch-wait.js +177 -0
  35. package/dist/bridge/dispatch.d.ts +78 -2
  36. package/dist/bridge/dispatch.js +841 -25
  37. package/dist/bridge/dream-schedule.d.ts +133 -0
  38. package/dist/bridge/dream-schedule.js +322 -0
  39. package/dist/bridge/fanouts.js +20 -3
  40. package/dist/bridge/files.d.ts +1 -1
  41. package/dist/bridge/git-credential.d.ts +44 -0
  42. package/dist/bridge/git-credential.js +113 -0
  43. package/dist/bridge/git-host-auth.d.ts +9 -1
  44. package/dist/bridge/git-host-auth.js +18 -5
  45. package/dist/bridge/git-host-gitboy.js +8 -1
  46. package/dist/bridge/git-hosts.d.ts +12 -1
  47. package/dist/bridge/git-publish.js +3 -2
  48. package/dist/bridge/herdr.d.ts +4 -0
  49. package/dist/bridge/herdr.js +44 -9
  50. package/dist/bridge/install.d.ts +1 -1
  51. package/dist/bridge/install.js +12 -4
  52. package/dist/bridge/launch-brief.d.ts +11 -0
  53. package/dist/bridge/launch-brief.js +22 -0
  54. package/dist/bridge/launch-worktree.d.ts +2 -0
  55. package/dist/bridge/launch-worktree.js +5 -1
  56. package/dist/bridge/pane-status.js +1 -1
  57. package/dist/bridge/protocol.d.ts +7 -0
  58. package/dist/bridge/schedule-watch.js +13 -2
  59. package/dist/bridge/server-launch.d.ts +2 -0
  60. package/dist/bridge/server-launch.js +251 -145
  61. package/dist/bridge/server-routes.d.ts +3 -0
  62. package/dist/bridge/server-routes.js +33 -17
  63. package/dist/bridge/server-stream.d.ts +4 -0
  64. package/dist/bridge/server-stream.js +24 -5
  65. package/dist/bridge/server.js +35 -4
  66. package/dist/bridge/session-move.d.ts +10 -4
  67. package/dist/bridge/session-move.js +65 -34
  68. package/dist/bridge/simulator-stream.d.ts +2 -0
  69. package/dist/bridge/simulator-stream.js +2 -0
  70. package/dist/bridge/status-line-fast.d.ts +9 -0
  71. package/dist/bridge/status-line-fast.js +56 -0
  72. package/dist/bridge/tab-activity.d.ts +2 -0
  73. package/dist/bridge/tab-activity.js +15 -2
  74. package/dist/bridge/task-routes.d.ts +20 -16
  75. package/dist/bridge/task-routes.js +1 -1
  76. package/dist/bridge/terminal-herdr.d.ts +5 -1
  77. package/dist/bridge/terminal-herdr.js +67 -2
  78. package/dist/bridge/terminal-tmux.d.ts +2 -0
  79. package/dist/bridge/terminal-tmux.js +29 -7
  80. package/dist/bridge/terminal.d.ts +5 -1
  81. package/dist/bridge/transcript-claude.js +192 -112
  82. package/dist/bridge/transcript-preview.d.ts +2 -1
  83. package/dist/bridge/transcript-preview.js +85 -3
  84. package/dist/bridge/transcripts.js +17 -11
  85. package/dist/bridge/turn-records.js +16 -4
  86. package/dist/bridge/usage.d.ts +7 -1
  87. package/dist/bridge/usage.js +47 -31
  88. package/dist/bridge/worker-close.d.ts +15 -0
  89. package/dist/bridge/worker-close.js +304 -3
  90. package/dist/bridge/worker-identity.d.ts +51 -0
  91. package/dist/bridge/worker-identity.js +289 -0
  92. package/dist/bridge/worker-reports.js +15 -3
  93. package/dist/bridge-hook.mjs +39990 -36152
  94. package/dist/capabilities/mcp.js +1 -1
  95. package/dist/cli/browser-hint.d.ts +2 -0
  96. package/dist/cli/browser-hint.js +21 -0
  97. package/dist/cli/config-dreaming.d.ts +7 -0
  98. package/dist/cli/config-dreaming.js +72 -0
  99. package/dist/cli/config.js +6 -0
  100. package/dist/cli/dream.d.ts +59 -0
  101. package/dist/cli/dream.js +315 -0
  102. package/dist/cli/hooks-context.d.ts +2 -2
  103. package/dist/cli/hooks-context.js +3 -3
  104. package/dist/cli/hooks.js +20 -11
  105. package/dist/cli/namespaces-tasks.js +14 -0
  106. package/dist/cli-registry.js +28 -3
  107. package/dist/config/dreaming.d.ts +82 -0
  108. package/dist/config/dreaming.js +195 -0
  109. package/dist/config/resolve.js +11 -0
  110. package/dist/config/schema.d.ts +4 -4
  111. package/dist/config/schema.js +157 -1
  112. package/dist/content/citation-freshness.js +6 -0
  113. package/dist/content/learning.d.ts +1 -0
  114. package/dist/content/learning.js +2 -0
  115. package/dist/data/access.d.ts +1 -1
  116. package/dist/data/access.js +3 -1
  117. package/dist/data/task-contract.d.ts +5 -4
  118. package/dist/data/tasks.d.ts +5 -0
  119. package/dist/data/tasks.js +28 -2
  120. package/dist/dream/apply.d.ts +69 -0
  121. package/dist/dream/apply.js +372 -0
  122. package/dist/dream/budget.d.ts +78 -0
  123. package/dist/dream/budget.js +180 -0
  124. package/dist/dream/collect.d.ts +86 -0
  125. package/dist/dream/collect.js +449 -0
  126. package/dist/dream/eval/dream-adapter.d.ts +16 -0
  127. package/dist/dream/eval/dream-adapter.js +21 -0
  128. package/dist/dream/eval/fixture.d.ts +53 -0
  129. package/dist/dream/eval/fixture.js +172 -0
  130. package/dist/dream/eval/index.d.ts +40 -0
  131. package/dist/dream/eval/index.js +78 -0
  132. package/dist/dream/eval/score.d.ts +34 -0
  133. package/dist/dream/eval/score.js +99 -0
  134. package/dist/dream/eval/scripted-model.d.ts +19 -0
  135. package/dist/dream/eval/scripted-model.js +70 -0
  136. package/dist/dream/pages.d.ts +68 -0
  137. package/dist/dream/pages.js +220 -0
  138. package/dist/dream/privacy.d.ts +3 -0
  139. package/dist/dream/privacy.js +18 -0
  140. package/dist/dream/prompt.d.ts +13 -0
  141. package/dist/dream/prompt.js +84 -0
  142. package/dist/dream/run.d.ts +98 -0
  143. package/dist/dream/run.js +317 -0
  144. package/dist/dream/types.d.ts +74 -0
  145. package/dist/dream/types.js +4 -0
  146. package/dist/finding/lifecycle.d.ts +2 -2
  147. package/dist/finding/lifecycle.js +5 -2
  148. package/dist/finding/versions.d.ts +4 -0
  149. package/dist/finding/versions.js +28 -0
  150. package/dist/index.js +1 -0
  151. package/dist/modules/registry.js +10 -8
  152. package/dist/project-config.d.ts +3 -0
  153. package/dist/task/merge-links.d.ts +38 -0
  154. package/dist/task/merge-links.js +45 -0
  155. package/dist/task/reconcile.d.ts +39 -0
  156. package/dist/task/reconcile.js +201 -0
  157. package/dist/task/report-links.d.ts +10 -0
  158. package/dist/task/report-links.js +47 -0
  159. package/dist/tools/config.js +46 -4
  160. package/dist/tools/dispatch.js +2 -1
  161. package/dist/tools/dream.d.ts +3 -0
  162. package/dist/tools/dream.js +123 -0
  163. package/dist/tools/tasks.js +4 -1
  164. package/package.json +1 -1
@@ -1,3 +1,4 @@
1
+ import { browserEnv } from "./browser-env.js";
1
2
  // tmux as the Hook's terminal provider, for computers without Herdr.
2
3
  //
3
4
  // Two tmux servers are Hook servers: the owner's own (the default socket,
@@ -190,6 +191,20 @@ function socketOf(server) {
190
191
  throw new BridgeError(400, "This is not a tmux server.");
191
192
  return socket;
192
193
  }
194
+ const shellQuote = (value) => `'${value.replace(/'/g, `'\\''`)}'`;
195
+ /** The exact keyed-launch command: shell init, then `env -i` with only the explicit environment. */
196
+ export function explicitAgentCommand(kind, args, env) {
197
+ const expanded = new Set(["HOME", "USER", "LOGNAME", "PATH", "SHELL", "TERM", "LANG", "LC_ALL", "TMPDIR"]);
198
+ const assignments = Object.entries(env).map(([key, value]) => expanded.has(key) ? `${key}="$${key}"` : `${key}=${shellQuote(value)}`);
199
+ const harness = [kind, ...args];
200
+ if (env.PHREN_WORKER_ID_FILE) {
201
+ // Record the exec'd process identity before handing the same PID to the
202
+ // harness. The command line carries paths and arguments only, never a secret.
203
+ const script = `umask 077; printf "%s %s\\n" "$$" "$(ps -o lstart= -p $$ | tr -s " ")" > "$PHREN_WORKER_ID_FILE.tmp" && mv "$PHREN_WORKER_ID_FILE.tmp" "$PHREN_WORKER_ID_FILE" && exec "$@"`;
204
+ return `exec env -i ${assignments.join(" ")} /bin/sh -c ${shellQuote(script)} phren-worker ${harness.map(shellQuote).join(" ")}`.replace(/\s+$/, "");
205
+ }
206
+ return `exec env -i ${assignments.join(" ")} ${harness.map(shellQuote).join(" ")}`.replace(/\s+$/, "");
207
+ }
193
208
  const tmux = (server, args, options) => deps.run(socketOf(server), args, options);
194
209
  // tmux ids carry sigils the Hook's ids do not allow: session $3, window @5,
195
210
  // pane %12 become s3, w5 and p12, and back.
@@ -309,7 +324,7 @@ export async function tmuxSnapshot(server) {
309
324
  const title = row.pane_title && row.pane_title !== host && row.pane_title !== short ? plainTitle(row.pane_title) : undefined;
310
325
  panes.push({ pane_id: pane, tab_id: tab, workspace_id: workspace, terminal_id: terminal, cwd: row.pane_current_path || undefined,
311
326
  foreground_cwd: row.pane_current_path || undefined, title, ...(row["@phren_label"] ? { label: row["@phren_label"] } : {}),
312
- ...(agent ? { agent, agent_status: status?.status ?? (hooked ? "unknown" : "idle"), ...(status?.seq ? { state_change_seq: status.seq } : {}) } : {}),
327
+ ...(agent ? { agent, agent_pid: running.find(p => agentFromCommand(p.args) === agent)?.pid, agent_status: status?.status ?? (hooked ? "unknown" : "idle"), ...(status?.seq ? { state_change_seq: status.seq } : {}) } : {}),
313
328
  ...(agent && name ? { agent_name: name } : {}) });
314
329
  if (agent && name)
315
330
  agents.push({ name, pane_id: pane });
@@ -458,7 +473,7 @@ export const tmuxTerminal = {
458
473
  const taken = new Set((await tmux(server, ["list-sessions", "-F", "#{session_name}"]).catch(() => "")).split("\n").filter(Boolean));
459
474
  return created(await tmux(server, ["new-session", "-d", ...printed, "-s", sessionName(label, taken), "-x", "200", "-y", "50", ...directory, ...name]));
460
475
  },
461
- async startAgent(server, pane, { name, kind, args, timeoutMs, env }) {
476
+ async startAgent(server, pane, { name, kind, args, timeoutMs, env, envExact }) {
462
477
  if (!["claude", "codex", "copilot", "opencode", "phren"].includes(kind))
463
478
  throw new BridgeError(400, "This agent cannot be started in tmux.");
464
479
  await requireDirectExec();
@@ -471,10 +486,17 @@ export const tmuxTerminal = {
471
486
  // the pane falls back to that shell when it exits. The harness and its
472
487
  // arguments are the script's positional parameters, never script text.
473
488
  const shell = loginShell();
474
- // Variables for the agent alone (a dispatch id) ride on the respawn.
475
- const variables = Object.entries(env ?? {}).flatMap(([key, value]) => ["-e", `${key}=${value}`]);
476
- await tmux(server, ["respawn-pane", "-k", "-t", target, ...(row.pane_current_path ? ["-c", row.pane_current_path] : []), ...variables,
477
- "--", shell, "-l", "-c", 'shell="$1"; shift; "$@"; exec "$shell" -l', "phren", shell, kind, ...args]);
489
+ if (envExact) {
490
+ const command = explicitAgentCommand(kind, args, env ?? {});
491
+ await tmux(server, ["respawn-pane", "-k", "-t", target, ...(row.pane_current_path ? ["-c", row.pane_current_path] : []),
492
+ "--", shell, "-l", "-c", command]);
493
+ }
494
+ else {
495
+ // Variables for the agent alone (a dispatch id) ride on the respawn.
496
+ const variables = Object.entries(env ?? {}).flatMap(([key, value]) => ["-e", `${key}=${value}`]);
497
+ await tmux(server, ["respawn-pane", "-k", "-t", target, ...(row.pane_current_path ? ["-c", row.pane_current_path] : []), ...variables,
498
+ "--", shell, "-l", "-c", 'shell="$1"; shift; "$@"; exec "$shell" -l', "phren", shell, kind, ...args]);
499
+ }
478
500
  // Started once the harness is the pane's foreground program.
479
501
  const deadline = Date.now() + Math.min(timeoutMs, 30_000);
480
502
  for (;;) {
@@ -494,7 +516,7 @@ export const tmuxTerminal = {
494
516
  paneEnv(server, { pane }) {
495
517
  const socket = socketOf(server), folder = tmuxSocketFolders()[0];
496
518
  const file = socketPaths.get(socket) ?? (folder ? path.join(folder, socket) : undefined);
497
- return file ? { TMUX: `${file},0,0`, TMUX_PANE: toTmuxId(pane, "p") } : undefined;
519
+ return file ? { ...browserEnv(pane), TMUX: `${file},0,0`, TMUX_PANE: toTmuxId(pane, "p") } : undefined;
498
520
  },
499
521
  // A pane user option, not `select-pane -T`: agents overwrite the pane title.
500
522
  async renamePane(server, pane, label) {
@@ -74,6 +74,10 @@ export interface AgentStart {
74
74
  args: string[];
75
75
  timeoutMs: number;
76
76
  env?: Record<string, string>;
77
+ /** The env is the complete environment: run the harness through `env -i`, never an overlay. */
78
+ envExact?: boolean;
79
+ /** This launch created the pane, so a keyed Herdr launch may type into its fresh shell. */
80
+ freshPane?: boolean;
77
81
  }
78
82
  /**
79
83
  * Key names are the Hook's vocabulary: "enter", "esc", "up", "down", "tab",
@@ -92,7 +96,7 @@ export interface TerminalProvider {
92
96
  * (`tab_id`, `workspace_id`, `label`, `agent_status`) and `panes`
93
97
  * (`pane_id`, `tab_id`, `workspace_id`, `terminal_id`, `cwd`,
94
98
  * `foreground_cwd`, `title`, `label`, `agent`, `agent_status`,
95
- * `agent_name`, `state_change_seq`), plus `focused_workspace_id` /
99
+ * `agent_name`, `state_change_seq`, optional already-resolved `agent_pid`), plus `focused_workspace_id` /
96
100
  * `focused_tab_id` / `focused_pane_id`. `terminal_id` names the terminal
97
101
  * instance, so a pane reused by a new shell is a different terminal.
98
102
  */
@@ -55,6 +55,23 @@ async function claudeChildModel(file) {
55
55
  * too: Git routes must fail explicitly when a checkout disappears, never
56
56
  * substitute the parent repository. */
57
57
  export async function claudeChildCheckout(file) {
58
+ // A child's first rows never change and its meta file rarely does; the tree asks for every child each time.
59
+ const [child, metaInfo] = await Promise.all([stat(file), stat(file.slice(0, -".jsonl".length) + ".meta.json").catch(() => undefined)]);
60
+ const stamp = `${child.dev}:${child.ino}:${metaInfo ? `${metaInfo.ino}:${metaInfo.size}:${metaInfo.mtimeMs}` : "-"}`;
61
+ const cached = claudeCheckoutCache.get(file);
62
+ if (cached?.stamp === stamp)
63
+ return cached.checkout;
64
+ const checkout = await readClaudeChildCheckout(file);
65
+ if (checkout.cwd) {
66
+ claudeCheckoutCache.delete(file);
67
+ claudeCheckoutCache.set(file, { stamp, checkout });
68
+ while (claudeCheckoutCache.size > 1024)
69
+ claudeCheckoutCache.delete(claudeCheckoutCache.keys().next().value);
70
+ }
71
+ return checkout;
72
+ }
73
+ const claudeCheckoutCache = new Map();
74
+ async function readClaudeChildCheckout(file) {
58
75
  const meta = await readFile(file.slice(0, -".jsonl".length) + ".meta.json", "utf8").then(v => object(JSON.parse(v))).catch(() => ({}));
59
76
  let cwd = typeof meta.worktreePath === "string" && path.isAbsolute(meta.worktreePath) ? meta.worktreePath : undefined;
60
77
  let branch = typeof meta.worktreeBranch === "string" && meta.worktreeBranch ? meta.worktreeBranch.slice(0, 200) : undefined;
@@ -108,7 +125,8 @@ export async function claudeChildAgents(file, session) {
108
125
  const rows = cached?.signature.startsWith(`${parent}:`) && cached.rows ? cached.rows : await claudeParentRows(file);
109
126
  return claudeChildRelations(file, session, signature, rows, stop);
110
127
  }
111
- async function claudeParentRows(file) {
128
+ const claudeParentParses = new Map();
129
+ function newParentParse(identity) {
112
130
  const launches = new Map();
113
131
  const stops = new Map();
114
132
  // A background skill (`/code-review` run as `@code-review`) is announced in
@@ -125,122 +143,170 @@ async function claudeParentRows(file) {
125
143
  // Agent calls by tool_use id: the parent waits on a foreground one until its tool_result; a background one
126
144
  // waits here for its launch result, which names its agent (or, when it names none, stays here).
127
145
  const foreground = new Map(), background = new Map(), unidentified = new Map();
128
- const lines = createInterface({ input: createReadStream(file, { encoding: "utf8" }), crlfDelay: Infinity });
129
- for await (const line of lines) {
130
- try {
131
- const raw = object(JSON.parse(line)), result = object(raw.toolUseResult);
132
- const blocks = objects(object(raw.message).content);
133
- const status = String(result.status ?? "");
134
- // The agent id under the key Claude Code uses, or the one an older or newer version does.
135
- const agentId = String([result.agentId, result.agent_id, result.taskType === "local_workflow" ? undefined : result.taskId, result.task_id]
136
- .find(value => typeof value === "string" && /^[A-Za-z0-9._-]{1,128}$/.test(value)) ?? "");
137
- // A launch that runs on: async by its own word, or by any status that is not an end.
138
- const launched = result.taskType !== "local_workflow" && !/^(completed|failed|error|killed|cancell?ed|stopped|done)$/.test(status)
139
- && (result.isAsync === true || /^(async_)?(launched|running|started|queued|pending|spawned)$/.test(status));
140
- const resultCall = String(blocks.find(b => b.type === "tool_result")?.tool_use_id ?? "");
141
- if (launched && agentId && resultCall) {
142
- launches.set(agentId, { path: String(result.description || result.name || "Agent").slice(0, 200), callId: resultCall, state: "running" });
143
- }
144
- else if (launched && resultCall && !agentId && background.has(resultCall)) {
145
- const call = background.get(resultCall);
146
- // Timed from the call itself: its agent can start before the launch result is stamped.
147
- unidentified.set(resultCall, { path: String(result.description || call?.path || "Agent").slice(0, 200), callId: resultCall, prompt: call?.prompt ?? "",
148
- ...(call?.at ? { at: call.at } : typeof raw.timestamp === "string" ? { at: raw.timestamp } : {}) });
149
- }
150
- // SendMessage to a finished agent resumes it until its next final notification.
151
- const resumed = typeof result.resumedAgentId === "string" ? launches.get(result.resumedAgentId) : undefined;
152
- if (resumed && typeof result.message === "string" && /^Resuming agent\b/i.test(result.message)) {
153
- resumed.state = "running";
154
- if (typeof raw.timestamp === "string")
155
- resumed.resumedAt = raw.timestamp;
156
- }
157
- if (result.taskType === "local_workflow" && status === "async_launched" && typeof result.taskId === "string"
158
- && typeof result.runId === "string" && /^wf_[A-Za-z0-9-]{1,64}$/.test(result.runId)) {
159
- const callId = String(blocks.find(b => b.type === "tool_result")?.tool_use_id ?? "");
160
- workflows.set(result.taskId, { runId: result.runId, name: String(result.workflowName || "Workflow").slice(0, 200), callId, state: "running" });
146
+ return { identity, offset: 0, stops, background, rows: { launches, skills, workflows, teammates, foreground, unidentified } };
147
+ }
148
+ async function claudeParentRows(file) {
149
+ // Reads of one file take turns, so no row is applied twice.
150
+ while (claudeParentParses.get(file)?.reading)
151
+ await claudeParentParses.get(file).reading;
152
+ const metadata = await stat(file), identity = `${metadata.dev}:${metadata.ino}`;
153
+ let parse = claudeParentParses.get(file);
154
+ if (parse?.reading)
155
+ return claudeParentRows(file);
156
+ // Replaced or rewritten (shorter than what was read): read from the start.
157
+ if (!parse || parse.identity !== identity || metadata.size < parse.offset)
158
+ parse = newParentParse(identity);
159
+ claudeParentParses.delete(file);
160
+ claudeParentParses.set(file, parse);
161
+ while (claudeParentParses.size > 64)
162
+ claudeParentParses.delete(claudeParentParses.keys().next().value);
163
+ if (metadata.size > parse.offset) {
164
+ const reading = readParentRows(file, parse, metadata.size);
165
+ parse.reading = reading.catch(() => undefined).finally(() => { parse.reading = undefined; });
166
+ await reading;
167
+ }
168
+ return copyRows(parse.rows);
169
+ }
170
+ /** Applies every whole row in [offset, size). A last row with no newline yet counts once it parses; a
171
+ * part-written one is left for the next read. */
172
+ async function readParentRows(file, parse, size) {
173
+ let carry = Buffer.alloc(0);
174
+ for await (const chunk of createReadStream(file, { start: parse.offset, end: size - 1 })) {
175
+ let data = carry.length ? Buffer.concat([carry, chunk]) : chunk, from = 0;
176
+ for (let at = data.indexOf(10); at !== -1; at = data.indexOf(10, from)) {
177
+ const end = at > from && data[at - 1] === 13 ? at - 1 : at;
178
+ applyParentRow(parse, data.toString("utf8", from, end));
179
+ parse.offset += at + 1 - from;
180
+ from = at + 1;
181
+ }
182
+ carry = data.subarray(from);
183
+ }
184
+ if (!carry.length)
185
+ return;
186
+ const line = carry.toString("utf8");
187
+ try {
188
+ JSON.parse(line);
189
+ }
190
+ catch {
191
+ return;
192
+ }
193
+ applyParentRow(parse, line);
194
+ parse.offset += carry.length;
195
+ }
196
+ function applyParentRow(parse, line) {
197
+ const { stops, background } = parse, { launches, skills, workflows, teammates, foreground, unidentified } = parse.rows;
198
+ try {
199
+ const raw = object(JSON.parse(line)), result = object(raw.toolUseResult);
200
+ const blocks = objects(object(raw.message).content);
201
+ const status = String(result.status ?? "");
202
+ // The agent id under the key Claude Code uses, or the one an older or newer version does.
203
+ const agentId = String([result.agentId, result.agent_id, result.taskType === "local_workflow" ? undefined : result.taskId, result.task_id]
204
+ .find(value => typeof value === "string" && /^[A-Za-z0-9._-]{1,128}$/.test(value)) ?? "");
205
+ // A launch that runs on: async by its own word, or by any status that is not an end.
206
+ const launched = result.taskType !== "local_workflow" && !/^(completed|failed|error|killed|cancell?ed|stopped|done)$/.test(status)
207
+ && (result.isAsync === true || /^(async_)?(launched|running|started|queued|pending|spawned)$/.test(status));
208
+ const resultCall = String(blocks.find(b => b.type === "tool_result")?.tool_use_id ?? "");
209
+ if (launched && agentId && resultCall) {
210
+ launches.set(agentId, { path: String(result.description || result.name || "Agent").slice(0, 200), callId: resultCall, state: "running" });
211
+ }
212
+ else if (launched && resultCall && !agentId && background.has(resultCall)) {
213
+ const call = background.get(resultCall);
214
+ // Timed from the call itself: its agent can start before the launch result is stamped.
215
+ unidentified.set(resultCall, { path: String(result.description || call?.path || "Agent").slice(0, 200), callId: resultCall, prompt: call?.prompt ?? "",
216
+ ...(call?.at ? { at: call.at } : typeof raw.timestamp === "string" ? { at: raw.timestamp } : {}) });
217
+ }
218
+ // SendMessage to a finished agent resumes it until its next final notification.
219
+ const resumed = typeof result.resumedAgentId === "string" ? launches.get(result.resumedAgentId) : undefined;
220
+ if (resumed && typeof result.message === "string" && /^Resuming agent\b/i.test(result.message)) {
221
+ resumed.state = "running";
222
+ if (typeof raw.timestamp === "string")
223
+ resumed.resumedAt = raw.timestamp;
224
+ }
225
+ if (result.taskType === "local_workflow" && status === "async_launched" && typeof result.taskId === "string"
226
+ && typeof result.runId === "string" && /^wf_[A-Za-z0-9-]{1,64}$/.test(result.runId)) {
227
+ const callId = String(blocks.find(b => b.type === "tool_result")?.tool_use_id ?? "");
228
+ workflows.set(result.taskId, { runId: result.runId, name: String(result.workflowName || "Workflow").slice(0, 200), callId, state: "running" });
229
+ }
230
+ if (raw.type === "system" && typeof raw.content === "string" && raw.content.includes("<forked-skill-launch>")) {
231
+ const launch = object(JSON.parse(/<forked-skill-launch>([\s\S]*?)<\/forked-skill-launch>/.exec(raw.content)?.[1] ?? "{}"));
232
+ const id = String(launch.agentId ?? "");
233
+ if (/^[A-Za-z0-9._-]{1,128}$/.test(id)) {
234
+ launches.set(id, { path: String(launch.description || (launch.skillName ? `/${launch.skillName}` : "Skill")).slice(0, 200), callId: `skill:${id}`, state: "running" });
235
+ skills.add(id);
161
236
  }
162
- if (raw.type === "system" && typeof raw.content === "string" && raw.content.includes("<forked-skill-launch>")) {
163
- const launch = object(JSON.parse(/<forked-skill-launch>([\s\S]*?)<\/forked-skill-launch>/.exec(raw.content)?.[1] ?? "{}"));
164
- const id = String(launch.agentId ?? "");
165
- if (/^[A-Za-z0-9._-]{1,128}$/.test(id)) {
166
- launches.set(id, { path: String(launch.description || (launch.skillName ? `/${launch.skillName}` : "Skill")).slice(0, 200), callId: `skill:${id}`, state: "running" });
167
- skills.add(id);
237
+ }
238
+ if (raw.type === "assistant") {
239
+ for (const block of blocks) {
240
+ if (block.type !== "tool_use")
241
+ continue;
242
+ if (block.name === "TaskStop" && typeof block.id === "string" && typeof object(block.input).task_id === "string") {
243
+ stops.set(block.id, String(object(block.input).task_id));
168
244
  }
169
- }
170
- if (raw.type === "assistant") {
171
- for (const block of blocks) {
172
- if (block.type !== "tool_use")
173
- continue;
174
- if (block.name === "TaskStop" && typeof block.id === "string" && typeof object(block.input).task_id === "string") {
175
- stops.set(block.id, String(object(block.input).task_id));
176
- }
177
- if (block.name !== "Agent" && block.name !== "Task")
178
- continue;
179
- const input = object(block.input), name = String(input.name ?? "");
180
- if (typeof block.id !== "string")
181
- continue;
182
- if (block.name === "Agent" && /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(name)) {
183
- teammates.set(name, { path: String(input.description || name).slice(0, 200), callId: block.id.slice(0, 200), state: "running" });
184
- continue;
185
- }
186
- const call = { path: String(input.description || input.subagent_type || "Agent").slice(0, 200), callId: block.id.slice(0, 200),
187
- prompt: typeof input.prompt === "string" ? input.prompt : "", ...(typeof raw.timestamp === "string" ? { at: raw.timestamp } : {}) };
188
- (input.run_in_background === true ? background : foreground).set(call.callId, call);
245
+ if (block.name !== "Agent" && block.name !== "Task")
246
+ continue;
247
+ const input = object(block.input), name = String(input.name ?? "");
248
+ if (typeof block.id !== "string")
249
+ continue;
250
+ if (block.name === "Agent" && /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(name)) {
251
+ teammates.set(name, { path: String(input.description || name).slice(0, 200), callId: block.id.slice(0, 200), state: "running" });
252
+ continue;
189
253
  }
254
+ const call = { path: String(input.description || input.subagent_type || "Agent").slice(0, 200), callId: block.id.slice(0, 200),
255
+ prompt: typeof input.prompt === "string" ? input.prompt : "", ...(typeof raw.timestamp === "string" ? { at: raw.timestamp } : {}) };
256
+ (input.run_in_background === true ? background : foreground).set(call.callId, call);
190
257
  }
191
- // A call's result ends the parent's wait on it: the foreground agent finished, failed or was interrupted.
192
- if (raw.type === "user")
193
- for (const block of blocks) {
194
- if (block.type !== "tool_result" || typeof block.tool_use_id !== "string")
195
- continue;
196
- foreground.delete(block.tool_use_id);
197
- background.delete(block.tool_use_id);
198
- }
199
- // A stop request alone proves nothing. Its successful, matching result
200
- // ends the child even when no later task notification is recorded.
201
- if (raw.type === "user") {
202
- for (const block of blocks) {
203
- if (block.type !== "tool_result" || typeof block.tool_use_id !== "string")
204
- continue;
205
- const task = stops.get(block.tool_use_id);
206
- if (!task)
207
- continue;
208
- stops.delete(block.tool_use_id);
209
- const previous = launches.get(task) ?? workflows.get(task);
210
- if (previous && block.is_error !== true && result.task_id === task && typeof result.message === "string"
211
- && /^Successfully stopped task\b/i.test(result.message))
212
- previous.state = "completed";
213
- }
258
+ }
259
+ // A call's result ends the parent's wait on it: the foreground agent finished, failed or was interrupted.
260
+ if (raw.type === "user")
261
+ for (const block of blocks) {
262
+ if (block.type !== "tool_result" || typeof block.tool_use_id !== "string")
263
+ continue;
264
+ foreground.delete(block.tool_use_id);
265
+ background.delete(block.tool_use_id);
214
266
  }
215
- const content = typeof raw.content === "string" ? raw.content : typeof object(raw.message).content === "string" ? String(object(raw.message).content) : "";
216
- const attachment = object(raw.attachment);
217
- const notices = [raw.type === "queue-operation" || raw.type === "user" ? content : "",
218
- ...(raw.type === "user" ? blocks.filter(block => block.type === "text" && typeof block.text === "string").map(block => String(block.text)) : []),
219
- raw.type === "attachment" && attachment.type === "queued_command" && attachment.commandMode === "task-notification" && typeof attachment.prompt === "string" ? attachment.prompt : ""];
220
- for (const notice of notices) {
221
- for (const match of notice.matchAll(/<task-notification>([\s\S]*?)<\/task-notification>/g)) {
222
- const child = /<task-id>([^<>]{1,128})<\/task-id>/.exec(match[1])?.[1], taskStatus = /<status>([^<>]+)<\/status>/.exec(match[1])?.[1].trim();
223
- // Terminal notifications end only the child named in that envelope.
224
- const previous = child && (launches.get(child) ?? workflows.get(child));
225
- if (previous && ["completed", "failed", "cancelled", "canceled", "killed", "stopped"].includes(taskStatus ?? ""))
226
- previous.state = "completed";
227
- }
267
+ // A stop request alone proves nothing. Its successful, matching result
268
+ // ends the child even when no later task notification is recorded.
269
+ if (raw.type === "user") {
270
+ for (const block of blocks) {
271
+ if (block.type !== "tool_result" || typeof block.tool_use_id !== "string")
272
+ continue;
273
+ const task = stops.get(block.tool_use_id);
274
+ if (!task)
275
+ continue;
276
+ stops.delete(block.tool_use_id);
277
+ const previous = launches.get(task) ?? workflows.get(task);
278
+ if (previous && block.is_error !== true && result.task_id === task && typeof result.message === "string"
279
+ && /^Successfully stopped task\b/i.test(result.message))
280
+ previous.state = "completed";
228
281
  }
229
- // One row can carry several messages (a shutdown approval and the
230
- // system's termination notice together). Idle, an approved shutdown
231
- // and termination end a teammate; anything else it says wakes it.
232
- for (const match of content.includes("<teammate-message") ? content.matchAll(/<teammate-message teammate_id="([A-Za-z0-9][A-Za-z0-9_-]{0,63})"[^>]*>([\s\S]*?)<\/teammate-message>/g) : []) {
233
- const [, from, body] = match;
234
- const type = /"type":"([a-z_]+)"/.exec(body)?.[1];
235
- const ended = from === "system" && type === "teammate_terminated" ? /"message":"([A-Za-z0-9][A-Za-z0-9_-]{0,63}) has shut down/.exec(body)?.[1] : undefined;
236
- const teammate = teammates.get(ended ?? from);
237
- if (teammate)
238
- teammate.state = ended || type === "idle_notification" || type === "shutdown_approved" ? "completed" : "running";
282
+ }
283
+ const content = typeof raw.content === "string" ? raw.content : typeof object(raw.message).content === "string" ? String(object(raw.message).content) : "";
284
+ const attachment = object(raw.attachment);
285
+ const notices = [raw.type === "queue-operation" || raw.type === "user" ? content : "",
286
+ ...(raw.type === "user" ? blocks.filter(block => block.type === "text" && typeof block.text === "string").map(block => String(block.text)) : []),
287
+ raw.type === "attachment" && attachment.type === "queued_command" && attachment.commandMode === "task-notification" && typeof attachment.prompt === "string" ? attachment.prompt : ""];
288
+ for (const notice of notices) {
289
+ for (const match of notice.matchAll(/<task-notification>([\s\S]*?)<\/task-notification>/g)) {
290
+ const child = /<task-id>([^<>]{1,128})<\/task-id>/.exec(match[1])?.[1], taskStatus = /<status>([^<>]+)<\/status>/.exec(match[1])?.[1].trim();
291
+ // Terminal notifications end only the child named in that envelope.
292
+ const previous = child && (launches.get(child) ?? workflows.get(child));
293
+ if (previous && ["completed", "failed", "cancelled", "canceled", "killed", "stopped"].includes(taskStatus ?? ""))
294
+ previous.state = "completed";
239
295
  }
240
296
  }
241
- catch { /* Ignore unrelated/malformed rows. */ }
297
+ // One row can carry several messages (a shutdown approval and the
298
+ // system's termination notice together). Idle, an approved shutdown
299
+ // and termination end a teammate; anything else it says wakes it.
300
+ for (const match of content.includes("<teammate-message") ? content.matchAll(/<teammate-message teammate_id="([A-Za-z0-9][A-Za-z0-9_-]{0,63})"[^>]*>([\s\S]*?)<\/teammate-message>/g) : []) {
301
+ const [, from, body] = match;
302
+ const type = /"type":"([a-z_]+)"/.exec(body)?.[1];
303
+ const ended = from === "system" && type === "teammate_terminated" ? /"message":"([A-Za-z0-9][A-Za-z0-9_-]{0,63}) has shut down/.exec(body)?.[1] : undefined;
304
+ const teammate = teammates.get(ended ?? from);
305
+ if (teammate)
306
+ teammate.state = ended || type === "idle_notification" || type === "shutdown_approved" ? "completed" : "running";
307
+ }
242
308
  }
243
- return { launches, skills, workflows, teammates, foreground, unidentified };
309
+ catch { /* Ignore unrelated/malformed rows. */ }
244
310
  }
245
311
  async function claudeChildRelations(file, session, signature, rows, stop) {
246
312
  // Kept as the parent wrote them: what follows marks finished children.
@@ -510,24 +576,38 @@ async function claudeWorkflowAgents(root, session, workflow, quietEnds = true, n
510
576
  }
511
577
  return relations;
512
578
  }
579
+ /** Answers from a child's first row, which Claude Code never rewrites: kept per file while it is the same file. */
580
+ const claudeBelongsCache = new Map();
513
581
  async function claudeChildBelongsTo(file, parent, agentId) {
514
- let bytes = Buffer.alloc(0);
582
+ const info = await stat(file), identity = `${info.dev}:${info.ino}`, key = `${file}\0${parent}\0${agentId}`;
583
+ const cached = claudeBelongsCache.get(key);
584
+ if (cached?.identity === identity)
585
+ return cached.belongs;
586
+ let bytes = Buffer.alloc(0), whole = false;
515
587
  for await (const chunk of createReadStream(file, { start: 0, end: 1_048_575 })) {
516
588
  bytes = Buffer.concat([bytes, Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)]);
517
589
  const newline = bytes.indexOf(0x0a);
518
590
  if (newline >= 0) {
519
591
  bytes = bytes.subarray(0, newline);
592
+ whole = true;
520
593
  break;
521
594
  }
522
595
  }
596
+ let belongs = false;
523
597
  try {
524
598
  const raw = object(JSON.parse(bytes.toString("utf8")));
525
- return (raw.isSidechain === true && raw.sessionId === parent && raw.agentId === agentId)
599
+ belongs = (raw.isSidechain === true && raw.sessionId === parent && raw.agentId === agentId)
526
600
  || (raw.type === "fork-context-ref" && raw.parentSessionId === parent && raw.agentId === agentId);
527
601
  }
528
- catch {
529
- return false;
602
+ catch { /* Not a row yet, or not one of this parent's. */ }
603
+ // A first row still being written is read again next time.
604
+ if (whole) {
605
+ claudeBelongsCache.delete(key);
606
+ claudeBelongsCache.set(key, { identity, belongs });
607
+ while (claudeBelongsCache.size > 1024)
608
+ claudeBelongsCache.delete(claudeBelongsCache.keys().next().value);
530
609
  }
610
+ return belongs;
531
611
  }
532
612
  // `effort` rides on each assistant row (Claude Code 2.1): with `message.model`
533
613
  // it is what the phone's model chip shows as in effect. `permissionMode` on a
@@ -116,7 +116,8 @@ export declare class TranscriptPreviewStream {
116
116
  constructor(target: Target, pane?: () => Promise<string>, delta?: (file?: string) => Promise<TranscriptPreview | null>);
117
117
  observe(entries: Entry[], reset?: boolean): void;
118
118
  /** Whether pane text is a reply block that already landed: its words agree with the block's as far as
119
- * both go (drawsLanded), so a block still drawing the same opening as a landed one waits until the two part. */
119
+ * both go (drawsLanded), or a long paragraph is still on screen after the block's opening scrolled away.
120
+ * A block still drawing the same opening as a landed one waits until the two part. */
120
121
  private hasLanded;
121
122
  /** Seed a reconnect from a classified owner row in the verified transcript. */
122
123
  seedTurn(turnStartedAt: string, prompt: string): void;
@@ -17,7 +17,9 @@ const MAX_PREVIEW_BYTES = MAX_TEXT * 6 + 1_024;
17
17
  * unless `inTurn` (the turn already landed an entry, so the screen is its own
18
18
  * output and the prompt scrolled off above it). */
19
19
  export function claudePanePreview(rendered, prompt, previous = "", inTurn = false) {
20
- const screen = rendered.split("\n");
20
+ const screen = claudeReplyRegion(rendered.split("\n"));
21
+ if (!screen)
22
+ return "";
21
23
  const raw = screen.map(stripTerminal);
22
24
  // What the phone shows: the line with Claude's bold as Markdown. Detection
23
25
  // below reads the plain line.
@@ -323,6 +325,84 @@ export function readPreviewPane(target) {
323
325
  }
324
326
  // An SGR sequence (captured) or any other control sequence stripTerminal removes.
325
327
  const PANE_CONTROL = /\x1b\[([0-?]*)[ -/]*([@-~])|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\r/g;
328
+ /** Separate a styled sidebar before classifying rows or measuring wraps. Claude's diff
329
+ * panel has no enclosing box: bold paths and dim/italic instructions start at a fixed
330
+ * column, with padding between them and the reply. Two rows establish that column;
331
+ * crop every row there, including unstyled wraps and rows with no intervening space.
332
+ * An isolated region cannot establish a safe boundary, so that read stays silent. */
333
+ function claudeReplyRegion(screen) {
334
+ const columns = new Map();
335
+ const rows = screen.map(line => {
336
+ const styles = new Map();
337
+ const runs = [];
338
+ let plain = "", last = 0, inkStyle = "";
339
+ const take = (end) => {
340
+ const text = line.slice(last, end);
341
+ if (!text)
342
+ return;
343
+ runs.push({ raw: last, plain: plain.length, text });
344
+ if (text.trim()) {
345
+ const style = [...styles].sort(([a], [b]) => a - b).map(([key, value]) => `${key}:${value}`).join(";");
346
+ const before = plain + text.slice(0, text.length - text.trimStart().length);
347
+ if (before.length >= 20 && / {4,}$/.test(before) && style && style !== inkStyle) {
348
+ columns.set(before.length, (columns.get(before.length) ?? 0) + 1);
349
+ }
350
+ inkStyle = style;
351
+ }
352
+ plain += text;
353
+ };
354
+ for (const match of line.matchAll(PANE_CONTROL)) {
355
+ take(match.index);
356
+ last = match.index + match[0].length;
357
+ if (match[2] !== "m")
358
+ continue;
359
+ const params = (match[1] || "0").split(/[;:]/).map(value => Number(value || 0));
360
+ for (let i = 0; i < params.length; i++) {
361
+ const code = params[i];
362
+ if (code === 0)
363
+ styles.clear();
364
+ else if (code === 22) {
365
+ styles.delete(1);
366
+ styles.delete(2);
367
+ }
368
+ else if ([23, 24, 27, 29].includes(code))
369
+ styles.delete(code - 20);
370
+ else if (code === 39 || code === 49)
371
+ styles.delete(code - 1);
372
+ else if (code === 38 || code === 48 || code === 58) {
373
+ const size = params[i + 1] === 5 ? 2 : params[i + 1] === 2 ? 4 : 0;
374
+ styles.set(code, params.slice(i + 1, i + size + 1).join(":"));
375
+ i += size;
376
+ }
377
+ else if ((code >= 30 && code <= 37) || (code >= 90 && code <= 97))
378
+ styles.set(38, String(code));
379
+ else if ((code >= 40 && code <= 47) || (code >= 100 && code <= 107))
380
+ styles.set(48, String(code));
381
+ else
382
+ styles.set(code, "");
383
+ }
384
+ }
385
+ take(line.length);
386
+ return { line, runs };
387
+ });
388
+ // Without usable styles/padding, a known diff-panel notice is still evidence
389
+ // that this read cannot safely be interpreted as a single text region.
390
+ const panelNotice = screen.some(line => /New file not yet staged\.|Run `?git add :\/.*to see line counts\./.test(stripTerminal(line)));
391
+ if (!columns.size)
392
+ return panelNotice ? undefined : screen;
393
+ const repeated = [...columns].filter(([, count]) => count >= 2).map(([column]) => column);
394
+ if (!repeated.length)
395
+ return undefined;
396
+ const column = Math.min(...repeated);
397
+ // Offsets above count UTF-16 units. Wide glyphs and combining marks make that
398
+ // an unsafe terminal column; do not guess a crop in those reads.
399
+ if (rows.some(({ line }) => /[\t\p{Mark}\u1100-\u11ff\u2e80-\ua4cf\uac00-\ud7a3\ud800-\udfff\uf900-\ufaff\ufe00-\ufe6f\uff00-\uffef]/u.test(stripTerminal(line).slice(0, column))))
400
+ return undefined;
401
+ return rows.map(({ line, runs }) => {
402
+ const run = runs.find(run => run.plain + run.text.length > column);
403
+ return run ? line.slice(0, run.raw + Math.max(0, column - run.plain)) + "\x1b[0m" : line;
404
+ });
405
+ }
326
406
  /**
327
407
  * One pane line as Markdown bold. Claude draws a reply's **bold** with SGR 1
328
408
  * and drops the asterisks, so a plain read loses it and the phone's preview
@@ -654,12 +734,14 @@ export class TranscriptPreviewStream {
654
734
  }
655
735
  }
656
736
  /** Whether pane text is a reply block that already landed: its words agree with the block's as far as
657
- * both go (drawsLanded), so a block still drawing the same opening as a landed one waits until the two part. */
737
+ * both go (drawsLanded), or a long paragraph is still on screen after the block's opening scrolled away.
738
+ * A block still drawing the same opening as a landed one waits until the two part. */
658
739
  hasLanded(text) {
659
740
  const words = previewWords(text);
660
741
  return !words || [...this.landedTexts].some(landed =>
661
742
  // A short block ("Let me check.") is not a longer one that starts with its words.
662
- !(landed.length < LANDED_MATCH_CHARS && words.length > landed.length) && drawsLanded(words, landed));
743
+ (words.length >= LANDED_MATCH_CHARS && landed.includes(words))
744
+ || !(landed.length < LANDED_MATCH_CHARS && words.length > landed.length) && drawsLanded(words, landed));
663
745
  }
664
746
  /** Seed a reconnect from a classified owner row in the verified transcript. */
665
747
  seedTurn(turnStartedAt, prompt) {