@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
@@ -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 {};
@@ -0,0 +1,143 @@
1
+ // What a pane's agent last said about its own turns, from its lifecycle hooks:
2
+ // when a prompt was submitted, when the turn stopped, what it stopped with and
3
+ // whether the harness still had background work in flight. Dispatch returns
4
+ // answer from this record first (dispatch-returns.ts `workerStates`): a
5
+ // worker is done only once a Stop arrived after its prompt, never because it
6
+ // has looked idle for a while.
7
+ //
8
+ // Claude, Codex, Copilot and phren-agent send SessionStart, UserPromptSubmit
9
+ // and Stop to the Hook (agent-hooks.ts), which records them here, one small
10
+ // file per pane beside its binding. OpenCode has no such hooks; phren's
11
+ // OpenCode plugin stamps its turns into the per-PID status file instead
12
+ // (`opencodeTurn`).
13
+ //
14
+ // The record is keyed by pane and holds the latest conversation there, with
15
+ // the dispatch id (PHREN_DISPATCH_ID) its SessionStart or first prompt named,
16
+ // so a dispatch placed on this computer is matched by id as well as by pane
17
+ // and conversation.
18
+ import { lstat, readFile } from "node:fs/promises";
19
+ import path from "node:path";
20
+ import { z } from "zod";
21
+ import { opencodeTurnStamps } from "./harness-status.js";
22
+ import { briefId } from "./launch-brief.js";
23
+ import { atomicInPrivateDir, bridgeRoot, provider, serverName, sessionId } from "./protocol.js";
24
+ /** Longest final reply kept from a Stop payload, in UTF-8 bytes (the receipt's limit). */
25
+ export const TURN_REPLY_LIMIT = 4000;
26
+ const MAX_RECORD_BYTES = 16_384;
27
+ const stamp = z.object({ seq: z.number().int().min(0), at: z.string().datetime() }).strict();
28
+ const turnRecordSchema = z.object({
29
+ terminal: z.string().min(1).max(200), source: provider, session: sessionId,
30
+ /** Climbs with every recorded event, so prompt and stop are ordered without trusting the clock. */
31
+ seq: z.number().int().min(0),
32
+ /** The dispatch this conversation was launched for, as its hooks named it. */
33
+ dispatch: briefId.optional(),
34
+ startedAt: z.string().datetime().optional(),
35
+ prompt: stamp.optional(),
36
+ stop: stamp.extend({
37
+ /** Background tasks (shells, subagents, monitors) the harness still ran when the turn stopped. */
38
+ background: z.number().int().min(0).max(999).optional(),
39
+ reply: z.string().max(TURN_REPLY_LIMIT).optional(), truncated: z.boolean().optional(),
40
+ }).strict().optional(),
41
+ at: z.string().datetime(),
42
+ }).strict();
43
+ export const turnPath = (server, pane) => path.join(bridgeRoot(), "turns", encodeURIComponent(serverName.parse(server)), encodeURIComponent(pane) + ".json");
44
+ /** `value` cut to at most `limit` UTF-8 bytes on a character boundary. */
45
+ export function truncateUtf8(value, limit = TURN_REPLY_LIMIT) {
46
+ const bytes = Buffer.from(value);
47
+ if (bytes.length <= limit)
48
+ return { text: value, truncated: false };
49
+ let end = limit;
50
+ while (end > 0 && (bytes[end] & 0xc0) === 0x80)
51
+ end--;
52
+ return { text: bytes.subarray(0, end).toString("utf8"), truncated: true };
53
+ }
54
+ /** The record after one lifecycle event; undefined for events that say nothing about turns.
55
+ * Another conversation or terminal in the pane starts a fresh record. */
56
+ export function nextTurn(previous, event) {
57
+ if (!["SessionStart", "UserPromptSubmit", "Stop"].includes(event.event))
58
+ return undefined;
59
+ const at = new Date(event.at ?? Date.now()).toISOString();
60
+ const same = previous && previous.terminal === event.terminal && previous.source === event.source && previous.session === event.session;
61
+ const record = same ? structuredClone(previous) : { terminal: event.terminal, source: event.source, session: event.session, seq: 0, at };
62
+ record.seq++;
63
+ record.at = at;
64
+ if (event.dispatch && briefId.safeParse(event.dispatch).success)
65
+ record.dispatch ??= event.dispatch;
66
+ if (event.event === "SessionStart")
67
+ record.startedAt ??= at;
68
+ else if (event.event === "UserPromptSubmit")
69
+ record.prompt = { seq: record.seq, at };
70
+ else {
71
+ const reply = event.reply?.trim() ? truncateUtf8(event.reply.trim()) : undefined;
72
+ record.stop = { seq: record.seq, at, ...(event.background !== undefined ? { background: Math.min(999, Math.max(0, Math.floor(event.background))) } : {}),
73
+ ...(reply ? { reply: reply.text, ...(reply.truncated ? { truncated: true } : {}) } : {}) };
74
+ }
75
+ return record;
76
+ }
77
+ /** Where the recorded conversation is: no prompt yet, a prompt with no Stop
78
+ * after it, or a turn that stopped. A Stop with no recorded prompt (hooks
79
+ * installed mid-conversation) still ended a turn. */
80
+ export function turnPhase(record) {
81
+ const { prompt, stop } = record;
82
+ if (prompt && (!stop || stop.seq < prompt.seq))
83
+ return { phase: "working", since: prompt.at };
84
+ if (!stop)
85
+ return { phase: "unprompted" };
86
+ return { phase: "ended", at: stop.at, ...(stop.background ? { background: stop.background } : {}),
87
+ ...(stop.reply ? { reply: stop.reply, ...(stop.truncated ? { truncated: true } : {}) } : {}) };
88
+ }
89
+ /** The background tasks of a Stop at `stoppedAt` still running: the Stop's
90
+ * count less the tasks whose finish the transcript recorded after it
91
+ * (`FinalTurn.finishedTasks`). No turn ran since that Stop, so every task
92
+ * finishing after it is one the count included; a finish does not always
93
+ * bring a new Stop (its notification can wait in an idle session's queue). */
94
+ export function backgroundLeft(count, stoppedAt, finishedTasks = []) {
95
+ if (!count)
96
+ return 0;
97
+ const stopped = Date.parse(stoppedAt);
98
+ return Math.max(0, count - finishedTasks.filter(at => Date.parse(at) >= stopped).length);
99
+ }
100
+ async function readRecord(file) {
101
+ try {
102
+ const info = await lstat(file);
103
+ if (!info.isFile() || info.size > MAX_RECORD_BYTES)
104
+ return undefined;
105
+ const parsed = turnRecordSchema.safeParse(JSON.parse(await readFile(file, "utf8")));
106
+ return parsed.success ? parsed.data : undefined;
107
+ }
108
+ catch {
109
+ return undefined;
110
+ }
111
+ }
112
+ let writes = Promise.resolve();
113
+ /** Record one lifecycle event for `pane`. Writes run one at a time, so a Stop
114
+ * and the next prompt arriving together keep their order. */
115
+ export function noteTurn(server, pane, event) {
116
+ const run = writes.then(async () => {
117
+ const file = turnPath(server, pane);
118
+ const next = nextTurn(await readRecord(file), event);
119
+ if (next)
120
+ await atomicInPrivateDir(file, turnRecordSchema.parse(next));
121
+ return next;
122
+ });
123
+ writes = run.catch(() => undefined);
124
+ return run;
125
+ }
126
+ /** The recorded turns of `pane`'s latest conversation, if its hooks reported any. */
127
+ export function readTurn(server, pane) {
128
+ return readRecord(turnPath(server, pane));
129
+ }
130
+ /** OpenCode's turns for a pane running `pids`, from the stamps phren's OpenCode
131
+ * plugin writes on session.status busy / session.idle; undefined for an older
132
+ * plugin that writes none. `terminal` is the pane's, since the PIDs are. */
133
+ export async function opencodeTurn(pids, terminal) {
134
+ const stamps = await opencodeTurnStamps(pids);
135
+ if (!stamps)
136
+ return undefined;
137
+ const busy = stamps.busyAt ? Date.parse(stamps.busyAt) : NaN, idle = stamps.idleAt ? Date.parse(stamps.idleAt) : NaN;
138
+ const parsed = turnRecordSchema.safeParse({ terminal, source: "opencode", session: stamps.session, seq: 2, at: stamps.at,
139
+ ...(Number.isFinite(busy) ? { prompt: { seq: 1, at: stamps.busyAt } } : {}),
140
+ // The plugin stamps idle after busy; an idle stamp older than the busy one belongs to an earlier turn.
141
+ ...(Number.isFinite(idle) && !(idle < busy) ? { stop: { seq: 2, at: stamps.idleAt } } : {}) });
142
+ return parsed.success ? parsed.data : undefined;
143
+ }
@@ -15,3 +15,6 @@ export declare function listUploads(session: string): Promise<{
15
15
  * any link) to a regular file inside the uploads folder whose bytes are
16
16
  * an image; anything else — outside, traversal, a note — is 404. */
17
17
  export declare function uploadImage(requested: string): Promise<Buffer>;
18
+ /** A file the phone uploaded for this conversation, by the path `/v1/upload`
19
+ * returned: it must resolve to a regular file inside uploads/<session>/. */
20
+ export declare function sessionUpload(session: string, requested: string): Promise<string>;
@@ -85,3 +85,17 @@ export async function uploadImage(requested) {
85
85
  throw missing;
86
86
  return bytes;
87
87
  }
88
+ /** A file the phone uploaded for this conversation, by the path `/v1/upload`
89
+ * returned: it must resolve to a regular file inside uploads/<session>/. */
90
+ export async function sessionUpload(session, requested) {
91
+ const refused = new BridgeError(400, "An attachment is not one of this conversation's uploads. Attach it again.");
92
+ if (!requested || requested.length > 4096 || !path.isAbsolute(requested))
93
+ throw refused;
94
+ const folder = await realpath(path.join(bridgeRoot(), "uploads", session)).catch(() => undefined);
95
+ const file = await realpath(requested).catch(() => undefined);
96
+ if (!folder || !file || !file.startsWith(folder + path.sep))
97
+ throw refused;
98
+ if (!(await stat(file)).isFile())
99
+ throw refused;
100
+ return file;
101
+ }