@phren/cli 0.3.67 → 0.3.69

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 (83) hide show
  1. package/dist/bridge/agent-hook-callback.js +11 -2
  2. package/dist/bridge/agent-hooks.d.ts +11 -1
  3. package/dist/bridge/agent-hooks.js +259 -40
  4. package/dist/bridge/changes.d.ts +2 -2
  5. package/dist/bridge/changes.js +11 -9
  6. package/dist/bridge/checkpoints.d.ts +24 -0
  7. package/dist/bridge/checkpoints.js +423 -0
  8. package/dist/bridge/claude-input-state.d.ts +14 -0
  9. package/dist/bridge/claude-input-state.js +58 -0
  10. package/dist/bridge/claude-queue.js +5 -2
  11. package/dist/bridge/claude-suggestion.d.ts +3 -0
  12. package/dist/bridge/claude-suggestion.js +10 -0
  13. package/dist/bridge/codex-threads.d.ts +7 -1
  14. package/dist/bridge/codex-threads.js +185 -56
  15. package/dist/bridge/conversation-search.d.ts +20 -0
  16. package/dist/bridge/conversation-search.js +928 -0
  17. package/dist/bridge/git-watch.d.ts +46 -0
  18. package/dist/bridge/git-watch.js +351 -0
  19. package/dist/bridge/git-worktree-remove.d.ts +44 -0
  20. package/dist/bridge/git-worktree-remove.js +140 -0
  21. package/dist/bridge/git-worktrees.d.ts +14 -0
  22. package/dist/bridge/git-worktrees.js +7 -3
  23. package/dist/bridge/git-write-policy.js +1 -1
  24. package/dist/bridge/gitboy-webhooks.d.ts +3 -1
  25. package/dist/bridge/gitboy-webhooks.js +26 -2
  26. package/dist/bridge/herdr.d.ts +6 -1
  27. package/dist/bridge/herdr.js +56 -10
  28. package/dist/bridge/hook-fast.js +13 -1
  29. package/dist/bridge/input-classification.d.ts +33 -0
  30. package/dist/bridge/input-classification.js +84 -0
  31. package/dist/bridge/pane-status.d.ts +3 -3
  32. package/dist/bridge/pane-status.js +16 -8
  33. package/dist/bridge/prompt-deliveries.d.ts +30 -4
  34. package/dist/bridge/prompt-deliveries.js +365 -13
  35. package/dist/bridge/prompt-identity.d.ts +8 -0
  36. package/dist/bridge/prompt-identity.js +15 -0
  37. package/dist/bridge/request-origin.js +2 -1
  38. package/dist/bridge/schedule-events.d.ts +17 -0
  39. package/dist/bridge/schedule-events.js +53 -0
  40. package/dist/bridge/schedule-format.d.ts +22 -2
  41. package/dist/bridge/schedule-format.js +40 -5
  42. package/dist/bridge/schedule-update.js +2 -1
  43. package/dist/bridge/schedule-watch.js +15 -5
  44. package/dist/bridge/schedules.d.ts +9 -0
  45. package/dist/bridge/schedules.js +120 -7
  46. package/dist/bridge/server-pane-routes.d.ts +7 -8
  47. package/dist/bridge/server-pane-routes.js +186 -82
  48. package/dist/bridge/server-routes.d.ts +26 -2
  49. package/dist/bridge/server-routes.js +180 -56
  50. package/dist/bridge/server-stream.js +66 -15
  51. package/dist/bridge/server.js +25 -7
  52. package/dist/bridge/session-activity.d.ts +49 -4
  53. package/dist/bridge/session-activity.js +47 -0
  54. package/dist/bridge/session-evidence.d.ts +18 -0
  55. package/dist/bridge/session-evidence.js +72 -0
  56. package/dist/bridge/session-seen.d.ts +23 -0
  57. package/dist/bridge/session-seen.js +69 -0
  58. package/dist/bridge/tab-activity.d.ts +26 -1
  59. package/dist/bridge/tab-activity.js +64 -9
  60. package/dist/bridge/terminal-resolve.d.ts +20 -0
  61. package/dist/bridge/terminal-resolve.js +145 -0
  62. package/dist/bridge/terminal-tmux.d.ts +8 -3
  63. package/dist/bridge/terminal-tmux.js +59 -7
  64. package/dist/bridge/transcript-claude.d.ts +12 -2
  65. package/dist/bridge/transcript-claude.js +91 -13
  66. package/dist/bridge/transcript-index.d.ts +4 -2
  67. package/dist/bridge/transcript-index.js +6 -5
  68. package/dist/bridge/transcript-preview.d.ts +16 -1
  69. package/dist/bridge/transcript-preview.js +171 -27
  70. package/dist/bridge/transcripts.d.ts +41 -1
  71. package/dist/bridge/transcripts.js +181 -23
  72. package/dist/bridge/turn-queue-pane.d.ts +6 -0
  73. package/dist/bridge/turn-queue-pane.js +30 -0
  74. package/dist/bridge/turn-queue.d.ts +86 -0
  75. package/dist/bridge/turn-queue.js +280 -0
  76. package/dist/bridge/turn-records.d.ts +18 -0
  77. package/dist/bridge/turn-records.js +77 -5
  78. package/dist/bridge-hook.mjs +7074 -3173
  79. package/dist/cli/config-shared.js +2 -1
  80. package/dist/cli/schedules.js +6 -1
  81. package/dist/content/secrets.js +1 -1
  82. package/dist/modules/registry.js +12 -11
  83. package/package.json +1 -1
@@ -0,0 +1,145 @@
1
+ import { boundSession } from "./agent-hook-stores.js";
2
+ import { isLocalComputer } from "./dispatch-hosts.js";
3
+ import { recentServers, servers, sharedSnapshot } from "./herdr.js";
4
+ import { hookPeers, peerRequest } from "./peers.js";
5
+ import { BridgeError, object, objects, sessionId } from "./protocol.js";
6
+ import { paneRecord, recordTitle } from "./session-activity.js";
7
+ const REFERENCE = /^(?:([A-Za-z0-9_][A-Za-z0-9_.-]{0,252})\/)?([A-Za-z0-9_-]{1,64}:[pt]\d{1,18})$/;
8
+ /** The reference itself, never a URL, path or a longer code-like token. */
9
+ export function parseTerminalReference(value) {
10
+ if (typeof value !== "string" || value.length > 512)
11
+ throw new BridgeError(400, "Invalid terminal reference.");
12
+ const match = REFERENCE.exec(value);
13
+ // `$` also matches before a trailing newline; the whole token must match.
14
+ if (!match || match[0] !== value)
15
+ throw new BridgeError(400, "Invalid terminal reference.");
16
+ return { ...(match[1] ? { computer: match[1] } : {}), id: match[2] };
17
+ }
18
+ const text = (value) => typeof value === "string" && value ? value : undefined;
19
+ /** The conversation Herdr reports for the pane, without probing its processes. */
20
+ function reportedSession(pane) {
21
+ const reported = object(pane.agent_session);
22
+ return reported.kind === "id" && reported.agent === pane.agent && typeof reported.value === "string"
23
+ && sessionId.safeParse(reported.value).success ? reported.value : undefined;
24
+ }
25
+ /** The session's displayed name, by the same rules as the pane rows: a rename
26
+ * wins, then a dispatch label, then the tab or workspace label, then the
27
+ * harness title, with brief-derived launch titles filtered out. */
28
+ async function titleFor(server, snapshot, pane) {
29
+ const tab = objects(snapshot.tabs).find(candidate => candidate.tab_id === pane.tab_id && candidate.workspace_id === pane.workspace_id);
30
+ const workspace = objects(snapshot.workspaces).find(candidate => candidate.workspace_id === pane.workspace_id);
31
+ // The Hook's own binding is terminal/source checked; Herdr's report is the fallback.
32
+ const record = await paneRecord(server, pane, await boundSession(server, pane) ?? reportedSession(pane));
33
+ const title = await recordTitle(record, { paneLabel: pane.label, harnessTitle: pane.title || pane.terminal_title_stripped,
34
+ tabLabel: tab?.label, workspaceLabel: workspace?.label, fallbackLabel: pane.label || pane.pane_id });
35
+ return title ?? String(pane.pane_id);
36
+ }
37
+ async function paneTerminal(computer, server, snapshot, pane) {
38
+ return { computer, server, pane: String(pane.pane_id), tab: String(pane.tab_id ?? ""), workspace: String(pane.workspace_id ?? ""),
39
+ title: await titleFor(server, snapshot, pane), agent: text(pane.agent) ?? null, status: text(pane.agent_status) ?? null };
40
+ }
41
+ async function tabTerminal(computer, server, snapshot, tab) {
42
+ const inside = objects(snapshot.panes).filter(pane => pane.tab_id === tab.tab_id && pane.workspace_id === tab.workspace_id);
43
+ // A tab is the session a phone opens; name its agent's pane when it has one.
44
+ const pane = inside.find(candidate => text(candidate.agent)) ?? inside[0];
45
+ return { computer, server, pane: pane ? String(pane.pane_id) : "", tab: String(tab.tab_id), workspace: String(tab.workspace_id ?? ""),
46
+ title: pane ? await titleFor(server, snapshot, pane) : text(tab.label) ?? String(tab.tab_id),
47
+ agent: text(pane?.agent) ?? null, status: text(tab.agent_status) ?? text(pane?.agent_status) ?? null };
48
+ }
49
+ /** The pane or tab `reference` names in one Hook snapshot. */
50
+ async function fromSnapshot(computer, server, snapshot, reference) {
51
+ const pane = objects(snapshot.panes).find(candidate => candidate.pane_id === reference);
52
+ if (pane)
53
+ return paneTerminal(computer, server, snapshot, pane);
54
+ const tab = objects(snapshot.tabs).find(candidate => candidate.tab_id === reference);
55
+ if (tab)
56
+ return tabTerminal(computer, server, snapshot, tab);
57
+ throw new BridgeError(404, "No terminal matches that reference.", { code: "terminal-not-found" });
58
+ }
59
+ /** Shared snapshots, so a resolve adds no Herdr call of its own when the
60
+ * activity timer or an open overview already holds one. A failed server is
61
+ * kept: it must not read as an absent terminal. */
62
+ async function snapshotsFor(names) {
63
+ return Promise.all(names.map(async (server) => {
64
+ try {
65
+ return { server, snapshot: await sharedSnapshot(server) };
66
+ }
67
+ catch (error) {
68
+ return { server, error };
69
+ }
70
+ }));
71
+ }
72
+ /** The first match, preferring the server the text came from; undefined when
73
+ * no inspected server holds the reference. */
74
+ async function search(held, computer, reference, from) {
75
+ // The pane the text came from is the cheapest hint at its server; workspace
76
+ // ids are only unique within one Herdr server.
77
+ const preferred = from ? held.find(entry => entry.snapshot && objects(entry.snapshot.panes).some(pane => pane.pane_id === from))?.server : undefined;
78
+ const ordered = preferred ? [...held.filter(entry => entry.server === preferred), ...held.filter(entry => entry.server !== preferred)] : held;
79
+ for (const entry of ordered) {
80
+ if (!entry.snapshot)
81
+ continue;
82
+ try {
83
+ return await fromSnapshot(computer, entry.server, entry.snapshot, reference.id);
84
+ }
85
+ catch (error) {
86
+ if (!(error instanceof BridgeError && error.status === 404))
87
+ throw error;
88
+ }
89
+ }
90
+ return undefined;
91
+ }
92
+ async function resolveLocal(computer, reference, from) {
93
+ const held = await snapshotsFor((await recentServers()).map(server => String(server.session)).slice(0, 64));
94
+ const originKnown = !from || held.some(entry => entry.snapshot && objects(entry.snapshot.panes).some(pane => pane.pane_id === from));
95
+ const found = await search(held, computer, reference, from);
96
+ if (found && originKnown)
97
+ return found;
98
+ // Discovery is shared with background work and can lag a newly started
99
+ // server. A miss, or an origin pane the cached servers do not hold, refreshes
100
+ // it once so a duplicate id is not matched on the wrong server; snapshots
101
+ // stay shared.
102
+ const known = new Set(held.map(entry => entry.server));
103
+ const added = (await servers()).map(server => String(server.session)).filter(server => !known.has(server)).slice(0, 64);
104
+ if (added.length) {
105
+ const extra = [...held, ...await snapshotsFor(added)];
106
+ const foundAfterRefresh = await search(extra, computer, reference, from);
107
+ if (foundAfterRefresh)
108
+ return foundAfterRefresh;
109
+ const failed = extra.find(entry => entry.error);
110
+ if (failed)
111
+ throw failed.error;
112
+ }
113
+ else if (found) {
114
+ return found;
115
+ }
116
+ else {
117
+ const failed = held.find(entry => entry.error);
118
+ if (failed)
119
+ throw failed.error;
120
+ }
121
+ throw new BridgeError(404, "No terminal matches that reference.", { code: "terminal-not-found" });
122
+ }
123
+ const sameName = (left, right) => left.trim().toLowerCase() === right.trim().toLowerCase();
124
+ function peerNamed(peers, name) {
125
+ return peers.find(peer => sameName(peer.name, name));
126
+ }
127
+ /** The terminal a chat reference names, on this computer or a verified peer. */
128
+ export async function resolveTerminalReference(value, options) {
129
+ const reference = parseTerminalReference(value);
130
+ const own = [options.computer.name, ...(options.computer.aliases ?? [])];
131
+ if (!reference.computer || isLocalComputer(reference.computer, own))
132
+ return resolveLocal(options.computer.name, reference, options.from);
133
+ const peers = await hookPeers().catch(error => {
134
+ // No hooks.yaml means no peers; any other failure is the owner's to fix.
135
+ if (error instanceof BridgeError && error.details?.hooksYaml === "missing")
136
+ return [];
137
+ throw error;
138
+ });
139
+ const peer = peerNamed(peers, reference.computer);
140
+ if (!peer)
141
+ throw new BridgeError(404, "No linked computer answers to that name.", { code: "terminal-not-found" });
142
+ // The remote Hook resolves its own bare ref; this machine's `from` pane is
143
+ // meaningless there.
144
+ return object(await peerRequest(peer, `/v1/terminals/resolve?${new URLSearchParams({ ref: reference.id })}`));
145
+ }
@@ -27,8 +27,9 @@ interface TmuxDeps {
27
27
  processes: () => Promise<string>;
28
28
  /** `tmux -V`. */
29
29
  version: () => Promise<string>;
30
- /** The names of the tmux sockets this user has, whether or not they answer. */
31
- sockets: () => Promise<string[]>;
30
+ /** The names of the tmux sockets this user has, whether or not they answer.
31
+ * In strict mode a discovery failure other than a missing folder is thrown. */
32
+ sockets: (strict?: boolean) => Promise<string[]>;
32
33
  sleep: (ms: number, signal?: AbortSignal) => Promise<void>;
33
34
  }
34
35
  /** The tmux on PATH or in the usual install folders; the Hook's service
@@ -42,7 +43,7 @@ export declare function tmuxSocketFolders(env?: NodeJS.ProcessEnv): string[];
42
43
  * first, so a live server sorts ahead of stale socket files left by killed
43
44
  * runs. A socket outside the first folder of `tmuxSocketFolders` is remembered
44
45
  * by path. */
45
- export declare function tmuxSocketsIn(folder: string): Promise<string[]>;
46
+ export declare function tmuxSocketsIn(folder: string, strict?: boolean): Promise<string[]>;
46
47
  /** For tests: replace how tmux and ps run; the returned function restores them. */
47
48
  export declare function setTmuxDeps(replacement: Partial<TmuxDeps>): () => void;
48
49
  declare const SIGILS: {
@@ -81,6 +82,10 @@ export declare const tmuxTerminal: TerminalProvider;
81
82
  export declare function tmuxServers(options?: {
82
83
  hidden?: boolean;
83
84
  }): Promise<Json[]>;
85
+ /** The tmux servers that are actually running, for a safety check. Unlike
86
+ * `tmuxServers`, a timeout, permission or discovery failure fails the call
87
+ * instead of quietly dropping that server; a stopped one is simply absent. */
88
+ export declare function tmuxServersStrict(): Promise<Json[]>;
84
89
  /** What `phren bridge doctor` and the health details say about tmux. */
85
90
  export interface TmuxHealth {
86
91
  /** "off" when PHREN_TMUX=off, "missing" without a tmux executable. */
@@ -76,8 +76,10 @@ function tmuxError(stderr, error) {
76
76
  return new BridgeError(504, "tmux did not answer. Refresh before trying again.");
77
77
  if (error.code === "ENOENT")
78
78
  return new BridgeError(503, "tmux is not installed on this computer.");
79
- if (/no server running|error connecting to|No such file or directory/i.test(said))
79
+ if (/no server running/i.test(said)
80
+ || /error connecting to .*\((?:no such file or directory|connection refused)\)/i.test(said)) {
80
81
  return new BridgeError(503, "tmux is not running on this computer.", { code: "not_running" });
82
+ }
81
83
  return new BridgeError(409, said ? `tmux: ${said}` : "tmux could not perform this action. Refresh the session before trying again.");
82
84
  }
83
85
  /** The folders this user's tmux sockets live in: `$TMUX_TMPDIR/tmux-<uid>`,
@@ -100,14 +102,28 @@ function socketFlags(socket) {
100
102
  * first, so a live server sorts ahead of stale socket files left by killed
101
103
  * runs. A socket outside the first folder of `tmuxSocketFolders` is remembered
102
104
  * by path. */
103
- export async function tmuxSocketsIn(folder) {
105
+ export async function tmuxSocketsIn(folder, strict = false) {
104
106
  const uid = process.getuid?.(), primary = tmuxSocketFolders()[0];
105
- const names = (await readdir(folder).catch(() => [])).slice(0, 256);
107
+ let names;
108
+ try {
109
+ names = await readdir(folder);
110
+ }
111
+ catch (error) {
112
+ if (!strict || error.code === "ENOENT")
113
+ return [];
114
+ throw new BridgeError(503, "Could not list this computer's tmux servers.", { code: "tmux-discovery-failed" });
115
+ }
116
+ if (!strict)
117
+ names = names.slice(0, 256);
106
118
  const found = [];
107
119
  for (const name of names) {
108
120
  if (!tmuxServerName(name))
109
121
  continue;
110
- const info = await lstat(path.join(folder, name)).catch(() => undefined);
122
+ const info = await lstat(path.join(folder, name)).catch(error => {
123
+ if (!strict || error.code === "ENOENT")
124
+ return undefined;
125
+ throw new BridgeError(503, "Could not inspect this computer's tmux servers.", { code: "tmux-discovery-failed" });
126
+ });
111
127
  if (!info?.isSocket() || (uid !== undefined && info.uid !== uid))
112
128
  continue;
113
129
  found.push({ name, at: info.mtimeMs });
@@ -116,8 +132,9 @@ export async function tmuxSocketsIn(folder) {
116
132
  }
117
133
  found.sort((a, b) => b.at - a.at);
118
134
  // 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);
135
+ // per snapshot, and stale files from killed runs sort to the end. A removal
136
+ // check reads every candidate: a hidden live server must never be skipped.
137
+ return (strict ? found : found.slice(0, 32)).map(entry => entry.name);
121
138
  }
122
139
  const defaultDeps = {
123
140
  binary: tmuxBinary,
@@ -149,7 +166,7 @@ const defaultDeps = {
149
166
  }
150
167
  execFile(binary, ["-V"], { timeout: 3_000 }, (error, stdout) => resolve(error ? "" : String(stdout)));
151
168
  }),
152
- sockets: async () => (await Promise.all(tmuxSocketFolders().map(tmuxSocketsIn))).flat(),
169
+ sockets: async (strict = false) => (await Promise.all(tmuxSocketFolders().map(folder => tmuxSocketsIn(folder, strict)))).flat(),
153
170
  sleep: (ms, signal) => new Promise((resolve, reject) => {
154
171
  if (signal?.aborted) {
155
172
  reject(new BridgeError(499, "Request cancelled."));
@@ -554,6 +571,41 @@ export async function tmuxServers(options = {}) {
554
571
  return [...await ownerServers(), ...(hiddenRunning ? [TMUX_HIDDEN] : [])]
555
572
  .map(name => ({ id: `tmux:${name}`, kind: "tmux", terminal: "tmux", session: name, running: true }));
556
573
  }
574
+ function tmuxServerStopped(error) {
575
+ return error instanceof BridgeError && (error.details?.code === "not_running" || /is not running/.test(error.message));
576
+ }
577
+ /** The tmux servers that are actually running, for a safety check. Unlike
578
+ * `tmuxServers`, a timeout, permission or discovery failure fails the call
579
+ * instead of quietly dropping that server; a stopped one is simply absent. */
580
+ export async function tmuxServersStrict() {
581
+ if (!deps.binary())
582
+ return [];
583
+ const sockets = [...new Set(["default", ...await deps.sockets(true)])]
584
+ .filter(socket => socket !== "phren" && !isTestName(socket));
585
+ const names = sockets.flatMap(socket => tmuxServerName(socket) ?? []);
586
+ const running = await Promise.all(names.map(async (name) => {
587
+ try {
588
+ const text = await tmux(name, ["list-sessions", "-F", "#{session_path}"], { timeoutMs: 3_000 });
589
+ return !isTestServer(text.split("\n").filter(Boolean));
590
+ }
591
+ catch (error) {
592
+ if (tmuxServerStopped(error))
593
+ return false;
594
+ throw error;
595
+ }
596
+ }));
597
+ const found = names.filter((_, index) => running[index]);
598
+ try {
599
+ await tmux(TMUX_HIDDEN, ["list-sessions", "-F", "#{session_id}"], { timeoutMs: 3_000 });
600
+ if (!found.includes(TMUX_HIDDEN))
601
+ found.push(TMUX_HIDDEN);
602
+ }
603
+ catch (error) {
604
+ if (!tmuxServerStopped(error))
605
+ throw error;
606
+ }
607
+ return found.map(name => ({ id: `tmux:${name}`, kind: "tmux", terminal: "tmux", session: name, running: true }));
608
+ }
557
609
  export async function tmuxHealth() {
558
610
  if (process.env.PHREN_TMUX === "off")
559
611
  return { state: "off" };
@@ -16,11 +16,17 @@ export declare function claudeChildAgents(file: string, session: string): Promis
16
16
  export declare const CLAUDE_SKILL_QUIET_MS: number;
17
17
  /** State one newest-first pass over a Claude transcript keeps so a
18
18
  * content-free `dequeue` can name the prompt turn it delivered: the queue key
19
- * of that turn and whether the agent's own schedule (a cron, /loop or
20
- * ScheduleWakeup fire, or an auto-continuation) injected it. */
19
+ * of that turn, whether the agent's own schedule (a cron, /loop or
20
+ * ScheduleWakeup fire, or an auto-continuation) injected it, and the phone
21
+ * delivery the Hook's records bound to that turn. `offset` is the raw row's
22
+ * byte offset, so a queue occurrence can be named exactly (`deliveryFor`). */
21
23
  export interface ClaudeQueueState {
22
24
  key?: string;
23
25
  scheduled?: boolean;
26
+ delivery?: string;
27
+ offset?: number;
28
+ /** The phone delivery a queue row was bound to, from the Hook's delivery records. */
29
+ deliveryFor?: (raw: Json, offset: number | undefined) => string | undefined;
24
30
  }
25
31
  export declare const harnessPreamble: (text: string) => boolean;
26
32
  export declare function unwrapPastedContent(text: string): string;
@@ -37,6 +43,10 @@ export declare function skillBody(raw: Json): Json | undefined;
37
43
  /** A phren UserPromptSubmit injection, as `{ type: "phren_hook_context",
38
44
  * parentUuid, content }`, or undefined for any other row. */
39
45
  export declare function phrenHookContext(raw: Json, includeSidechain?: boolean): Json | undefined;
46
+ /** The normalized prompt identity of a displayed Claude user prompt. Tool
47
+ * results, hidden/meta or scheduled turns, sidechains, compaction summaries,
48
+ * queue placeholders and synthetic rows never carry one. */
49
+ export declare function claudePromptIdentity(original: Json, projected: Json | undefined): string | undefined;
40
50
  /** Claude Code rows the phone may see: user, assistant and system turns with
41
51
  * private reasoning redacted, queued phone messages, background task
42
52
  * notifications and compaction markers. */
@@ -3,7 +3,9 @@ import { createReadStream } from "node:fs";
3
3
  import { createInterface } from "node:readline";
4
4
  import { createHash } from "node:crypto";
5
5
  import path from "node:path";
6
+ import { classifyClaudeInput } from "./input-classification.js";
6
7
  import { object, objects } from "./protocol.js";
8
+ import { claudePromptEntryId } from "./prompt-identity.js";
7
9
  import { latestStopTasks } from "./turn-records.js";
8
10
  const claudeRelationCache = new Map();
9
11
  const copyRows = (rows) => ({ launches: new Map([...rows.launches].map(([id, launch]) => [id, { ...launch }])),
@@ -530,7 +532,7 @@ async function claudeChildBelongsTo(file, parent, agentId) {
530
532
  // `effort` rides on each assistant row (Claude Code 2.1): with `message.model`
531
533
  // it is what the phone's model chip shows as in effect. `permissionMode` on a
532
534
  // user row is the mode that turn ran in (the phone's permission chip).
533
- const CLAUDE_KEYS = new Set(["type", "uuid", "parentUuid", "timestamp", "message", "gitBranch", "cwd", "requestId", "isMeta", "isSidechain", "isCompactSummary", "phrenQueued", "phrenQueueKey", "phrenBackground", "phrenCompacted", "effort", "permissionMode"]);
535
+ const CLAUDE_KEYS = new Set(["type", "uuid", "parentUuid", "timestamp", "message", "gitBranch", "cwd", "requestId", "isMeta", "isSidechain", "isCompactSummary", "phrenQueued", "phrenQueueKey", "phrenBackground", "phrenExecution", "phrenCompacted", "effort", "permissionMode"]);
534
536
  /** The `phrenQueueKey` of the prompt turn a queued message was delivered as:
535
537
  * the same SHA-256 of the unwrapped content the enqueue row exports. Undefined
536
538
  * for a tool result, a harness envelope, or a turn that is not the person's. */
@@ -649,6 +651,26 @@ export function phrenHookContext(raw, includeSidechain = false) {
649
651
  return { type: "phren_hook_context", timestamp: raw.timestamp, uuid: raw.uuid, parentUuid: raw.parentUuid,
650
652
  content: content.length > HOOK_CONTEXT_LIMIT ? content.slice(0, HOOK_CONTEXT_LIMIT) + "\n…" : content };
651
653
  }
654
+ /** The normalized prompt identity of a displayed Claude user prompt. Tool
655
+ * results, hidden/meta or scheduled turns, sidechains, compaction summaries,
656
+ * queue placeholders and synthetic rows never carry one. */
657
+ export function claudePromptIdentity(original, projected) {
658
+ if (original.type !== "user" || original.isSidechain === true || original.isMeta === true
659
+ || original.isCompactSummary === true || original.isSynthetic === true
660
+ || original.isApiErrorMessage === true || original.isVisibleInTranscriptOnly === true)
661
+ return undefined;
662
+ if (original.toolUseResult !== undefined)
663
+ return undefined;
664
+ const message = object(original.message);
665
+ if (message.role !== undefined && message.role !== "user")
666
+ return undefined;
667
+ if (objects(message.content).some(block => block.type === "tool_result"))
668
+ return undefined;
669
+ if (!projected || projected.type !== "user" || projected.isCompactSummary === true || projected.isMeta === true
670
+ || projected.isSidechain === true || projected.phrenQueued === true)
671
+ return undefined;
672
+ return claudePromptEntryId(original.promptId);
673
+ }
652
674
  /** Claude Code rows the phone may see: user, assistant and system turns with
653
675
  * private reasoning redacted, queued phone messages, background task
654
676
  * notifications and compaction markers. */
@@ -668,22 +690,37 @@ export function visibleClaudeEvent(raw, includeSidechain = false, queue) {
668
690
  // own schedule fired it.
669
691
  if (raw.type === "queue-operation" && raw.operation === "dequeue") {
670
692
  const key = queue?.key, scheduled = queue?.scheduled;
693
+ // The Hook's binding names the phone message this occurrence delivered, even
694
+ // though the row itself is content-free.
695
+ // When occurrence bindings are available they are authoritative. A nearby
696
+ // user turn must not lend its verified identity to an unowned queue head.
697
+ const delivery = queue?.deliveryFor?.(raw, queue.offset);
671
698
  // One prompt turn answers one dequeue: an older dequeue must not reuse
672
699
  // this key and mark a different queued message consumed.
673
700
  if (queue) {
674
701
  queue.key = undefined;
675
702
  queue.scheduled = undefined;
703
+ queue.delivery = undefined;
676
704
  }
677
- return { type: "phren_queue_consumed", ...(key ? { key } : {}), ...(key && scheduled ? { scheduled: true } : {}), timestamp: raw.timestamp };
705
+ return { type: "phren_queue_consumed", ...(key ? { key } : {}), ...(key && scheduled ? { scheduled: true } : {}),
706
+ ...(delivery ? { phrenDeliveryId: delivery } : {}), timestamp: raw.timestamp };
678
707
  }
679
708
  // popAll pulls queued prompts back into the input: they were neither
680
709
  // consumed nor scheduled, so the phone must not draw the leftovers as a
681
710
  // "Scheduled check" after the next reply.
682
711
  if (raw.type === "queue-operation" && raw.operation === "popAll" && typeof raw.content === "string") {
683
- return { type: "phren_queue_returned", key: createHash("sha256").update(raw.content).digest("hex"), timestamp: raw.timestamp };
712
+ const delivery = queue?.deliveryFor?.(raw, queue.offset);
713
+ return { type: "phren_queue_returned", key: createHash("sha256").update(raw.content).digest("hex"),
714
+ ...(delivery ? { phrenDeliveryId: delivery } : {}), timestamp: raw.timestamp };
684
715
  }
685
716
  if (raw.type === "queue-operation" && raw.operation === "remove" && typeof raw.content === "string") {
686
- return { type: "phren_queue_consumed", key: createHash("sha256").update(raw.content).digest("hex"), timestamp: raw.timestamp };
717
+ const delivery = queue?.deliveryFor?.(raw, queue.offset), key = createHash("sha256").update(raw.content).digest("hex");
718
+ // Only a removal the running turn took is consumption. A cancellation drops the input
719
+ // without the agent seeing it, so the phone keeps the message as withdrawn, not sent.
720
+ const taken = raw.reason === "absorbed_mid_turn" || raw.reason === "delivered_to_agent";
721
+ return taken
722
+ ? { type: "phren_queue_consumed", key, ...(delivery ? { phrenDeliveryId: delivery } : {}), timestamp: raw.timestamp }
723
+ : { type: "phren_queue_returned", key, ...(delivery ? { phrenDeliveryId: delivery } : {}), timestamp: raw.timestamp };
687
724
  }
688
725
  // Claude Code records background completion as an internal queue row,
689
726
  // outside the ordinary user/assistant transcript. Export only the small
@@ -699,7 +736,7 @@ export function visibleClaudeEvent(raw, includeSidechain = false, queue) {
699
736
  // Claude Code hands it to the model inside a later tool result and never
700
737
  // writes a user turn for it. Export the enqueue as the person's message so
701
738
  // the phone can draw the bubble it sent. Consumption exposes only a digest.
702
- if (raw.type === "queue-operation" && ["enqueue", "remove"].includes(String(raw.operation))
739
+ if (raw.type === "queue-operation" && raw.operation === "enqueue"
703
740
  && !raw.isMeta && !raw.isSidechain && typeof raw.content === "string"
704
741
  && raw.content.length <= 65_536 && !raw.content.includes("<task-notification>")) {
705
742
  // The paste wrapper was removed above; any envelope still starting
@@ -708,16 +745,15 @@ export function visibleClaudeEvent(raw, includeSidechain = false, queue) {
708
745
  return undefined;
709
746
  const text = raw.content;
710
747
  const key = createHash("sha256").update(raw.content).digest("hex");
711
- // Only the identity crosses the wire on consumption: no queue payload,
712
- // tool envelope, private metadata, or reasoning is exported.
713
- if (raw.operation === "remove")
714
- return { type: "phren_queue_consumed", key, timestamp: raw.timestamp };
715
748
  // A picture sent mid-turn queues as "[Image #7]Attached files on this
716
749
  // computer:": the pixels never reach this row. Words-free, it matched no
717
750
  // receipt, and the phone warned "Not confirmed in chat" about a picture
718
751
  // the agent had taken. Name it the way a picture-only turn reads.
719
752
  const pictureOnly = QUEUED_IMAGE_LABEL.test(text) && !text.replace(QUEUED_IMAGE_LABELS, "").replace(ATTACHED_FILES_FOOTER, "").trim();
720
- return { type: "user", phrenQueued: true, phrenQueueKey: key, timestamp: raw.timestamp,
753
+ // The phone id comes from the Hook's own delivery record, never from the
754
+ // row's Claude `deliveryId`/`commandUuid`, which are the harness's.
755
+ const delivery = queue?.deliveryFor?.(raw, queue.offset);
756
+ return { type: "user", phrenQueued: true, phrenQueueKey: key, ...(delivery ? { phrenDeliveryId: delivery } : {}), timestamp: raw.timestamp,
721
757
  message: { role: "user", content: pictureOnly ? "[Image attachment]" : text } };
722
758
  }
723
759
  // Claude Code appends a boundary marker and then the summary it hands the
@@ -745,18 +781,59 @@ export function visibleClaudeEvent(raw, includeSidechain = false, queue) {
745
781
  return { type: "permission-mode", permissionMode: raw.permissionMode, ...(typeof raw.timestamp === "string" ? { timestamp: raw.timestamp } : {}) };
746
782
  }
747
783
  // Remember the prompt turn a queued message was delivered as, so the
748
- // content-free dequeue written before it can be keyed and flagged scheduled.
784
+ // content-free dequeue written before it can be keyed and flagged scheduled,
785
+ // and the phone id the Hook's records bound to that occurrence, so a real
786
+ // submitted turn replaces the queued row with the same identity.
749
787
  if (queue && raw.type === "user") {
788
+ queue.delivery = undefined;
750
789
  const key = queuePromptKey(raw);
751
790
  if (key !== undefined) {
752
791
  queue.key = key;
753
792
  queue.scheduled = scheduledPromptTurn(raw);
793
+ queue.delivery = queue.deliveryFor?.(raw, queue.offset);
794
+ }
795
+ }
796
+ // A background task's completion reaches Claude Code as a user row whose
797
+ // origin says "task-notification" (sometimes wrapped in a system reminder).
798
+ // It is a notice, not a prompt: normalize only its public envelope and never
799
+ // let established notification provenance fall through as ordinary user text.
800
+ if (raw.type === "user") {
801
+ const content = object(raw.message).content;
802
+ const text = typeof content === "string" ? content
803
+ : objects(content).filter(block => block.type === "text" && typeof block.text === "string").map(block => String(block.text)).join("\n");
804
+ const input = classifyClaudeInput({ text, hasImage: objects(content).some(block => block.type === "image"), origin: raw.origin, commandMode: raw.commandMode,
805
+ isMeta: raw.isMeta, isSidechain: raw.isSidechain && !includeSidechain, isCompactSummary: raw.isCompactSummary,
806
+ toolResult: objects(content).some(block => block.type === "tool_result") });
807
+ if (input.category === "internal" && !objects(content).some(block => block.type === "tool_result"))
808
+ return undefined;
809
+ if (input.category === "notification") {
810
+ if (raw.isSidechain && !includeSidechain)
811
+ return undefined;
812
+ const trimmed = text.trimStart();
813
+ const envelope = trimmed.startsWith("<task-notification>")
814
+ || (trimmed.startsWith("<system-reminder>") && trimmed.includes("<task-notification>"));
815
+ // A system-origin notification that is not a public task envelope stays private.
816
+ if (text.length > 65_536 || !envelope)
817
+ return undefined;
818
+ const notice = taskNotification(text);
819
+ return notice ? { type: "system", phrenBackground: true, timestamp: raw.timestamp,
820
+ ...(typeof raw.uuid === "string" ? { uuid: raw.uuid } : {}),
821
+ ...(typeof raw.parentUuid === "string" ? { parentUuid: raw.parentUuid } : {}),
822
+ message: { role: "user", content: notice } } : undefined;
754
823
  }
755
824
  }
756
825
  if (raw.isMeta || (raw.isSidechain && !includeSidechain) || !["user", "assistant", "system"].includes(String(raw.type)))
757
826
  return undefined;
827
+ if (raw.type === "assistant" || (raw.type === "system" && raw.subtype === "turn_duration")) {
828
+ // Publish only the execution category, never raw origin metadata. A
829
+ // background end_turn is not the foreground execution's boundary.
830
+ const execution = classifyClaudeInput({ text: "execution", origin: raw.origin, isSidechain: raw.isSidechain && !includeSidechain });
831
+ if (execution.category !== "owner")
832
+ raw = { ...raw, phrenExecution: "background" };
833
+ }
758
834
  raw = Object.fromEntries(Object.entries(raw).filter(([key]) => CLAUDE_KEYS.has(key)));
759
835
  const message = unwrapUserText(object(raw.message));
836
+ const delivery = raw.type === "user" ? queue?.delivery : undefined;
760
837
  // Keep indexes for historical images while removing thinking contents.
761
838
  // The one exception is narration: short progress notes the model writes
762
839
  // for the person watching (the lines Claude Code's terminal shows between
@@ -764,9 +841,10 @@ export function visibleClaudeEvent(raw, includeSidechain = false, queue) {
764
841
  // them narration and whose text is present; private reasoning is stored
765
842
  // with empty text and a "thinking" signature and stays redacted.
766
843
  if (typeof message.content === "string")
767
- return raw.type === "user" && harnessPreamble(message.content) ? undefined : { ...raw, message };
844
+ return raw.type === "user" && harnessPreamble(message.content) ? undefined
845
+ : { ...raw, ...(delivery ? { phrenDeliveryId: delivery } : {}), message };
768
846
  if (Array.isArray(message.content))
769
- return { ...raw, message: { ...message, content: objects(message.content).map(b => ["text", "image", "tool_use", "tool_result"].includes(String(b.type)) ? b
847
+ return { ...raw, ...(delivery ? { phrenDeliveryId: delivery } : {}), message: { ...message, content: objects(message.content).map(b => ["text", "image", "tool_use", "tool_result"].includes(String(b.type)) ? b
770
848
  : isNarration(b) ? { type: "text", text: String(b.thinking), narration: true } : { type: "redacted" }) } };
771
849
  return undefined;
772
850
  }
@@ -17,9 +17,11 @@ declare class TranscriptIndex {
17
17
  private refresh;
18
18
  private position;
19
19
  /** Read newest first and stop as soon as the caller has a page. Large rows
20
- * are skipped with bounded memory while keeping absolute line identities. */
21
- rows(handle: FileHandle, before: number, after: number, signal?: AbortSignal): AsyncGenerator<{
20
+ * are skipped with bounded memory while keeping absolute line and byte
21
+ * identities. */
22
+ rows(handle: FileHandle, before: number, after: number, signal?: AbortSignal, maxRowBytes?: number): AsyncGenerator<{
22
23
  line: number;
24
+ offset: number;
23
25
  bytes?: Buffer;
24
26
  }>;
25
27
  }
@@ -92,8 +92,9 @@ class TranscriptIndex {
92
92
  return offset;
93
93
  }
94
94
  /** Read newest first and stop as soon as the caller has a page. Large rows
95
- * are skipped with bounded memory while keeping absolute line identities. */
96
- async *rows(handle, before, after, signal) {
95
+ * are skipped with bounded memory while keeping absolute line and byte
96
+ * identities. */
97
+ async *rows(handle, before, after, signal, maxRowBytes = MAX_ROW_BYTES) {
97
98
  const endLine = Math.min(before, this.lines);
98
99
  if (endLine <= after)
99
100
  return;
@@ -112,13 +113,13 @@ class TranscriptIndex {
112
113
  while (end > 0) {
113
114
  const newline = buffer.lastIndexOf(10, end - 1), begin = newline + 1;
114
115
  size += end - begin;
115
- if (size <= MAX_ROW_BYTES)
116
+ if (size <= maxRowBytes)
116
117
  parts.push(Buffer.from(buffer.subarray(begin, end)));
117
118
  else
118
119
  parts = [];
119
120
  if (newline < 0)
120
121
  break;
121
- yield { line: line--, bytes: size <= MAX_ROW_BYTES ? Buffer.concat(parts.reverse(), size) : undefined };
122
+ yield { line: line--, offset: start + begin, bytes: size <= maxRowBytes ? Buffer.concat(parts.reverse(), size) : undefined };
122
123
  parts = [];
123
124
  size = 0;
124
125
  end = newline;
@@ -126,7 +127,7 @@ class TranscriptIndex {
126
127
  cursor = start;
127
128
  }
128
129
  if (line >= after)
129
- yield { line, bytes: size <= MAX_ROW_BYTES ? Buffer.concat(parts.reverse(), size) : undefined };
130
+ yield { line, offset: lower, bytes: size <= maxRowBytes ? Buffer.concat(parts.reverse(), size) : undefined };
130
131
  }
131
132
  }
132
133
  // No on-disk transcript copies. Eviction affects speed only; an evicted reader
@@ -94,6 +94,8 @@ export declare class TranscriptPreviewStream {
94
94
  * showing a landed block until a newer one is drawn, so only a block not among these is previewed. */
95
95
  private readonly landedTexts;
96
96
  private ended;
97
+ private lifecycleEnded;
98
+ private retirementComplete;
97
99
  /** Claude's own spinner word for the running turn, sent beside frames as
98
100
  * `activityVerb` for older phones. */
99
101
  verb: string | undefined;
@@ -104,6 +106,7 @@ export declare class TranscriptPreviewStream {
104
106
  private lastRead;
105
107
  private lastSent;
106
108
  private current;
109
+ private clearPending;
107
110
  private observedLine;
108
111
  private wasWorking;
109
112
  /** Replies that already landed as entries: a sidecar or thread a tick
@@ -115,7 +118,19 @@ export declare class TranscriptPreviewStream {
115
118
  /** Whether pane text is a reply block that already landed: its words agree with the block's as far as
116
119
  * both go (drawsLanded), so a block still drawing the same opening as a landed one waits until the two part. */
117
120
  private hasLanded;
118
- update(status: unknown, file?: string, now?: number): Promise<{
121
+ /** Seed a reconnect from a classified owner row in the verified transcript. */
122
+ seedTurn(turnStartedAt: string, prompt: string): void;
123
+ /**
124
+ * Accept a pane candidate monotonically. Within one block, only a growing
125
+ * extension (or a verified overlap) is taken; a shorter or unrelated screen
126
+ * cannot replace the accepted block. A later block is accepted only once the
127
+ * previous one landed (which clears `current` first) or the caller observed a
128
+ * structural boundary.
129
+ */
130
+ private acceptClaudeCandidate;
131
+ update(status: unknown, file?: string, now?: number, lifecycle?: {
132
+ ended?: boolean;
133
+ }): Promise<{
119
134
  preview: TranscriptPreview | null;
120
135
  } | undefined>;
121
136
  }