@phren/cli 0.3.10 → 0.3.12

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 (184) hide show
  1. package/dist/bridge/agent-hook-stores.d.ts +3 -0
  2. package/dist/bridge/agent-hook-stores.js +5 -0
  3. package/dist/bridge/agent-hooks.d.ts +159 -5
  4. package/dist/bridge/agent-hooks.js +663 -49
  5. package/dist/bridge/approval-summary.d.ts +16 -0
  6. package/dist/bridge/approval-summary.js +133 -0
  7. package/dist/bridge/authority-command.d.ts +20 -0
  8. package/dist/bridge/authority-command.js +120 -0
  9. package/dist/bridge/authority.d.ts +223 -0
  10. package/dist/bridge/authority.js +231 -0
  11. package/dist/bridge/claude-account-setup.d.ts +14 -0
  12. package/dist/bridge/claude-account-setup.js +69 -0
  13. package/dist/bridge/claude-accounts.d.ts +49 -0
  14. package/dist/bridge/claude-accounts.js +195 -0
  15. package/dist/bridge/code-routes.js +2 -2
  16. package/dist/bridge/codex-app-server.d.ts +144 -0
  17. package/dist/bridge/codex-app-server.js +319 -0
  18. package/dist/bridge/codex-auth-refresh.d.ts +33 -0
  19. package/dist/bridge/codex-auth-refresh.js +71 -0
  20. package/dist/bridge/codex-question-reply.d.ts +16 -0
  21. package/dist/bridge/codex-question-reply.js +57 -0
  22. package/dist/bridge/codex-review-mode.d.ts +10 -0
  23. package/dist/bridge/codex-review-mode.js +74 -0
  24. package/dist/bridge/codex-servers.d.ts +217 -0
  25. package/dist/bridge/codex-servers.js +636 -0
  26. package/dist/bridge/command.js +94 -4
  27. package/dist/bridge/computer-identity.d.ts +75 -0
  28. package/dist/bridge/computer-identity.js +166 -0
  29. package/dist/bridge/conductor-group.d.ts +91 -8
  30. package/dist/bridge/conductor-group.js +105 -9
  31. package/dist/bridge/conductor-role.d.ts +94 -0
  32. package/dist/bridge/conductor-role.js +176 -0
  33. package/dist/bridge/conductor-sets.d.ts +20 -0
  34. package/dist/bridge/conductor-sets.js +59 -0
  35. package/dist/bridge/dispatch-command.d.ts +3 -0
  36. package/dist/bridge/dispatch-command.js +75 -11
  37. package/dist/bridge/dispatch-returns.d.ts +123 -19
  38. package/dist/bridge/dispatch-returns.js +357 -50
  39. package/dist/bridge/dispatch.d.ts +103 -2
  40. package/dist/bridge/dispatch.js +272 -40
  41. package/dist/bridge/fanout-messages.js +2 -2
  42. package/dist/bridge/fanouts.d.ts +7 -1
  43. package/dist/bridge/fanouts.js +40 -5
  44. package/dist/bridge/folder-trust.d.ts +56 -0
  45. package/dist/bridge/folder-trust.js +195 -0
  46. package/dist/bridge/grants.d.ts +22 -1
  47. package/dist/bridge/grants.js +57 -9
  48. package/dist/bridge/hand-off.d.ts +21 -9
  49. package/dist/bridge/hand-off.js +58 -45
  50. package/dist/bridge/harness-status.d.ts +11 -0
  51. package/dist/bridge/harness-status.js +32 -0
  52. package/dist/bridge/harnesses.d.ts +39 -0
  53. package/dist/bridge/harnesses.js +65 -0
  54. package/dist/bridge/health.d.ts +2 -0
  55. package/dist/bridge/health.js +1 -1
  56. package/dist/bridge/herdr.d.ts +11 -2
  57. package/dist/bridge/herdr.js +98 -23
  58. package/dist/bridge/hook-fast.d.ts +4 -0
  59. package/dist/bridge/hook-fast.js +68 -0
  60. package/dist/bridge/install.d.ts +16 -1
  61. package/dist/bridge/install.js +88 -21
  62. package/dist/bridge/launch-brief.d.ts +96 -0
  63. package/dist/bridge/launch-brief.js +164 -0
  64. package/dist/bridge/model-switch.d.ts +3 -0
  65. package/dist/bridge/model-switch.js +17 -1
  66. package/dist/bridge/models.d.ts +8 -4
  67. package/dist/bridge/models.js +24 -8
  68. package/dist/bridge/mux-wire.d.ts +9 -0
  69. package/dist/bridge/mux-wire.js +19 -0
  70. package/dist/bridge/opencode-pane-server.d.ts +113 -0
  71. package/dist/bridge/opencode-pane-server.js +332 -0
  72. package/dist/bridge/opencode-panes.d.ts +111 -0
  73. package/dist/bridge/opencode-panes.js +295 -0
  74. package/dist/bridge/pane-accounts.d.ts +8 -0
  75. package/dist/bridge/pane-accounts.js +46 -0
  76. package/dist/bridge/prompt-startup.d.ts +5 -0
  77. package/dist/bridge/prompt-startup.js +24 -0
  78. package/dist/bridge/protocol.d.ts +5 -0
  79. package/dist/bridge/protocol.js +4 -0
  80. package/dist/bridge/push.d.ts +5 -4
  81. package/dist/bridge/push.js +6 -4
  82. package/dist/bridge/questions.d.ts +37 -2
  83. package/dist/bridge/questions.js +158 -15
  84. package/dist/bridge/resources.d.ts +125 -0
  85. package/dist/bridge/resources.js +314 -0
  86. package/dist/bridge/schedule-format.d.ts +2 -0
  87. package/dist/bridge/schedule-format.js +3 -0
  88. package/dist/bridge/schedule-launch.d.ts +2 -1
  89. package/dist/bridge/schedule-launch.js +23 -53
  90. package/dist/bridge/schedule-watch.d.ts +10 -1
  91. package/dist/bridge/schedule-watch.js +54 -2
  92. package/dist/bridge/server-launch.d.ts +22 -5
  93. package/dist/bridge/server-launch.js +225 -29
  94. package/dist/bridge/server-overview.d.ts +8 -2
  95. package/dist/bridge/server-overview.js +26 -5
  96. package/dist/bridge/server-pane-routes.d.ts +2 -0
  97. package/dist/bridge/server-pane-routes.js +145 -15
  98. package/dist/bridge/server-routes.d.ts +11 -1
  99. package/dist/bridge/server-routes.js +195 -36
  100. package/dist/bridge/server-stream.d.ts +2 -0
  101. package/dist/bridge/server-stream.js +22 -8
  102. package/dist/bridge/server.d.ts +6 -1
  103. package/dist/bridge/server.js +47 -12
  104. package/dist/bridge/session-activity.d.ts +81 -0
  105. package/dist/bridge/session-activity.js +117 -0
  106. package/dist/bridge/session-rename.d.ts +48 -0
  107. package/dist/bridge/session-rename.js +190 -0
  108. package/dist/bridge/session-servers.js +2 -2
  109. package/dist/bridge/settings-switch.d.ts +60 -0
  110. package/dist/bridge/settings-switch.js +287 -0
  111. package/dist/bridge/speech-voice.d.ts +55 -0
  112. package/dist/bridge/speech-voice.js +132 -0
  113. package/dist/bridge/speech.d.ts +70 -11
  114. package/dist/bridge/speech.js +169 -41
  115. package/dist/bridge/terminal-herdr.js +9 -3
  116. package/dist/bridge/terminal-tmux.d.ts +3 -3
  117. package/dist/bridge/terminal-tmux.js +24 -9
  118. package/dist/bridge/terminal.d.ts +27 -4
  119. package/dist/bridge/terminal.js +8 -1
  120. package/dist/bridge/transcript-claude.js +62 -12
  121. package/dist/bridge/transcript-codex.d.ts +0 -2
  122. package/dist/bridge/transcript-codex.js +29 -4
  123. package/dist/bridge/transcript-preview.d.ts +1 -0
  124. package/dist/bridge/transcript-preview.js +24 -4
  125. package/dist/bridge/transcripts.d.ts +15 -2
  126. package/dist/bridge/transcripts.js +47 -16
  127. package/dist/bridge/turn-records.d.ts +85 -0
  128. package/dist/bridge/turn-records.js +143 -0
  129. package/dist/bridge/uploads.d.ts +3 -0
  130. package/dist/bridge/uploads.js +14 -0
  131. package/dist/bridge/usage.d.ts +73 -28
  132. package/dist/bridge/usage.js +313 -340
  133. package/dist/bridge-hook.mjs +24624 -18450
  134. package/dist/cli/claude-unmanaged.d.ts +12 -0
  135. package/dist/cli/claude-unmanaged.js +105 -0
  136. package/dist/cli/schedules.js +2 -1
  137. package/dist/cli/session-start.js +10 -1
  138. package/dist/cli/session-stop.js +9 -1
  139. package/dist/cli-registry.d.ts +2 -0
  140. package/dist/cli-registry.js +37 -5
  141. package/dist/computers/command.d.ts +6 -0
  142. package/dist/computers/command.js +152 -0
  143. package/dist/computers/mcp.d.ts +1 -0
  144. package/dist/computers/mcp.js +97 -0
  145. package/dist/computers/read.d.ts +85 -0
  146. package/dist/computers/read.js +177 -0
  147. package/dist/data/task-receipts.d.ts +19 -0
  148. package/dist/data/task-receipts.js +68 -0
  149. package/dist/data/tasks.js +4 -1
  150. package/dist/entrypoint.js +10 -0
  151. package/dist/fanout/adapters/claude.js +15 -2
  152. package/dist/fanout/adapters/types.d.ts +6 -0
  153. package/dist/fanout/launcher.d.ts +5 -1
  154. package/dist/fanout/launcher.js +34 -3
  155. package/dist/fanout/picker.js +3 -2
  156. package/dist/fanout/usage.js +1 -1
  157. package/dist/generated/memory-ui-graph.browser.js +63 -63
  158. package/dist/graph-core/model.js +24 -3
  159. package/dist/graph-core/types.d.ts +4 -1
  160. package/dist/graph-core/types.js +1 -0
  161. package/dist/init/init-preset.js +7 -3
  162. package/dist/init/init-uninstall.js +2 -11
  163. package/dist/init/teardown.d.ts +3 -0
  164. package/dist/init/teardown.js +47 -0
  165. package/dist/link/context.js +21 -9
  166. package/dist/mcp/plugin-mode.js +1 -1
  167. package/dist/memory-ui-graph.runtime.js +63 -63
  168. package/dist/modules/code-package.d.ts +1 -0
  169. package/dist/modules/code-package.js +36 -7
  170. package/dist/modules/registry.js +14 -13
  171. package/dist/profile-store.d.ts +6 -0
  172. package/dist/profile-store.js +25 -1
  173. package/dist/shell/graph/glyphs.js +4 -0
  174. package/dist/shell/graph/graph-view.js +2 -0
  175. package/dist/status.js +7 -1
  176. package/dist/sync/task-claim.js +3 -2
  177. package/dist/task/lifecycle.js +25 -4
  178. package/dist/test-global-setup.js +5 -0
  179. package/dist/tools/dispatch.js +35 -2
  180. package/dist/tools/tasks.js +10 -1
  181. package/package.json +1 -1
  182. package/plugins/opencode/phren-transcript.js +87 -4
  183. package/starter/global/skills/conductor/SKILL.md +17 -2
  184. package/starter/global/skills/fanout/SKILL.md +3 -0
@@ -92,6 +92,7 @@ export async function claudeChildAgents(file, session) {
92
92
  return cached.relations;
93
93
  }
94
94
  const launches = new Map();
95
+ const stops = new Map();
95
96
  // Named teammates (the Agent tool with a `name`) run as their own session
96
97
  // and never post a task-notification: they announce themselves idle in a
97
98
  // teammate-message instead, and may be woken again later. Their file is
@@ -101,15 +102,21 @@ export async function claudeChildAgents(file, session) {
101
102
  for await (const line of lines) {
102
103
  try {
103
104
  const raw = object(JSON.parse(line)), result = object(raw.toolUseResult);
105
+ const blocks = objects(object(raw.message).content);
104
106
  const agentId = String(result.agentId ?? ""), status = String(result.status ?? "");
105
107
  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 ?? "");
108
+ const callId = String(blocks.find(b => b.type === "tool_result")?.tool_use_id ?? "");
107
109
  if (callId)
108
110
  launches.set(agentId, { path: String(result.description || result.name || "Agent").slice(0, 200), callId, state: "running" });
109
111
  }
110
112
  if (raw.type === "assistant") {
111
- for (const block of objects(object(raw.message).content)) {
112
- if (block.type !== "tool_use" || block.name !== "Agent")
113
+ for (const block of blocks) {
114
+ if (block.type !== "tool_use")
115
+ continue;
116
+ if (block.name === "TaskStop" && typeof block.id === "string" && typeof object(block.input).task_id === "string") {
117
+ stops.set(block.id, String(object(block.input).task_id));
118
+ }
119
+ if (block.name !== "Agent")
113
120
  continue;
114
121
  const input = object(block.input), name = String(input.name ?? "");
115
122
  if (!/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(name) || typeof block.id !== "string")
@@ -117,14 +124,35 @@ export async function claudeChildAgents(file, session) {
117
124
  teammates.set(name, { path: String(input.description || name).slice(0, 200), callId: block.id.slice(0, 200), state: "running" });
118
125
  }
119
126
  }
127
+ // A stop request alone proves nothing. Its successful, matching result
128
+ // ends the child even when no later task notification is recorded.
129
+ if (raw.type === "user") {
130
+ for (const block of blocks) {
131
+ if (block.type !== "tool_result" || typeof block.tool_use_id !== "string")
132
+ continue;
133
+ const task = stops.get(block.tool_use_id);
134
+ if (!task)
135
+ continue;
136
+ stops.delete(block.tool_use_id);
137
+ const previous = launches.get(task);
138
+ if (previous && block.is_error !== true && result.task_id === task && typeof result.message === "string"
139
+ && /^Successfully stopped task\b/i.test(result.message))
140
+ previous.state = "completed";
141
+ }
142
+ }
120
143
  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";
144
+ const attachment = object(raw.attachment);
145
+ const notices = [raw.type === "queue-operation" || raw.type === "user" ? content : "",
146
+ ...(raw.type === "user" ? blocks.filter(block => block.type === "text" && typeof block.text === "string").map(block => String(block.text)) : []),
147
+ raw.type === "attachment" && attachment.type === "queued_command" && attachment.commandMode === "task-notification" && typeof attachment.prompt === "string" ? attachment.prompt : ""];
148
+ for (const notice of notices) {
149
+ for (const match of notice.matchAll(/<task-notification>([\s\S]*?)<\/task-notification>/g)) {
150
+ const child = /<task-id>([^<>]{1,128})<\/task-id>/.exec(match[1])?.[1], taskStatus = /<status>([^<>]+)<\/status>/.exec(match[1])?.[1].trim();
151
+ // Terminal notifications end only the child named in that envelope.
152
+ const previous = child && launches.get(child);
153
+ if (previous && ["completed", "failed", "cancelled", "canceled", "killed", "stopped"].includes(taskStatus ?? ""))
154
+ previous.state = "completed";
155
+ }
128
156
  }
129
157
  if (content.includes("<teammate-message")) {
130
158
  const from = /<teammate-message teammate_id="([A-Za-z0-9][A-Za-z0-9_-]{0,63})"/.exec(content)?.[1];
@@ -199,7 +227,10 @@ async function claudeChildBelongsTo(file, parent, agentId) {
199
227
  return false;
200
228
  }
201
229
  }
202
- const CLAUDE_KEYS = new Set(["type", "uuid", "parentUuid", "timestamp", "message", "gitBranch", "cwd", "requestId", "isMeta", "isSidechain", "isCompactSummary", "phrenQueued", "phrenQueueKey", "phrenBackground", "phrenCompacted"]);
230
+ // `effort` rides on each assistant row (Claude Code 2.1): with `message.model`
231
+ // it is what the phone's model chip shows as in effect. `permissionMode` on a
232
+ // user row is the mode that turn ran in (the phone's permission chip).
233
+ const CLAUDE_KEYS = new Set(["type", "uuid", "parentUuid", "timestamp", "message", "gitBranch", "cwd", "requestId", "isMeta", "isSidechain", "isCompactSummary", "phrenQueued", "phrenQueueKey", "phrenBackground", "phrenCompacted", "effort", "permissionMode"]);
203
234
  export const harnessPreamble = (text) => /^<(?:environment_context>|user_instructions>|permission_profile|system-reminder>|turn_context>)/.test(text.trimStart());
204
235
  function taskNotification(content) {
205
236
  const envelope = /<task-notification>([\s\S]*?)<\/task-notification>/.exec(content)?.[1];
@@ -273,6 +304,11 @@ export function skillBody(raw) {
273
304
  return { type: "user", timestamp: raw.timestamp, ...(typeof raw.uuid === "string" ? { uuid: raw.uuid } : {}),
274
305
  message: { role: "user", content: [{ type: "tool_result", tool_use_id: raw.sourceToolUseID, content: text.slice(0, 32_768), phrenSkillBody: true }] } };
275
306
  }
307
+ /** Claude Code's label where a pasted picture path was, and the footer the
308
+ * phone puts above the paths of the files it attached. */
309
+ const QUEUED_IMAGE_LABEL = /\[Image #\d+\]/;
310
+ const QUEUED_IMAGE_LABELS = /\[Image #\d+\]/g;
311
+ const ATTACHED_FILES_FOOTER = /Attached files on this computer:\s*$/;
276
312
  /** A phren UserPromptSubmit injection, as `{ type: "phren_hook_context",
277
313
  * parentUuid, content }`, or undefined for any other row. */
278
314
  export function phrenHookContext(raw, includeSidechain = false) {
@@ -297,6 +333,11 @@ export function phrenHookContext(raw, includeSidechain = false) {
297
333
  * private reasoning redacted, queued phone messages, background task
298
334
  * notifications and compaction markers. */
299
335
  export function visibleClaudeEvent(raw, includeSidechain = false) {
336
+ // A follow-up the phone sent a Claude fan-out worker, written into its
337
+ // event log by the Hook before the resumed run.
338
+ if (raw.type === "phren/fanout-message" && typeof raw.text === "string") {
339
+ return { type: "user", timestamp: raw.timestamp, message: { role: "user", content: raw.text.slice(0, 65_536) } };
340
+ }
300
341
  // A queued phone message carries the same wrapper; unwrap before the
301
342
  // digest so enqueue and remove keep matching keys.
302
343
  if (raw.type === "queue-operation" && typeof raw.content === "string")
@@ -331,8 +372,13 @@ export function visibleClaudeEvent(raw, includeSidechain = false) {
331
372
  // tool envelope, private metadata, or reasoning is exported.
332
373
  if (raw.operation === "remove")
333
374
  return { type: "phren_queue_consumed", key, timestamp: raw.timestamp };
375
+ // A picture sent mid-turn queues as "[Image #7]Attached files on this
376
+ // computer:": the pixels never reach this row. Words-free, it matched no
377
+ // receipt, and the phone warned "Not confirmed in chat" about a picture
378
+ // the agent had taken. Name it the way a picture-only turn reads.
379
+ const pictureOnly = QUEUED_IMAGE_LABEL.test(text) && !text.replace(QUEUED_IMAGE_LABELS, "").replace(ATTACHED_FILES_FOOTER, "").trim();
334
380
  return { type: "user", phrenQueued: true, phrenQueueKey: key, timestamp: raw.timestamp,
335
- message: { role: "user", content: text } };
381
+ message: { role: "user", content: pictureOnly ? "[Image attachment]" : text } };
336
382
  }
337
383
  // Claude Code appends a boundary marker and then the summary it hands the
338
384
  // model as a user turn. The phone shows the marker and a bounded preview,
@@ -354,6 +400,10 @@ export function visibleClaudeEvent(raw, includeSidechain = false) {
354
400
  const skill = skillBody(raw);
355
401
  if (skill)
356
402
  return skill;
403
+ // The row Claude writes when the permission mode changes; nothing else of it.
404
+ if (raw.type === "permission-mode" && typeof raw.permissionMode === "string" && /^[A-Za-z]{1,30}$/.test(raw.permissionMode)) {
405
+ return { type: "permission-mode", permissionMode: raw.permissionMode, ...(typeof raw.timestamp === "string" ? { timestamp: raw.timestamp } : {}) };
406
+ }
357
407
  if (raw.isMeta || (raw.isSidechain && !includeSidechain) || !["user", "assistant", "system"].includes(String(raw.type)))
358
408
  return undefined;
359
409
  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;
@@ -3,6 +3,7 @@ import { stat } from "node:fs/promises";
3
3
  import { object, objects, sessionId } from "./protocol.js";
4
4
  import { visibleCodexExecEvent } from "./fanouts.js";
5
5
  import { harnessPreamble } from "./transcript-claude.js";
6
+ import { readableQuestionReply } from "./codex-question-reply.js";
6
7
  const childRelationCache = new Map();
7
8
  function addChildRelation(line, found) {
8
9
  if (!line.includes("SubAgentActivity"))
@@ -73,6 +74,15 @@ export async function childTranscriptBelongsTo(file, parent) {
73
74
  }
74
75
  /** Codex rows the phone may see: public messages, tool calls and their
75
76
  * outputs, the answering model, and turn/usage events. */
77
+ /** The approval policy (a granular one as its kind), reviewer, sandbox kind and
78
+ * collaboration mode of a turn_context, each only when short and plain. */
79
+ function turnSettings(p) {
80
+ const word = (value) => typeof value === "string" && /^[A-Za-z_-]{1,30}$/.test(value) ? value : undefined;
81
+ const policy = word(p.approval_policy) ?? (p.approval_policy && typeof p.approval_policy === "object" ? Object.keys(p.approval_policy).find(key => word(key)) : undefined);
82
+ const reviewer = word(p.approvals_reviewer), sandbox = word(object(p.sandbox_policy).type), mode = word(object(p.collaboration_mode).mode);
83
+ return { ...(policy ? { approval_policy: policy } : {}), ...(reviewer ? { approvals_reviewer: reviewer } : {}),
84
+ ...(sandbox ? { sandbox_policy: { type: sandbox } } : {}), ...(mode ? { collaboration_mode: { mode } } : {}) };
85
+ }
76
86
  export function visibleCodexEvent(raw) {
77
87
  if (raw.type === "phren_queue_consumed" && typeof raw.key === "string" && /^[a-f0-9]{64}$/.test(raw.key)) {
78
88
  return { type: raw.type, key: raw.key };
@@ -81,10 +91,12 @@ export function visibleCodexEvent(raw) {
81
91
  if (execEvent)
82
92
  return execEvent;
83
93
  const p = object(raw.payload);
84
- // The model answering this turn is the only field of turn_context the
85
- // phone shows; its policies and instructions stay on the computer.
94
+ // The model answering this turn, its effort and the permission and plan
95
+ // settings are the only fields of turn_context the phone shows; its
96
+ // instructions, paths and rules stay on the computer.
86
97
  if (raw.type === "turn_context")
87
- return typeof p.model === "string" ? { type: "turn_context", timestamp: raw.timestamp, payload: { model: p.model } } : undefined;
98
+ return typeof p.model === "string" ? { type: "turn_context", timestamp: raw.timestamp,
99
+ payload: { model: p.model, ...(typeof p.effort === "string" && p.effort.length <= 20 ? { effort: p.effort } : {}), ...turnSettings(p) } } : undefined;
88
100
  if (raw.type === "event_msg" && p.type === "error")
89
101
  return { type: raw.type, timestamp: raw.timestamp,
90
102
  payload: { type: "error", ...(typeof p.message === "string" ? { message: p.message } : {}) } };
@@ -99,7 +111,20 @@ export function visibleCodexEvent(raw) {
99
111
  return wrapper.images.length ? imageCall(raw, wrapper) : undefined;
100
112
  if (p.type === "message" && ["user", "assistant"].includes(String(p.role)) && p.channel !== "analysis") {
101
113
  const text = typeof p.content === "string" ? p.content : objects(p.content).map(b => typeof b.text === "string" ? b.text : "").join("\n");
102
- return p.role === "user" && harnessPreamble(text) ? undefined : raw;
114
+ if (p.role === "user" && harnessPreamble(text))
115
+ return undefined;
116
+ // An answer to an async question reads as the question and its answer,
117
+ // not as the envelope Codex's TUI (or the Hook) sent it in.
118
+ // Only the reply's own block changes: attached files and images that
119
+ // came with the answer stay as their own blocks.
120
+ if (p.role === "user" && Array.isArray(p.content) && readableQuestionReply(text) !== undefined) {
121
+ return { ...raw, payload: { ...p, content: objects(p.content).map(block => {
122
+ const readable = typeof block.text === "string" ? readableQuestionReply(block.text) : undefined;
123
+ return readable === undefined ? block : { ...block, text: readable };
124
+ }) } };
125
+ }
126
+ const answered = p.role === "user" && typeof p.content === "string" ? readableQuestionReply(p.content) : undefined;
127
+ return answered ? { ...raw, payload: { ...p, content: answered } } : raw;
103
128
  }
104
129
  if (["function_call", "custom_tool_call", "function_call_output", "custom_tool_call_output"].includes(String(p.type)))
105
130
  return raw;
@@ -92,6 +92,7 @@ export declare class TranscriptPreviewStream {
92
92
  private current;
93
93
  private observedLine;
94
94
  private wasWorking;
95
+ private readonly codexCompleted;
95
96
  private readonly rollout;
96
97
  constructor(target: Target, pane?: () => Promise<string>, delta?: (file?: string) => Promise<TranscriptPreview | null>);
97
98
  observe(entries: Entry[], reset?: boolean): void;
@@ -402,6 +402,7 @@ export class TranscriptPreviewStream {
402
402
  current = null;
403
403
  observedLine = -1;
404
404
  wasWorking = false;
405
+ codexCompleted = new Set();
405
406
  rollout = new CodexRolloutPreview();
406
407
  constructor(target, pane = () => readPreviewPane(target), delta = file => readDeltaPreview(target, file, this.rollout)) {
407
408
  this.target = target;
@@ -415,19 +416,33 @@ export class TranscriptPreviewStream {
415
416
  this.landed = false;
416
417
  this.ended = false;
417
418
  this.wasWorking = false;
419
+ this.codexCompleted.clear();
418
420
  }
419
421
  for (const { raw, line } of entries) {
420
422
  if (line <= this.observedLine)
421
423
  continue;
422
424
  this.observedLine = line;
423
425
  if (this.target.source === "codex") {
424
- // Codex brackets a turn with task_started and task_complete; its
425
- // delta source is only read between them.
426
+ // A completed commentary message can land before task_complete while
427
+ // Codex keeps working on a tool call.
426
428
  const payload = object(raw.payload);
427
- if (raw.type === "event_msg" && payload.type === "task_started")
429
+ if (raw.type === "event_msg" && payload.type === "task_started") {
428
430
  this.ended = false;
429
- else if (raw.type === "response_item" && payload.type === "message" && payload.role === "user")
431
+ this.codexCompleted.clear();
432
+ }
433
+ else if (raw.type === "response_item" && payload.type === "message" && payload.role === "user" && !raw.phrenQueued) {
430
434
  this.ended = false;
435
+ this.codexCompleted.clear();
436
+ }
437
+ else if (raw.type === "response_item" && payload.type === "message" && payload.role === "assistant") {
438
+ const text = (typeof payload.content === "string" ? payload.content
439
+ : objects(payload.content).map(block => typeof block.text === "string" ? block.text : "").join("\n")).trim();
440
+ if (text) {
441
+ this.codexCompleted.add(text);
442
+ if (this.codexCompleted.size > 32)
443
+ this.codexCompleted.delete(this.codexCompleted.values().next().value);
444
+ }
445
+ }
431
446
  else if (raw.type === "event_msg" && ["task_complete", "task_completed", "turn_aborted", "task_aborted"].includes(String(payload.type)))
432
447
  this.ended = true;
433
448
  continue;
@@ -487,6 +502,11 @@ export class TranscriptPreviewStream {
487
502
  // when the source is temporarily empty or unavailable.
488
503
  if (!this.ended)
489
504
  next = await this.delta(file);
505
+ if (this.target.source === "codex" && next) {
506
+ const text = next.text.trim();
507
+ if (text && [...this.codexCompleted].some(completed => completed.startsWith(text)))
508
+ next = null;
509
+ }
490
510
  }
491
511
  else if (this.target.source === "claude" && this.startedAt && !this.ended) {
492
512
  if (readAt - this.lastRead < PREVIEW_INTERVAL_MS)
@@ -1,3 +1,4 @@
1
+ import { type AccountRef } from "./claude-accounts.js";
1
2
  import { type Json, type Provider, type Target } from "./protocol.js";
2
3
  import { type ChangeLookup } from "./changes.js";
3
4
  export { isNarration, unwrapPastedContent } from "./transcript-claude.js";
@@ -14,9 +15,11 @@ export interface ChildAgentRelation {
14
15
  provider: Provider;
15
16
  path: string;
16
17
  callId: string;
17
- state: "running" | "completed" | "failed" | "unavailable";
18
+ state: "running" | "completed" | "failed" | "gone" | "unavailable";
18
19
  /** Why a fan-out worker did not finish: `blocked: <type> <pattern>`. */
19
20
  reason?: string;
21
+ /** Present only when a source supplies a validated worker launch time. */
22
+ startedAt?: string;
20
23
  finishedAt?: string;
21
24
  /** Fan-out manifests and Claude child transcripts can name a model. */
22
25
  model?: string;
@@ -60,7 +63,17 @@ export declare function childAgent(tree: ChildAgentRelation[], id: string): Loca
60
63
  * yaml and the data layer, and this bundle is budgeted for cold start.
61
64
  */
62
65
  export declare function phrenStoreRoot(env?: NodeJS.ProcessEnv): string;
63
- export declare function transcriptPath(source: Provider, session: string): Promise<string>;
66
+ /** The account a resolved Claude transcript belongs to, by the home holding it. */
67
+ export declare function transcriptAccount(file: string): AccountRef | undefined;
68
+ /** A pane's transcript: the pane's known Claude account settles a session id found in more than one home. */
69
+ export declare function targetTranscriptPath(target: {
70
+ server: string;
71
+ pane: string;
72
+ source: Provider;
73
+ session: string;
74
+ }): Promise<string>;
75
+ /** `account` (a Claude home id) settles a session id found in more than one home. */
76
+ export declare function transcriptPath(source: Provider, session: string, account?: string): Promise<string>;
64
77
  /** Keeps a materialized Codex thread current before a read; a no-op for
65
78
  * transcripts the agent writes itself. */
66
79
  export declare function refreshTranscript(file: string, source: Provider, session: string): Promise<void>;
@@ -1,7 +1,9 @@
1
1
  import { readdir, realpath, lstat } from "node:fs/promises";
2
2
  import { createHash } from "node:crypto";
3
3
  import { homedir } from "node:os";
4
- import { codexHome, claudeConfigDir } from "../home-paths.js";
4
+ import { codexHome } from "../home-paths.js";
5
+ import { claudeAccountRef, claudeHomeOfPath, claudeHomes } from "./claude-accounts.js";
6
+ import { paneAccount, paneAccountKey } from "./pane-accounts.js";
5
7
  import path from "node:path";
6
8
  import { withTranscriptIndex } from "./transcript-index.js";
7
9
  import { BridgeError, object, objects, sessionId } from "./protocol.js";
@@ -44,11 +46,12 @@ export async function childAgentTree(source, session, depth = 0, seen = new Set(
44
46
  /** Explicit wire projection prevents a provider's private transcript identity
45
47
  * from being returned if relation internals grow later. */
46
48
  export function publicChildAgents(tree) {
47
- return tree.map(({ id, provider, path: agentPath, callId, state, reason, finishedAt, model, worktreeName, branch, computer, remote, fanout, children }) =>
49
+ return tree.map(({ id, provider, path: agentPath, callId, state, reason, startedAt, finishedAt, model, worktreeName, branch, computer, remote, fanout, children }) =>
48
50
  // A blocked worker is finished; the phone's relation contract has no failed
49
51
  // state, so the reason carries what happened without breaking old clients.
50
- ({ id, provider, path: agentPath, callId, state: state === "failed" ? "completed" : state,
51
- ...(state === "failed" ? { failed: true } : {}), ...(finishedAt ? { finishedAt } : {}),
52
+ ({ id, provider, path: agentPath, callId, state: state === "failed" || state === "gone" ? "completed" : state,
53
+ ...(state === "failed" || state === "gone" ? { failed: true } : {}),
54
+ ...(startedAt ? { startedAt } : {}), ...(finishedAt ? { finishedAt } : {}),
52
55
  ...(reason !== undefined ? { reason } : {}), ...(model !== undefined ? { model } : {}),
53
56
  ...(worktreeName !== undefined ? { worktreeName } : {}), ...(branch !== undefined ? { branch } : {}),
54
57
  ...(computer !== undefined ? { computer: { id: computer.id, name: computer.name } } : {}),
@@ -185,27 +188,49 @@ async function findPatternMatches(root, pattern) {
185
188
  await walk(root, 0);
186
189
  return matches;
187
190
  }
188
- export async function transcriptPath(source, session) {
191
+ /** The account a resolved Claude transcript belongs to, by the home holding it. */
192
+ export function transcriptAccount(file) {
193
+ const home = claudeHomeOfPath(file);
194
+ return home ? claudeAccountRef(home) : undefined;
195
+ }
196
+ /** A pane's transcript: the pane's known Claude account settles a session id found in more than one home. */
197
+ export function targetTranscriptPath(target) {
198
+ const account = target.source === "claude" ? paneAccount(paneAccountKey(target.server, target.pane))?.id : undefined;
199
+ return transcriptPath(target.source, target.session, account);
200
+ }
201
+ /** `account` (a Claude home id) settles a session id found in more than one home. */
202
+ export async function transcriptPath(source, session, account) {
189
203
  if (!sessionId.safeParse(session).success)
190
204
  throw new BridgeError(400, "Invalid conversation identity.");
191
- const base = source === "codex" ? path.join(codexHome(), "sessions")
192
- : source === "claude" ? path.join(claudeConfigDir(), "projects")
193
- : source === "phren" || source === "opencode" ? path.join(phrenStoreRoot(), ".runtime", "sessions")
194
- : path.join(process.env.COPILOT_HOME || path.join(homedir(), ".copilot"), "session-state");
195
- const root = await realpath(base).catch(() => base);
205
+ const bases = source === "codex" ? [{ base: path.join(codexHome(), "sessions") }]
206
+ : source === "claude" ? claudeHomes().map(home => ({ id: home.id, base: path.join(home.dir, "projects") }))
207
+ : source === "phren" || source === "opencode" ? [{ base: path.join(phrenStoreRoot(), ".runtime", "sessions") }]
208
+ : [{ base: path.join(process.env.COPILOT_HOME || path.join(homedir(), ".copilot"), "session-state") }];
196
209
  const pattern = source === "codex" ? `*/*/*/rollout-*-${session}.jsonl` : source === "claude" ? `*/${session}.jsonl`
197
210
  : source === "phren" ? `session-${session}.events.jsonl` : source === "opencode" ? `opencode-${session}.events.jsonl` : `${session}/events.jsonl`;
198
- const matches = await findPatternMatches(root, pattern).catch(() => []);
199
- if (matches.length !== 1) {
211
+ const found = [];
212
+ for (const entry of bases) {
213
+ const root = await realpath(entry.base).catch(() => entry.base);
214
+ const matches = await findPatternMatches(root, pattern).catch(() => []);
215
+ for (const match of matches)
216
+ found.push({ id: entry.id, root, match });
217
+ }
218
+ let chosen = found;
219
+ if (source === "claude" && found.length > 1 && account) {
220
+ const preferred = found.filter(item => item.id === account);
221
+ if (preferred.length)
222
+ chosen = preferred;
223
+ }
224
+ if (chosen.length !== 1) {
200
225
  // Codex 0.155 keeps new threads only in its sqlite store; the Hook
201
226
  // materializes those into a rollout-shaped file of its own.
202
227
  const materialized = source === "codex" ? await materializeCodexThread(session) : undefined;
203
228
  if (materialized)
204
229
  return materialized;
205
- throw new BridgeError(404, "The transcript is not available for this conversation.");
230
+ throw new BridgeError(404, "The transcript is not available for this conversation.", { code: "transcript-unavailable" });
206
231
  }
207
- const file = await realpath(matches[0]);
208
- if (!file.startsWith(root + path.sep))
232
+ const file = await realpath(chosen[0].match);
233
+ if (!file.startsWith(chosen[0].root + path.sep))
209
234
  throw new BridgeError(403, "The transcript points outside its agent folder.");
210
235
  return file;
211
236
  }
@@ -341,8 +366,14 @@ export class TranscriptReader {
341
366
  this.revision = index.revision;
342
367
  this.nextLine = held ?? index.lines;
343
368
  }
369
+ // Live reads run newest first. After a long disconnect or a burst of
370
+ // output, a bounded page can stop before the phone's cursor. Mark that
371
+ // page as a replacement so its start becomes a usable older-page cursor
372
+ // instead of silently merging two disjoint windows. A pending diff
373
+ // holds its row for a later poll and is not a completed page.
374
+ const skippedLiveLines = before === undefined && held === undefined && cursor > lower;
344
375
  return { entries: entries.reverse(), totalLines: index.lines, startLine: cursor, hasMore: cursor > 0,
345
- reset: resuming && !pastEnd ? false : reset };
376
+ reset: (resuming && !pastEnd ? false : reset) || skippedLiveLines };
346
377
  }, signal);
347
378
  }
348
379
  }
@@ -0,0 +1,85 @@
1
+ import { z } from "zod";
2
+ import { type Provider } from "./protocol.js";
3
+ /** Longest final reply kept from a Stop payload, in UTF-8 bytes (the receipt's limit). */
4
+ export declare const TURN_REPLY_LIMIT = 4000;
5
+ declare const turnRecordSchema: z.ZodObject<{
6
+ terminal: z.ZodString;
7
+ source: z.ZodEnum<{
8
+ claude: "claude";
9
+ codex: "codex";
10
+ copilot: "copilot";
11
+ opencode: "opencode";
12
+ phren: "phren";
13
+ }>;
14
+ session: z.ZodUnion<readonly [z.ZodString, z.ZodString]>;
15
+ seq: z.ZodNumber;
16
+ dispatch: z.ZodOptional<z.ZodString>;
17
+ startedAt: z.ZodOptional<z.ZodString>;
18
+ prompt: z.ZodOptional<z.ZodObject<{
19
+ seq: z.ZodNumber;
20
+ at: z.ZodString;
21
+ }, z.core.$strict>>;
22
+ stop: z.ZodOptional<z.ZodObject<{
23
+ seq: z.ZodNumber;
24
+ at: z.ZodString;
25
+ background: z.ZodOptional<z.ZodNumber>;
26
+ reply: z.ZodOptional<z.ZodString>;
27
+ truncated: z.ZodOptional<z.ZodBoolean>;
28
+ }, z.core.$strict>>;
29
+ at: z.ZodString;
30
+ }, z.core.$strict>;
31
+ export type TurnRecord = z.infer<typeof turnRecordSchema>;
32
+ export interface TurnEvent {
33
+ event: string;
34
+ terminal: string;
35
+ source: Provider;
36
+ session: string;
37
+ /** SessionStart / UserPromptSubmit: the dispatch id the worker's hook named. */
38
+ dispatch?: string;
39
+ /** Stop only: the harness's count of in-flight background tasks, when it reports one. */
40
+ background?: number;
41
+ /** Stop only: the harness's last assistant message, when it reports one. */
42
+ reply?: string;
43
+ at?: number;
44
+ }
45
+ export declare const turnPath: (server: string, pane: string) => string;
46
+ /** `value` cut to at most `limit` UTF-8 bytes on a character boundary. */
47
+ export declare function truncateUtf8(value: string, limit?: number): {
48
+ text: string;
49
+ truncated: boolean;
50
+ };
51
+ /** The record after one lifecycle event; undefined for events that say nothing about turns.
52
+ * Another conversation or terminal in the pane starts a fresh record. */
53
+ export declare function nextTurn(previous: TurnRecord | undefined, event: TurnEvent): TurnRecord | undefined;
54
+ export type TurnPhase = {
55
+ phase: "unprompted";
56
+ } | {
57
+ phase: "working";
58
+ since: string;
59
+ } | {
60
+ phase: "ended";
61
+ at: string;
62
+ background?: number;
63
+ reply?: string;
64
+ truncated?: boolean;
65
+ };
66
+ /** Where the recorded conversation is: no prompt yet, a prompt with no Stop
67
+ * after it, or a turn that stopped. A Stop with no recorded prompt (hooks
68
+ * installed mid-conversation) still ended a turn. */
69
+ export declare function turnPhase(record: TurnRecord): TurnPhase;
70
+ /** The background tasks of a Stop at `stoppedAt` still running: the Stop's
71
+ * count less the tasks whose finish the transcript recorded after it
72
+ * (`FinalTurn.finishedTasks`). No turn ran since that Stop, so every task
73
+ * finishing after it is one the count included; a finish does not always
74
+ * bring a new Stop (its notification can wait in an idle session's queue). */
75
+ export declare function backgroundLeft(count: number | undefined, stoppedAt: string, finishedTasks?: readonly string[]): number;
76
+ /** Record one lifecycle event for `pane`. Writes run one at a time, so a Stop
77
+ * and the next prompt arriving together keep their order. */
78
+ export declare function noteTurn(server: string, pane: string, event: TurnEvent): Promise<TurnRecord | undefined>;
79
+ /** The recorded turns of `pane`'s latest conversation, if its hooks reported any. */
80
+ export declare function readTurn(server: string, pane: string): Promise<TurnRecord | undefined>;
81
+ /** OpenCode's turns for a pane running `pids`, from the stamps phren's OpenCode
82
+ * plugin writes on session.status busy / session.idle; undefined for an older
83
+ * plugin that writes none. `terminal` is the pane's, since the PIDs are. */
84
+ export declare function opencodeTurn(pids: number[], terminal: string): Promise<TurnRecord | undefined>;
85
+ export {};