@phren/cli 0.3.16 → 0.3.18

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 (46) hide show
  1. package/dist/bridge/agent-hooks.d.ts +10 -0
  2. package/dist/bridge/agent-hooks.js +49 -10
  3. package/dist/bridge/claude-suggestion.d.ts +8 -0
  4. package/dist/bridge/claude-suggestion.js +71 -0
  5. package/dist/bridge/dispatch-returns.d.ts +6 -3
  6. package/dist/bridge/dispatch-returns.js +29 -17
  7. package/dist/bridge/job-registry.d.ts +144 -0
  8. package/dist/bridge/job-registry.js +247 -0
  9. package/dist/bridge/opencode-permissions.d.ts +17 -0
  10. package/dist/bridge/opencode-permissions.js +96 -0
  11. package/dist/bridge/permission-mode.d.ts +48 -0
  12. package/dist/bridge/permission-mode.js +144 -0
  13. package/dist/bridge/protocol.d.ts +4 -0
  14. package/dist/bridge/protocol.js +3 -0
  15. package/dist/bridge/resources.d.ts +38 -5
  16. package/dist/bridge/resources.js +110 -19
  17. package/dist/bridge/server-launch.js +8 -0
  18. package/dist/bridge/server-pane-routes.d.ts +2 -0
  19. package/dist/bridge/server-pane-routes.js +12 -2
  20. package/dist/bridge/server-routes.d.ts +3 -1
  21. package/dist/bridge/server-routes.js +8 -6
  22. package/dist/bridge/server-stream.js +14 -2
  23. package/dist/bridge/server.js +4 -2
  24. package/dist/bridge/session-activity.d.ts +13 -0
  25. package/dist/bridge/session-activity.js +27 -2
  26. package/dist/bridge/settings-switch.d.ts +19 -7
  27. package/dist/bridge/settings-switch.js +21 -29
  28. package/dist/bridge/speech.d.ts +6 -4
  29. package/dist/bridge/speech.js +6 -4
  30. package/dist/bridge/terminal-tmux.d.ts +4 -2
  31. package/dist/bridge/terminal-tmux.js +13 -7
  32. package/dist/bridge/transcript-claude.d.ts +9 -1
  33. package/dist/bridge/transcript-claude.js +50 -1
  34. package/dist/bridge/transcript-codex.js +23 -3
  35. package/dist/bridge/transcripts.d.ts +5 -1
  36. package/dist/bridge/transcripts.js +13 -3
  37. package/dist/bridge-hook.mjs +1169 -546
  38. package/dist/computers/command.js +2 -1
  39. package/dist/fanout/opencode-serve.js +3 -2
  40. package/dist/hooks.d.ts +3 -0
  41. package/dist/hooks.js +41 -6
  42. package/dist/init/setup.js +6 -3
  43. package/dist/modules/registry.js +2 -2
  44. package/dist/tools/dispatch.js +3 -2
  45. package/package.json +1 -1
  46. package/plugins/opencode/phren-transcript.js +4 -4
@@ -1,6 +1,8 @@
1
1
  import { AgentHooks } from "./agent-hooks.js";
2
2
  import { type CodexNextTurn } from "./codex-servers.js";
3
+ import { type PermissionModeName } from "./permission-mode.js";
3
4
  import { type Json, type PermissionMode, type Target } from "./protocol.js";
5
+ export { claudeFooterMode } from "./permission-mode.js";
4
6
  /** T3's CodexSessionRuntime mapping. The reviewer is always sent: leaving it
5
7
  * out would keep `auto_review` from an earlier turn. */
6
8
  export declare const CODEX_MODES: Record<PermissionMode, Pick<CodexNextTurn, "approvalPolicy" | "approvalsReviewer" | "sandboxPolicy">>;
@@ -17,11 +19,6 @@ export interface SettingsCapabilities {
17
19
  * from its transcript, but switching is not offered. Claude's cycle holds
18
20
  * `full-access` only when it was launched allowing bypass. */
19
21
  export declare function settingsCapabilities(source: string, codexServed: boolean, claudeBypass?: boolean): SettingsCapabilities | undefined;
20
- /** Claude's permission mode from the footer line its TUI draws under the
21
- * composer. The transcript lags it: a `permission-mode` row is written only
22
- * when a prompt is submitted, and a fresh session has no file yet. The line may
23
- * trail hints ("(shift+tab to cycle) · 1 agent"), so only its start counts. */
24
- export declare function claudeFooterMode(screen: string): string | undefined;
25
22
  export interface SettingsState {
26
23
  permissionMode?: string;
27
24
  plan?: boolean;
@@ -29,7 +26,8 @@ export interface SettingsState {
29
26
  }
30
27
  /** A Claude pane's settings as its footer shows them, read at most once per
31
28
  * `PHREN_DIALOG_THROTTLE_MS` like the dialog check, and whether bypass was
32
- * ever seen in it (which is when full access is offered). */
29
+ * ever seen in it (which is when full access is offered). The same read, with
30
+ * its styles, carries the suggested next prompt in the input box. */
33
31
  export declare class ClaudeSettingsReader {
34
32
  private readonly hooks;
35
33
  private readonly every;
@@ -38,6 +36,12 @@ export declare class ClaudeSettingsReader {
38
36
  read(target: Target, terminal: unknown): Promise<{
39
37
  state?: SettingsState;
40
38
  bypass: boolean;
39
+ suggestion?: {
40
+ text: string;
41
+ readAt: number;
42
+ };
43
+ permissionMode?: PermissionModeName;
44
+ permissionModes?: PermissionModeName[];
41
45
  }>;
42
46
  }
43
47
  /** One settings transaction per pane owns its terminal input until it ends. */
@@ -47,10 +51,18 @@ export declare class SettingsSwitcher {
47
51
  private active;
48
52
  private readonly reader;
49
53
  constructor(hooks: AgentHooks, wait?: number);
50
- /** A Claude pane's footer-read settings and capabilities for the stream. */
54
+ /** A Claude pane's footer-read settings and capabilities for the stream,
55
+ * with the suggested next prompt its input box shows and the raw permission
56
+ * mode (`agentStatus.permissionMode`) its picker offers. */
51
57
  streamSettings(target: Target, terminal: unknown, codexServed: boolean): Promise<{
52
58
  settings?: SettingsCapabilities;
53
59
  settingsState?: SettingsState;
60
+ suggestion?: {
61
+ text: string;
62
+ readAt: number;
63
+ };
64
+ permissionMode?: PermissionModeName;
65
+ permissionModes?: PermissionModeName[];
54
66
  }>;
55
67
  private key;
56
68
  assertAvailable(target: Target): void;
@@ -1,14 +1,17 @@
1
1
  import { open, stat } from "node:fs/promises";
2
2
  import { z } from "zod";
3
+ import { stripTerminal } from "../terminal-text.js";
3
4
  import { visibleTerminalChoice } from "./agent-hooks.js";
5
+ import { claudeSuggestion } from "./claude-suggestion.js";
4
6
  import { codexServers } from "./codex-servers.js";
5
7
  import { validateTarget } from "./herdr.js";
6
8
  import { intervalFromEnv } from "./limits.js";
7
9
  import { emptyComposer } from "./model-switch.js";
10
+ import { claudeFooterMode, permissionModes } from "./permission-mode.js";
8
11
  import { BridgeError, object, PERMISSION_MODES } from "./protocol.js";
9
12
  import { terminalProvider } from "./terminal.js";
10
13
  import { transcriptPath } from "./transcripts.js";
11
- import { stripTerminal } from "../terminal-text.js";
14
+ export { claudeFooterMode } from "./permission-mode.js";
12
15
  /** T3's CodexSessionRuntime mapping. The reviewer is always sent: leaving it
13
16
  * out would keep `auto_review` from an earlier turn. */
14
17
  export const CODEX_MODES = {
@@ -40,31 +43,10 @@ export function settingsCapabilities(source, codexServed, claudeBypass = false)
40
43
  }
41
44
  const request = z.object({ permissionMode: z.enum(PERMISSION_MODES).optional(), plan: z.boolean().optional(), fast: z.boolean().optional() })
42
45
  .strict().refine(value => value.permissionMode !== undefined || value.plan !== undefined || value.fast !== undefined, "Choose a setting to change.");
43
- /** Claude's permission mode from the footer line its TUI draws under the
44
- * composer. The transcript lags it: a `permission-mode` row is written only
45
- * when a prompt is submitted, and a fresh session has no file yet. The line may
46
- * trail hints ("(shift+tab to cycle) · 1 agent"), so only its start counts. */
47
- export function claudeFooterMode(screen) {
48
- for (const line of stripTerminal(screen).split(/\r?\n/).map(line => line.trim()).filter(Boolean).slice(-8).reverse()) {
49
- const text = line.replace(/^[⏵⏸]+\s*/, "");
50
- if (text === line)
51
- continue;
52
- if (/bypass permissions on/i.test(text))
53
- return "bypassPermissions";
54
- if (/^manual mode on\b/i.test(text))
55
- return "default";
56
- if (/^accept edits on\b/i.test(text))
57
- return "acceptEdits";
58
- if (/^plan mode on\b/i.test(text))
59
- return "plan";
60
- if (/^auto mode on\b/i.test(text))
61
- return "auto";
62
- }
63
- return undefined;
64
- }
65
46
  /** A Claude pane's settings as its footer shows them, read at most once per
66
47
  * `PHREN_DIALOG_THROTTLE_MS` like the dialog check, and whether bypass was
67
- * ever seen in it (which is when full access is offered). */
48
+ * ever seen in it (which is when full access is offered). The same read, with
49
+ * its styles, carries the suggested next prompt in the input box. */
68
50
  export class ClaudeSettingsReader {
69
51
  hooks;
70
52
  every;
@@ -83,14 +65,21 @@ export class ClaudeSettingsReader {
83
65
  this.cache.set(key, entry);
84
66
  if (Date.now() - entry.at >= this.every) {
85
67
  entry.at = Date.now();
86
- entry.mode = await this.hooks.paneLines(target).then(claudeFooterMode, () => entry.mode);
68
+ const screen = await this.hooks.paneAnsi(target).catch(() => undefined);
69
+ if (screen !== undefined)
70
+ entry.mode = claudeFooterMode(screen);
71
+ entry.suggestion = screen === undefined ? undefined : claudeSuggestion(screen);
87
72
  if (entry.mode === "bypassPermissions")
88
73
  entry.bypass = true;
89
74
  while (this.cache.size > 64)
90
75
  this.cache.delete(this.cache.keys().next().value);
91
76
  }
92
77
  const phone = entry.mode ? CLAUDE_MODES[entry.mode] : undefined;
93
- return { bypass: entry.bypass, ...(phone ? { state: phone === "plan" ? { plan: true } : { permissionMode: phone, plan: false } } : {}) };
78
+ return { bypass: entry.bypass, ...(phone ? { state: phone === "plan" ? { plan: true } : { permissionMode: phone, plan: false } } : {}),
79
+ ...(entry.suggestion ? { suggestion: { text: entry.suggestion, readAt: entry.at } } : {}),
80
+ // The raw Claude mode the phone's mode picker shows, only when the footer
81
+ // was read: an unreadable one is not a confident "default".
82
+ ...(entry.mode ? { permissionMode: entry.mode, permissionModes: permissionModes(entry.bypass) } : {}) };
94
83
  }
95
84
  }
96
85
  /** Claude's answer to a slash command: the first `<local-command-stdout>` user
@@ -130,14 +119,17 @@ export class SettingsSwitcher {
130
119
  this.wait = wait;
131
120
  this.reader = new ClaudeSettingsReader(hooks);
132
121
  }
133
- /** A Claude pane's footer-read settings and capabilities for the stream. */
122
+ /** A Claude pane's footer-read settings and capabilities for the stream,
123
+ * with the suggested next prompt its input box shows and the raw permission
124
+ * mode (`agentStatus.permissionMode`) its picker offers. */
134
125
  async streamSettings(target, terminal, codexServed) {
135
126
  if (target.source !== "claude") {
136
127
  const settings = settingsCapabilities(target.source, codexServed);
137
128
  return settings ? { settings } : {};
138
129
  }
139
- const { state, bypass } = await this.reader.read(target, terminal);
140
- return { settings: settingsCapabilities("claude", false, bypass), ...(state ? { settingsState: state } : {}) };
130
+ const { state, bypass, suggestion, permissionMode, permissionModes } = await this.reader.read(target, terminal);
131
+ return { settings: settingsCapabilities("claude", false, bypass), ...(state ? { settingsState: state } : {}), ...(suggestion ? { suggestion } : {}),
132
+ ...(permissionMode ? { permissionMode, permissionModes } : {}) };
141
133
  }
142
134
  key(target) { return `${target.server}:${target.pane}`; }
143
135
  assertAvailable(target) {
@@ -11,10 +11,11 @@ export { DEFAULT_SPEECH_MODEL, DEFAULT_SPEECH_VOICE, FALLBACK_SPEECH_MODEL } fro
11
11
  * it queues straight into its audio engine without decoding. */
12
12
  export declare const SPEECH_AUDIO = "pcm_s16le;rate=24000;channels=1";
13
13
  /** ElevenLabs output formats the Hook can serve, best first. Each account
14
- * plan allows some of them (Creator refuses pcm_44100, which is Pro and
15
- * above); the Hook learns which from ElevenLabs' refusal rather than a
16
- * hard-coded plan table. pcm_24000 works on every plan and every phone. */
17
- export declare const SPEECH_FORMATS: readonly ["pcm_44100", "mp3_44100_192", "pcm_24000"];
14
+ * plan allows some of them (pcm_44100 is Pro and above, mp3_44100_192 is
15
+ * Creator and above); the Hook learns which from ElevenLabs' refusal rather
16
+ * than a hard-coded plan table. pcm_24000 works on every plan and every
17
+ * phone, so it is the base every request falls back to. */
18
+ export declare const SPEECH_FORMATS: readonly ["pcm_44100", "mp3_44100_192", "mp3_44100_128", "pcm_24000"];
18
19
  export type SpeechFormat = typeof SPEECH_FORMATS[number];
19
20
  /** How each format is described to the phone: `audioFormat` in the JSON reply
20
21
  * and `X-Phren-Audio` on the streamed one, plus the sample rate on its own. */
@@ -37,6 +38,7 @@ export declare const speechRequest: z.ZodObject<{
37
38
  timestamps: z.ZodOptional<z.ZodBoolean>;
38
39
  voice: z.ZodOptional<z.ZodString>;
39
40
  formats: z.ZodPreprocess<z.ZodOptional<z.ZodArray<z.ZodEnum<{
41
+ mp3_44100_128: "mp3_44100_128";
40
42
  mp3_44100_192: "mp3_44100_192";
41
43
  pcm_24000: "pcm_24000";
42
44
  pcm_44100: "pcm_44100";
@@ -13,16 +13,18 @@ export { DEFAULT_SPEECH_MODEL, DEFAULT_SPEECH_VOICE, FALLBACK_SPEECH_MODEL } fro
13
13
  * it queues straight into its audio engine without decoding. */
14
14
  export const SPEECH_AUDIO = "pcm_s16le;rate=24000;channels=1";
15
15
  /** ElevenLabs output formats the Hook can serve, best first. Each account
16
- * plan allows some of them (Creator refuses pcm_44100, which is Pro and
17
- * above); the Hook learns which from ElevenLabs' refusal rather than a
18
- * hard-coded plan table. pcm_24000 works on every plan and every phone. */
19
- export const SPEECH_FORMATS = ["pcm_44100", "mp3_44100_192", "pcm_24000"];
16
+ * plan allows some of them (pcm_44100 is Pro and above, mp3_44100_192 is
17
+ * Creator and above); the Hook learns which from ElevenLabs' refusal rather
18
+ * than a hard-coded plan table. pcm_24000 works on every plan and every
19
+ * phone, so it is the base every request falls back to. */
20
+ export const SPEECH_FORMATS = ["pcm_44100", "mp3_44100_192", "mp3_44100_128", "pcm_24000"];
20
21
  const BASE_FORMAT = "pcm_24000";
21
22
  /** How each format is described to the phone: `audioFormat` in the JSON reply
22
23
  * and `X-Phren-Audio` on the streamed one, plus the sample rate on its own. */
23
24
  export const SPEECH_FORMAT_INFO = {
24
25
  pcm_44100: { audio: "pcm_s16le;rate=44100;channels=1", sampleRate: 44_100, contentType: "application/octet-stream" },
25
26
  mp3_44100_192: { audio: "mp3;rate=44100;bitrate=192000;channels=1", sampleRate: 44_100, contentType: "audio/mpeg" },
27
+ mp3_44100_128: { audio: "mp3;rate=44100;bitrate=128000;channels=1", sampleRate: 44_100, contentType: "audio/mpeg" },
26
28
  pcm_24000: { audio: SPEECH_AUDIO, sampleRate: 24_000, contentType: "application/octet-stream" },
27
29
  };
28
30
  /** Talk mode waits for the whole sentence on the timestamped path, so a model
@@ -38,8 +38,10 @@ export declare function tmuxBinary(): string | undefined;
38
38
  * where `-L` looks, then `/tmp/tmux-<uid>` when TMUX_TMPDIR points elsewhere
39
39
  * (a server started from a shell with another TMUX_TMPDIR than the Hook's). */
40
40
  export declare function tmuxSocketFolders(env?: NodeJS.ProcessEnv): string[];
41
- /** The tmux sockets in `folder` this user owns, by name (at most 32). A socket
42
- * outside the first folder of `tmuxSocketFolders` is remembered by path. */
41
+ /** The tmux sockets in `folder` this user owns, by name, most recently active
42
+ * first, so a live server sorts ahead of stale socket files left by killed
43
+ * runs. A socket outside the first folder of `tmuxSocketFolders` is remembered
44
+ * by path. */
43
45
  export declare function tmuxSocketsIn(folder: string): Promise<string[]>;
44
46
  /** For tests: replace how tmux and ps run; the returned function restores them. */
45
47
  export declare function setTmuxDeps(replacement: Partial<TmuxDeps>): () => void;
@@ -96,25 +96,28 @@ function socketFlags(socket) {
96
96
  const file = socketPaths.get(socket);
97
97
  return file ? ["-S", file] : ["-L", socket];
98
98
  }
99
- /** The tmux sockets in `folder` this user owns, by name (at most 32). A socket
100
- * outside the first folder of `tmuxSocketFolders` is remembered by path. */
99
+ /** The tmux sockets in `folder` this user owns, by name, most recently active
100
+ * first, so a live server sorts ahead of stale socket files left by killed
101
+ * runs. A socket outside the first folder of `tmuxSocketFolders` is remembered
102
+ * by path. */
101
103
  export async function tmuxSocketsIn(folder) {
102
104
  const uid = process.getuid?.(), primary = tmuxSocketFolders()[0];
103
105
  const names = (await readdir(folder).catch(() => [])).slice(0, 256);
104
106
  const found = [];
105
107
  for (const name of names) {
106
- if (found.length >= 32)
107
- break;
108
108
  if (!tmuxServerName(name))
109
109
  continue;
110
110
  const info = await lstat(path.join(folder, name)).catch(() => undefined);
111
111
  if (!info?.isSocket() || (uid !== undefined && info.uid !== uid))
112
112
  continue;
113
- found.push(name);
113
+ found.push({ name, at: info.mtimeMs });
114
114
  if (folder !== primary && !socketPaths.has(name) && !existsSync(path.join(primary ?? folder, name)))
115
115
  socketPaths.set(name, path.join(folder, name));
116
116
  }
117
- return found;
117
+ found.sort((a, b) => b.at - a.at);
118
+ // Most recent first, then capped: each candidate costs a tmux process
119
+ // per snapshot, and stale files from killed runs sort to the end.
120
+ return found.slice(0, 32).map(entry => entry.name);
118
121
  }
119
122
  const defaultDeps = {
120
123
  binary: tmuxBinary,
@@ -506,9 +509,12 @@ export const tmuxTerminal = {
506
509
  };
507
510
  /** The owner's tmux servers that answer, by Hook server name: the default
508
511
  * socket and every other socket in the user's tmux folders (`tmux -L work`
509
- * is "tmux-work"), at most 16. The hidden server is not among them. */
512
+ * is "tmux-work"), the 16 most recently active. Sockets are ordered by
513
+ * activity, so stale socket files from killed runs can't crowd out a live
514
+ * server. The hidden server is not among them. */
510
515
  async function ownerServers() {
511
516
  const sockets = [...new Set(["default", ...await deps.sockets().catch(() => [])])].filter(socket => socket !== "phren");
517
+ // Sockets arrive most recently active first, so the cap keeps live servers.
512
518
  const names = sockets.flatMap(socket => tmuxServerName(socket) ?? []).slice(0, 16);
513
519
  const running = await Promise.all(names.map(name => tmuxTerminal.ping(name).then(() => true, () => false)));
514
520
  return names.filter((_, index) => running[index]);
@@ -11,6 +11,14 @@ export declare function claudeChildAgents(file: string, session: string): Promis
11
11
  * taken as finished: the parent records no end for it, and a session that
12
12
  * exited mid-skill leaves it without a final reply. */
13
13
  export declare const CLAUDE_SKILL_QUIET_MS: number;
14
+ /** State one newest-first pass over a Claude transcript keeps so a
15
+ * content-free `dequeue` can name the prompt turn it delivered: the queue key
16
+ * of that turn and whether the agent's own schedule (a cron, /loop or
17
+ * ScheduleWakeup fire, or an auto-continuation) injected it. */
18
+ export interface ClaudeQueueState {
19
+ key?: string;
20
+ scheduled?: boolean;
21
+ }
14
22
  export declare const harnessPreamble: (text: string) => boolean;
15
23
  export declare function unwrapPastedContent(text: string): string;
16
24
  /** A thinking block Claude marks as narration for the person watching: its
@@ -29,4 +37,4 @@ export declare function phrenHookContext(raw: Json, includeSidechain?: boolean):
29
37
  /** Claude Code rows the phone may see: user, assistant and system turns with
30
38
  * private reasoning redacted, queued phone messages, background task
31
39
  * notifications and compaction markers. */
32
- export declare function visibleClaudeEvent(raw: Json, includeSidechain?: boolean): Json | undefined;
40
+ export declare function visibleClaudeEvent(raw: Json, includeSidechain?: boolean, queue?: ClaudeQueueState): Json | undefined;
@@ -356,6 +356,26 @@ async function claudeChildBelongsTo(file, parent, agentId) {
356
356
  // it is what the phone's model chip shows as in effect. `permissionMode` on a
357
357
  // user row is the mode that turn ran in (the phone's permission chip).
358
358
  const CLAUDE_KEYS = new Set(["type", "uuid", "parentUuid", "timestamp", "message", "gitBranch", "cwd", "requestId", "isMeta", "isSidechain", "isCompactSummary", "phrenQueued", "phrenQueueKey", "phrenBackground", "phrenCompacted", "effort", "permissionMode"]);
359
+ /** The `phrenQueueKey` of the prompt turn a queued message was delivered as:
360
+ * the same SHA-256 of the unwrapped content the enqueue row exports. Undefined
361
+ * for a tool result, a harness envelope, or a turn that is not the person's. */
362
+ function queuePromptKey(raw) {
363
+ if (raw.type !== "user" || raw.isSidechain === true)
364
+ return undefined;
365
+ const content = object(raw.message).content;
366
+ const text = unwrapPastedContent(typeof content === "string" ? content
367
+ : objects(content).filter(block => block.type === "text").map(block => String(block.text ?? "")).join("\n"));
368
+ if (!text.trim() || text.trimStart().startsWith("<"))
369
+ return undefined;
370
+ return createHash("sha256").update(text).digest("hex");
371
+ }
372
+ /** A prompt the agent scheduled for itself, which Claude Code delivers as a
373
+ * hidden user turn (`isMeta`). Auto-continuation names its origin rather than
374
+ * a task id. */
375
+ function scheduledPromptTurn(raw) {
376
+ return raw.turnOrigin === "scheduled" || typeof raw.scheduledTaskId === "string"
377
+ || object(raw.origin).kind === "auto-continuation";
378
+ }
359
379
  export const harnessPreamble = (text) => /^<(?:environment_context>|user_instructions>|permission_profile|system-reminder>|turn_context>)/.test(text.trimStart());
360
380
  function taskNotification(content) {
361
381
  const envelope = /<task-notification>([\s\S]*?)<\/task-notification>/.exec(content)?.[1];
@@ -457,7 +477,7 @@ export function phrenHookContext(raw, includeSidechain = false) {
457
477
  /** Claude Code rows the phone may see: user, assistant and system turns with
458
478
  * private reasoning redacted, queued phone messages, background task
459
479
  * notifications and compaction markers. */
460
- export function visibleClaudeEvent(raw, includeSidechain = false) {
480
+ export function visibleClaudeEvent(raw, includeSidechain = false, queue) {
461
481
  // A follow-up the phone sent a Claude fan-out worker, written into its
462
482
  // event log by the Hook before the resumed run.
463
483
  if (raw.type === "phren/fanout-message" && typeof raw.text === "string") {
@@ -467,6 +487,26 @@ export function visibleClaudeEvent(raw, includeSidechain = false) {
467
487
  // digest so enqueue and remove keep matching keys.
468
488
  if (raw.type === "queue-operation" && typeof raw.content === "string")
469
489
  raw = { ...raw, content: unwrapPastedContent(raw.content) };
490
+ // A dequeue is the queue head handed to a turn. Unlike `remove` it carries
491
+ // no content, so its consumption is keyed by the prompt turn it delivered
492
+ // (a newest-first read sees that turn first) and flagged when the agent's
493
+ // own schedule fired it.
494
+ if (raw.type === "queue-operation" && raw.operation === "dequeue") {
495
+ const key = queue?.key, scheduled = queue?.scheduled;
496
+ // One prompt turn answers one dequeue: an older dequeue must not reuse
497
+ // this key and mark a different queued message consumed.
498
+ if (queue) {
499
+ queue.key = undefined;
500
+ queue.scheduled = undefined;
501
+ }
502
+ return { type: "phren_queue_consumed", ...(key ? { key } : {}), ...(key && scheduled ? { scheduled: true } : {}), timestamp: raw.timestamp };
503
+ }
504
+ // popAll pulls queued prompts back into the input: they were neither
505
+ // consumed nor scheduled, so the phone must not draw the leftovers as a
506
+ // "Scheduled check" after the next reply.
507
+ if (raw.type === "queue-operation" && raw.operation === "popAll" && typeof raw.content === "string") {
508
+ return { type: "phren_queue_returned", key: createHash("sha256").update(raw.content).digest("hex"), timestamp: raw.timestamp };
509
+ }
470
510
  if (raw.type === "queue-operation" && raw.operation === "remove" && typeof raw.content === "string") {
471
511
  return { type: "phren_queue_consumed", key: createHash("sha256").update(raw.content).digest("hex"), timestamp: raw.timestamp };
472
512
  }
@@ -529,6 +569,15 @@ export function visibleClaudeEvent(raw, includeSidechain = false) {
529
569
  if (raw.type === "permission-mode" && typeof raw.permissionMode === "string" && /^[A-Za-z]{1,30}$/.test(raw.permissionMode)) {
530
570
  return { type: "permission-mode", permissionMode: raw.permissionMode, ...(typeof raw.timestamp === "string" ? { timestamp: raw.timestamp } : {}) };
531
571
  }
572
+ // Remember the prompt turn a queued message was delivered as, so the
573
+ // content-free dequeue written before it can be keyed and flagged scheduled.
574
+ if (queue && raw.type === "user") {
575
+ const key = queuePromptKey(raw);
576
+ if (key !== undefined) {
577
+ queue.key = key;
578
+ queue.scheduled = scheduledPromptTurn(raw);
579
+ }
580
+ }
532
581
  if (raw.isMeta || (raw.isSidechain && !includeSidechain) || !["user", "assistant", "system"].includes(String(raw.type)))
533
582
  return undefined;
534
583
  raw = Object.fromEntries(Object.entries(raw).filter(([key]) => CLAUDE_KEYS.has(key)));
@@ -1,5 +1,5 @@
1
1
  import { createReadStream } from "node:fs";
2
- import { stat } from "node:fs/promises";
2
+ import { open, 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";
@@ -24,6 +24,24 @@ function addChildRelation(line, found) {
24
24
  }
25
25
  catch { /* Ignore malformed/private rows. */ }
26
26
  }
27
+ const TAIL_CHECK = 256;
28
+ async function readAt(file, position, length) {
29
+ const handle = await open(file, "r");
30
+ try {
31
+ const buffer = Buffer.alloc(length);
32
+ const { bytesRead } = await handle.read(buffer, 0, length, position);
33
+ return buffer.subarray(0, bytesRead);
34
+ }
35
+ finally {
36
+ await handle.close();
37
+ }
38
+ }
39
+ /** Whether `file` still holds `expected` at `position`. */
40
+ async function sameBytes(file, position, expected) {
41
+ if (position < 0)
42
+ return false;
43
+ return (await readAt(file, position, expected.length).catch(() => Buffer.alloc(0))).equals(expected);
44
+ }
27
45
  export async function directChildAgents(file) {
28
46
  const metadata = await stat(file), cached = childRelationCache.get(file);
29
47
  if (cached && cached.dev === metadata.dev && cached.ino === metadata.ino
@@ -32,7 +50,8 @@ export async function directChildAgents(file) {
32
50
  // Codex rollouts are append-only. Keep the byte position of the last full
33
51
  // JSONL row so a live transcript only scans new rows as its chat advances.
34
52
  // A truncate, replacement, or in-place rewrite starts from zero.
35
- const append = cached && cached.dev === metadata.dev && cached.ino === metadata.ino && metadata.size > cached.fileSize;
53
+ const append = cached && cached.dev === metadata.dev && cached.ino === metadata.ino && metadata.size > cached.fileSize
54
+ && await sameBytes(file, cached.completeOffset - cached.tail.length, cached.tail);
36
55
  const start = append ? cached.completeOffset : 0;
37
56
  const found = append ? new Map(cached.relations) : new Map();
38
57
  let pending = Buffer.alloc(0), completeOffset = start;
@@ -46,8 +65,9 @@ export async function directChildAgents(file) {
46
65
  pending = pending.subarray(newline + 1);
47
66
  }
48
67
  }
68
+ const tail = completeOffset > 0 ? await readAt(file, Math.max(0, completeOffset - TAIL_CHECK), Math.min(TAIL_CHECK, completeOffset)) : Buffer.alloc(0);
49
69
  const entry = { dev: metadata.dev, ino: metadata.ino, fileSize: metadata.size, completeOffset,
50
- mtimeMs: metadata.mtimeMs, relations: found };
70
+ mtimeMs: metadata.mtimeMs, tail, relations: found };
51
71
  childRelationCache.set(file, entry);
52
72
  while (childRelationCache.size > 64)
53
73
  childRelationCache.delete(childRelationCache.keys().next().value);
@@ -1,6 +1,7 @@
1
1
  import { type AccountRef } from "./claude-accounts.js";
2
2
  import { type Json, type Provider, type Target } from "./protocol.js";
3
3
  import { type ChangeLookup } from "./changes.js";
4
+ import { type ClaudeQueueState } from "./transcript-claude.js";
4
5
  export { isNarration, unwrapPastedContent } from "./transcript-claude.js";
5
6
  export { codeToolCalls, projectCodexRow, type CodeToolCall } from "./transcript-codex.js";
6
7
  export interface Entry {
@@ -55,6 +56,9 @@ export declare function childAgentTree(source: Provider, session: string, depth?
55
56
  * from being returned if relation internals grow later. */
56
57
  export declare function publicChildAgents(tree: ChildAgentRelation[]): Json[];
57
58
  export declare function childAgent(tree: ChildAgentRelation[], id: string): LocalChildAgentRelation | undefined;
59
+ /** The running children of a child-agent tree, at any depth: the sub-agents,
60
+ * teammates, workflow agents and fan-out jobs a finished turn still waits on. */
61
+ export declare function runningChildAgents(tree: ChildAgentRelation[]): ChildAgentRelation[];
58
62
  /**
59
63
  * The phren store whose `.runtime/sessions` holds phren-agent event logs.
60
64
  * `PHREN_PATH` or the shared `~/.phren` root — the two resolutions the CLI's
@@ -78,7 +82,7 @@ export declare function transcriptPath(source: Provider, session: string, accoun
78
82
  * transcripts the agent writes itself. */
79
83
  export declare function refreshTranscript(file: string, source: Provider, session: string): Promise<void>;
80
84
  /** Public conversation/tool events and real usage only. Never export private reasoning. */
81
- export declare function visibleEvent(raw: Json, source: Provider, includeSidechain?: boolean, cwd?: string): Json | undefined;
85
+ export declare function visibleEvent(raw: Json, source: Provider, includeSidechain?: boolean, cwd?: string, queue?: ClaudeQueueState): Json | undefined;
82
86
  /** Parse only the requested page; shared byte indexes make reopening and
83
87
  * backward pagination independent of the amount of already-read history. */
84
88
  export declare class TranscriptReader {
@@ -70,6 +70,13 @@ export function childAgent(tree, id) {
70
70
  return nested;
71
71
  }
72
72
  }
73
+ /** The running children of a child-agent tree, at any depth: the sub-agents,
74
+ * teammates, workflow agents and fan-out jobs a finished turn still waits on. */
75
+ export function runningChildAgents(tree) {
76
+ return tree.flatMap(function visit(child) {
77
+ return [child, ...child.children.flatMap(visit)];
78
+ }).filter(child => child.state === "running");
79
+ }
73
80
  /** Preserve content positions and image types; original bytes stay in the
74
81
  * transcript for the separate image route. Only provider content blocks are
75
82
  * interpreted, never text strings or arbitrary tool arguments. */
@@ -241,13 +248,13 @@ export async function refreshTranscript(file, source, session) {
241
248
  await materializeCodexThread(session);
242
249
  }
243
250
  /** Public conversation/tool events and real usage only. Never export private reasoning. */
244
- export function visibleEvent(raw, source, includeSidechain = false, cwd) {
251
+ export function visibleEvent(raw, source, includeSidechain = false, cwd, queue) {
245
252
  if (source === "phren" || source === "opencode")
246
253
  return visibleOpencodeEvent(raw, source, cwd);
247
254
  if (source === "codex")
248
255
  return visibleCodexEvent(raw);
249
256
  if (source === "claude")
250
- return visibleClaudeEvent(raw, includeSidechain);
257
+ return visibleClaudeEvent(raw, includeSidechain, queue);
251
258
  return visibleCopilotEvent(raw);
252
259
  }
253
260
  /** Parse only the requested page; shared byte indexes make reopening and
@@ -299,11 +306,14 @@ export class TranscriptReader {
299
306
  const entryBudget = opening ? 60 : 200;
300
307
  const byteBudget = opening ? 1_048_576 : 4_194_304;
301
308
  let bytes = 0, cursor = end, held;
309
+ // Claude's queue pairing: the row scan is newest-first, so a prompt turn
310
+ // is seen before the content-free dequeue that delivered it.
311
+ const queue = {};
302
312
  for await (const row of index.rows(handle, end, lower, signal)) {
303
313
  signal?.throwIfAborted();
304
314
  let rows = [];
305
315
  try {
306
- let raw = row.bytes && visibleEvent(object(JSON.parse(row.bytes.toString())), this.source, this.includeSidechain, this.cwd);
316
+ let raw = row.bytes && visibleEvent(object(JSON.parse(row.bytes.toString())), this.source, this.includeSidechain, this.cwd, queue);
307
317
  // A child agent's transcript is the sidechain. Its rows are that
308
318
  // conversation's own turns, not something for the reader to skip.
309
319
  if (raw && this.includeSidechain && raw.isSidechain === true) {