@phren/cli 0.2.12 → 0.2.14

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.
@@ -78,7 +78,16 @@ export async function servers() {
78
78
  }
79
79
  export async function snapshot(server) { return object((await rpc(server, "session.snapshot")).snapshot); }
80
80
  export function workspaceSnapshot(s) {
81
- return { kind: "herdr", groups: objects(s.workspaces).map(w => ({ id: w.workspace_id, label: w.label,
81
+ const focusedPane = objects(s.panes).find(p => p.pane_id === s.focused_pane_id
82
+ && p.tab_id === s.focused_tab_id && p.workspace_id === s.focused_workspace_id);
83
+ const focus = focusedPane && id.safeParse(s.focused_workspace_id).success
84
+ && id.safeParse(s.focused_tab_id).success && id.safeParse(s.focused_pane_id).success
85
+ && objects(s.tabs).some(t => t.tab_id === s.focused_tab_id && t.workspace_id === s.focused_workspace_id)
86
+ && objects(s.workspaces).some(w => w.workspace_id === s.focused_workspace_id)
87
+ ? { workspaceID: s.focused_workspace_id, tabID: s.focused_tab_id, paneID: s.focused_pane_id } : undefined;
88
+ // Focus identifies a pane to inspect. Its conversation is still resolved and
89
+ // validated independently through panes(), never inferred from a directory.
90
+ return { kind: "herdr", focus, groups: objects(s.workspaces).map(w => ({ id: w.workspace_id, label: w.label,
82
91
  children: objects(s.tabs).filter(t => t.workspace_id === w.workspace_id).map(t => {
83
92
  const panes = objects(s.panes).filter(p => p.tab_id === t.tab_id);
84
93
  const agent = panes.find(p => p.agent);
@@ -108,6 +108,18 @@ export async function serve(version) {
108
108
  response.end(bytes);
109
109
  return;
110
110
  }
111
+ case "/v1/transcripts/history": {
112
+ const target = targetFromURL(url);
113
+ const before = z.coerce.number().int().positive().parse(url.searchParams.get("beforeLine"));
114
+ const abort = new AbortController();
115
+ response.once("close", () => { if (!response.writableEnded)
116
+ abort.abort(); });
117
+ await validateTarget(target);
118
+ const reader = new TranscriptReader(await transcriptPath(target.source, target.session), target.source);
119
+ const page = await reader.read(before, abort.signal);
120
+ result = { ...page, type: "older", source: target.source, session: target.session };
121
+ break;
122
+ }
111
123
  default: throw new BridgeError(404, "Unknown Phren Hook route.");
112
124
  }
113
125
  }
@@ -183,60 +195,87 @@ export async function serve(version) {
183
195
  });
184
196
  async function stream(client, url) {
185
197
  const target = targetFromURL(url);
186
- await validateTarget(target);
187
- if (client.readyState !== WebSocket.OPEN)
188
- return;
189
- const unwatch = agentHooks.watch(target);
190
- client.once("close", unwatch);
191
- const reader = url.pathname === "/v1/transcripts" ? new TranscriptReader(await transcriptPath(target.source, target.session), target.source) : undefined;
192
- let busy = false, closed = false, first = true;
193
- client.on("close", () => { closed = true; clearInterval(timer); });
194
- client.on("error", () => { closed = true; clearInterval(timer); });
198
+ const abort = new AbortController();
199
+ let reader, timer;
200
+ let unwatch;
201
+ let busy = false, ready = false, first = true;
202
+ let initialPane;
203
+ const pending = [];
204
+ const stop = () => { abort.abort(); clearInterval(timer); unwatch?.(); pending.length = 0; };
205
+ client.once("close", stop);
206
+ client.once("error", stop);
195
207
  const tick = async () => {
196
- if (busy || closed)
208
+ if (busy || !ready || abort.signal.aborted)
197
209
  return;
198
210
  busy = true;
199
211
  try {
200
- const pane = await validateTarget(target);
201
- if (reader) {
202
- const page = await reader.read();
203
- if (first || page.entries.length || page.reset)
204
- send(client, { type: first || page.reset ? "backlog" : "append", source: target.source,
205
- session: target.session, entries: page.entries, totalLines: page.totalLines, hasMore: page.hasMore });
212
+ if (first || pending.length === 0) {
213
+ const pane = first ? initialPane : await validateTarget(target);
214
+ if (reader) {
215
+ const page = await reader.read(undefined, abort.signal);
216
+ if (first || page.entries.length || page.reset)
217
+ send(client, { ...page, type: first || page.reset ? "backlog" : "append", source: target.source,
218
+ session: target.session });
219
+ }
220
+ else {
221
+ const pendingApproval = agentHooks.approval(target);
222
+ send(client, { agentStatus: { source: target.source, session: target.session,
223
+ status: pendingApproval ? "waiting" : pane.agent_status, pendingApproval, capabilities } });
224
+ }
225
+ first = false;
206
226
  }
207
- else {
208
- const pendingApproval = agentHooks.approval(target);
209
- send(client, { agentStatus: { source: target.source, session: target.session,
210
- status: pendingApproval ? "waiting" : pane.agent_status, pendingApproval, capabilities } });
227
+ while (pending.length && reader && !abort.signal.aborted) {
228
+ const before = pending.shift();
229
+ await validateTarget(target);
230
+ const page = await reader.read(before, abort.signal);
231
+ send(client, { ...page, type: "older", source: target.source, session: target.session });
211
232
  }
212
- first = false;
213
233
  }
214
234
  catch {
235
+ stop();
215
236
  client.close(1011, "The conversation changed; refresh");
216
237
  }
217
238
  finally {
218
239
  busy = false;
240
+ if (pending.length)
241
+ void tick();
219
242
  }
220
243
  };
221
- const timer = setInterval(() => { void tick(); }, reader ? 500 : 1500);
222
244
  client.on("message", bytes => {
223
- void (async () => {
245
+ try {
224
246
  const message = object(JSON.parse(bytes.toString()));
225
- if (message.type !== "older" || !reader || busy)
247
+ if (message.type !== "older" || url.pathname !== "/v1/transcripts" || abort.signal.aborted)
226
248
  return;
227
- busy = true;
228
- try {
229
- await validateTarget(target);
230
- const before = z.number().int().positive().parse(message.beforeLine);
231
- const page = await new TranscriptReader(reader.file, target.source).read(before);
232
- send(client, { type: "older", source: target.source, entries: page.entries, hasMore: page.hasMore, totalLines: page.totalLines });
233
- }
234
- finally {
235
- busy = false;
236
- }
237
- })().catch(() => client.close(1008, "Invalid history request"));
249
+ const before = z.number().int().positive().parse(message.beforeLine);
250
+ if (pending.length >= 8)
251
+ throw new Error("History queue is full");
252
+ if (!pending.includes(before))
253
+ pending.push(before);
254
+ void tick();
255
+ }
256
+ catch {
257
+ stop();
258
+ client.close(1008, "Invalid history request");
259
+ }
238
260
  });
239
- await tick();
261
+ try {
262
+ initialPane = await validateTarget(target);
263
+ if (abort.signal.aborted)
264
+ return;
265
+ unwatch = agentHooks.watch(target);
266
+ reader = url.pathname === "/v1/transcripts" ? new TranscriptReader(await transcriptPath(target.source, target.session), target.source) : undefined;
267
+ if (abort.signal.aborted) {
268
+ stop();
269
+ return;
270
+ }
271
+ ready = true;
272
+ timer = setInterval(() => { void tick(); }, reader ? 500 : 1500);
273
+ await tick();
274
+ }
275
+ catch (error) {
276
+ stop();
277
+ throw error;
278
+ }
240
279
  }
241
280
  await new Promise((resolve, reject) => { http.once("error", reject); http.listen(socketPath(), () => resolve()); });
242
281
  await chmod(socketPath(), 0o600);
@@ -0,0 +1,27 @@
1
+ import { type FileHandle } from "node:fs/promises";
2
+ /** A sparse byte/line index, shared by live readers, history pages, and images.
3
+ * Indexing counts newlines without decoding JSON or retaining transcript text.
4
+ * At the 4 GiB file limit, checkpoints occupy only a few hundred KiB. */
5
+ declare class TranscriptIndex {
6
+ readonly file: string;
7
+ revision: `${string}-${string}-${string}-${string}-${string}`;
8
+ lines: number;
9
+ private identity;
10
+ private modified;
11
+ private scanned;
12
+ private complete;
13
+ private checkpoints;
14
+ private tail;
15
+ constructor(file: string);
16
+ use<T>(read: (handle: FileHandle, index: TranscriptIndex) => Promise<T>, signal?: AbortSignal): Promise<T>;
17
+ private refresh;
18
+ private position;
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<{
22
+ line: number;
23
+ bytes?: Buffer;
24
+ }>;
25
+ }
26
+ export declare function withTranscriptIndex<T>(file: string, read: (handle: FileHandle, index: TranscriptIndex) => Promise<T>, signal?: AbortSignal): Promise<T>;
27
+ export {};
@@ -0,0 +1,142 @@
1
+ import { open } from "node:fs/promises";
2
+ import { randomUUID } from "node:crypto";
3
+ import { BridgeError } from "./protocol.js";
4
+ const BLOCK = 65_536;
5
+ const CHECKPOINT_BYTES = 524_288;
6
+ const MAX_ROW_BYTES = 67_108_864;
7
+ /** A sparse byte/line index, shared by live readers, history pages, and images.
8
+ * Indexing counts newlines without decoding JSON or retaining transcript text.
9
+ * At the 4 GiB file limit, checkpoints occupy only a few hundred KiB. */
10
+ class TranscriptIndex {
11
+ file;
12
+ revision = randomUUID();
13
+ lines = 0;
14
+ identity = "";
15
+ modified = 0;
16
+ scanned = 0;
17
+ complete = 0;
18
+ checkpoints = [{ line: 0, offset: 0 }];
19
+ tail = Promise.resolve();
20
+ constructor(file) {
21
+ this.file = file;
22
+ }
23
+ use(read, signal) {
24
+ const task = this.tail.then(async () => {
25
+ signal?.throwIfAborted();
26
+ const handle = await open(this.file, "r");
27
+ try {
28
+ await this.refresh(handle, signal);
29
+ return await read(handle, this);
30
+ }
31
+ finally {
32
+ await handle.close();
33
+ }
34
+ });
35
+ this.tail = task.catch(() => { });
36
+ return task;
37
+ }
38
+ async refresh(handle, signal) {
39
+ const meta = await handle.stat();
40
+ if (!meta.isFile() || meta.size > 4_294_967_296)
41
+ throw new BridgeError(413, "This conversation exceeds the transcript limit.");
42
+ const identity = `${meta.dev}:${meta.ino}`;
43
+ if (identity !== this.identity || meta.size < this.scanned || (meta.size === this.scanned && meta.mtimeMs !== this.modified)) {
44
+ this.identity = identity;
45
+ this.revision = randomUUID();
46
+ this.scanned = 0;
47
+ this.complete = 0;
48
+ this.lines = 0;
49
+ this.checkpoints = [{ line: 0, offset: 0 }];
50
+ }
51
+ this.modified = meta.mtimeMs;
52
+ const buffer = Buffer.alloc(BLOCK);
53
+ while (this.scanned < meta.size) {
54
+ signal?.throwIfAborted();
55
+ const { bytesRead } = await handle.read(buffer, 0, Math.min(BLOCK, meta.size - this.scanned), this.scanned);
56
+ if (!bytesRead)
57
+ throw new BridgeError(409, "The transcript changed while loading. Refresh the conversation.");
58
+ for (let newline = buffer.indexOf(10); newline >= 0 && newline < bytesRead; newline = buffer.indexOf(10, newline + 1)) {
59
+ this.lines++;
60
+ this.complete = this.scanned + newline + 1;
61
+ if (this.complete - this.checkpoints.at(-1).offset >= CHECKPOINT_BYTES) {
62
+ this.checkpoints.push({ line: this.lines, offset: this.complete });
63
+ }
64
+ }
65
+ this.scanned += bytesRead;
66
+ }
67
+ }
68
+ async position(handle, line, signal) {
69
+ if (line === this.lines)
70
+ return this.complete;
71
+ let low = 0, high = this.checkpoints.length;
72
+ while (low + 1 < high) {
73
+ const mid = Math.floor((low + high) / 2);
74
+ if (this.checkpoints[mid].line <= line)
75
+ low = mid;
76
+ else
77
+ high = mid;
78
+ }
79
+ let { offset, line: current } = this.checkpoints[low];
80
+ const buffer = Buffer.alloc(BLOCK);
81
+ while (current < line) {
82
+ signal?.throwIfAborted();
83
+ const { bytesRead } = await handle.read(buffer, 0, Math.min(BLOCK, this.complete - offset), offset);
84
+ if (!bytesRead)
85
+ throw new BridgeError(409, "The transcript changed while loading. Refresh the conversation.");
86
+ for (let newline = buffer.indexOf(10); newline >= 0 && newline < bytesRead; newline = buffer.indexOf(10, newline + 1)) {
87
+ if (++current === line)
88
+ return offset + newline + 1;
89
+ }
90
+ offset += bytesRead;
91
+ }
92
+ return offset;
93
+ }
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) {
97
+ const endLine = Math.min(before, this.lines);
98
+ if (endLine <= after)
99
+ return;
100
+ let cursor = await this.position(handle, endLine, signal) - 1;
101
+ const lower = await this.position(handle, after, signal);
102
+ let line = endLine - 1, size = 0;
103
+ let parts = [];
104
+ const buffer = Buffer.alloc(BLOCK);
105
+ while (cursor > lower) {
106
+ signal?.throwIfAborted();
107
+ const start = Math.max(lower, cursor - BLOCK), length = cursor - start;
108
+ const { bytesRead } = await handle.read(buffer, 0, length, start);
109
+ if (bytesRead !== length)
110
+ throw new BridgeError(409, "The transcript changed while loading. Refresh the conversation.");
111
+ let end = bytesRead;
112
+ while (end > 0) {
113
+ const newline = buffer.lastIndexOf(10, end - 1), begin = newline + 1;
114
+ size += end - begin;
115
+ if (size <= MAX_ROW_BYTES)
116
+ parts.push(Buffer.from(buffer.subarray(begin, end)));
117
+ else
118
+ parts = [];
119
+ if (newline < 0)
120
+ break;
121
+ yield { line: line--, bytes: size <= MAX_ROW_BYTES ? Buffer.concat(parts.reverse(), size) : undefined };
122
+ parts = [];
123
+ size = 0;
124
+ end = newline;
125
+ }
126
+ cursor = start;
127
+ }
128
+ if (line >= after)
129
+ yield { line, bytes: size <= MAX_ROW_BYTES ? Buffer.concat(parts.reverse(), size) : undefined };
130
+ }
131
+ }
132
+ // No on-disk transcript copies. Eviction affects speed only; an evicted reader
133
+ // receives a fresh revision/backlog if it is subsequently reopened.
134
+ const indexes = new Map();
135
+ export function withTranscriptIndex(file, read, signal) {
136
+ const index = indexes.get(file) ?? new TranscriptIndex(file);
137
+ indexes.delete(file);
138
+ indexes.set(file, index);
139
+ while (indexes.size > 32)
140
+ indexes.delete(indexes.keys().next().value);
141
+ return index.use(read, signal);
142
+ }
@@ -6,23 +6,19 @@ export interface Entry {
6
6
  export declare function transcriptPath(source: Provider, session: string): Promise<string>;
7
7
  /** Public conversation/tool events and real usage only. Never export private reasoning. */
8
8
  export declare function visibleEvent(raw: Json, source: Provider): Json | undefined;
9
- /** Append-only reader with bounded retained history. Incomplete rows wait for the next read. */
9
+ /** Parse only the requested page; shared byte indexes make reopening and
10
+ * backward pagination independent of the amount of already-read history. */
10
11
  export declare class TranscriptReader {
11
12
  readonly file: string;
12
13
  readonly source: Provider;
13
14
  private readonly imageLine?;
14
- private offset;
15
- private inode?;
16
- private pending;
17
- private pendingBytes;
18
- private skippingRow;
19
- private line;
20
- private retained;
21
- private retainedBytes;
15
+ private revision?;
16
+ private nextLine;
22
17
  constructor(file: string, source: Provider, imageLine?: number | undefined);
23
- read(before?: number): Promise<{
18
+ read(before?: number, signal?: AbortSignal): Promise<{
24
19
  entries: Entry[];
25
20
  totalLines: number;
21
+ startLine: number;
26
22
  hasMore: boolean;
27
23
  reset: boolean;
28
24
  }>;
@@ -1,7 +1,8 @@
1
- import { open, realpath } from "node:fs/promises";
1
+ import { realpath } from "node:fs/promises";
2
2
  import { homedir } from "node:os";
3
3
  import path from "node:path";
4
4
  import { glob } from "glob";
5
+ import { withTranscriptIndex } from "./transcript-index.js";
5
6
  import { BridgeError, object, objects } from "./protocol.js";
6
7
  /** Preserve image block indexes without putting base64 payloads on the chat socket. */
7
8
  function chatFrame(raw, source) {
@@ -34,7 +35,7 @@ export async function transcriptPath(source, session) {
34
35
  export function visibleEvent(raw, source) {
35
36
  if (source === "codex") {
36
37
  const p = object(raw.payload);
37
- if (raw.type === "event_msg" && ["token_count", "task_started", "task_complete", "task_completed", "turn_aborted", "error"].includes(String(p.type)))
38
+ if (raw.type === "event_msg" && ["token_count", "task_started", "task_complete", "task_completed", "turn_aborted", "task_aborted", "error"].includes(String(p.type)))
38
39
  return raw;
39
40
  if (raw.type !== "response_item")
40
41
  return undefined;
@@ -54,7 +55,7 @@ export function visibleEvent(raw, source) {
54
55
  return { ...raw, message: { ...message, content: objects(message.content).map(b => ["text", "image", "tool_use", "tool_result"].includes(String(b.type)) ? b : { type: "redacted" }) } };
55
56
  }
56
57
  else {
57
- if (raw.agentId || raw.ephemeral || !["user.message", "assistant.message", "assistant.message_delta", "tool.execution_start", "tool.execution_complete", "assistant.turn_start", "assistant.turn_end", "session.idle", "session.error", "session.usage_info", "assistant.usage"].includes(String(raw.type)))
58
+ if (raw.agentId || raw.ephemeral || !["user.message", "assistant.message", "assistant.message_delta", "tool.execution_start", "tool.execution_complete", "assistant.turn_start", "assistant.turn_end", "session.idle", "abort", "session.error", "session.usage_info", "assistant.usage"].includes(String(raw.type)))
58
59
  return undefined;
59
60
  const data = object(raw.data);
60
61
  // Copilot includes optional reasoning beside the public message in some
@@ -64,96 +65,55 @@ export function visibleEvent(raw, source) {
64
65
  }
65
66
  return undefined;
66
67
  }
67
- /** Append-only reader with bounded retained history. Incomplete rows wait for the next read. */
68
+ /** Parse only the requested page; shared byte indexes make reopening and
69
+ * backward pagination independent of the amount of already-read history. */
68
70
  export class TranscriptReader {
69
71
  file;
70
72
  source;
71
73
  imageLine;
72
- offset = 0;
73
- inode;
74
- pending = [];
75
- pendingBytes = 0;
76
- skippingRow = false;
77
- line = 0;
78
- retained = [];
79
- retainedBytes = 0;
74
+ revision;
75
+ nextLine = 0;
80
76
  constructor(file, source, imageLine) {
81
77
  this.file = file;
82
78
  this.source = source;
83
79
  this.imageLine = imageLine;
84
80
  }
85
- async read(before) {
86
- const handle = await open(this.file, "r");
87
- try {
88
- const meta = await handle.stat();
89
- if (!meta.isFile() || meta.size > 4_294_967_296)
90
- throw new BridgeError(413, "This conversation exceeds the transcript limit.");
91
- const reset = this.inode !== meta.ino || meta.size < this.offset;
92
- if (reset) {
93
- this.offset = 0;
94
- this.line = 0;
95
- this.pending = [];
96
- this.pendingBytes = 0;
97
- this.skippingRow = false;
98
- this.retained = [];
99
- this.retainedBytes = 0;
100
- }
101
- this.inode = meta.ino;
102
- const start = this.line;
103
- const buffer = Buffer.alloc(65_536);
104
- while (this.offset < meta.size && (before === undefined || this.line < before)) {
105
- const { bytesRead } = await handle.read(buffer, 0, Math.min(buffer.length, meta.size - this.offset), this.offset);
106
- if (!bytesRead)
107
- break;
108
- this.offset += bytesRead;
109
- let cursor = 0;
110
- while (cursor < bytesRead) {
111
- const newline = buffer.indexOf(10, cursor);
112
- const complete = newline >= cursor && newline < bytesRead;
113
- const end = complete ? newline : bytesRead;
114
- this.pendingBytes += end - cursor;
115
- if (this.pendingBytes > 67_108_864) {
116
- this.skippingRow = true;
117
- this.pending = [];
118
- }
119
- if (!this.skippingRow)
120
- this.pending.push(Buffer.from(buffer.subarray(cursor, end)));
121
- cursor = end + (complete ? 1 : 0);
122
- if (!complete)
123
- break;
124
- const line = this.line++;
125
- const row = this.skippingRow ? undefined : Buffer.concat(this.pending, this.pendingBytes);
126
- this.pending = [];
127
- this.pendingBytes = 0;
128
- this.skippingRow = false;
129
- if (!row || (before !== undefined && line >= before))
130
- continue;
131
- try {
132
- const raw = visibleEvent(object(JSON.parse(row.toString())), this.source);
133
- if (raw) {
134
- const entry = { line, raw: this.imageLine === line ? raw : chatFrame(raw, this.source) };
135
- const size = Buffer.byteLength(JSON.stringify(entry));
136
- if (this.imageLine === line) {
137
- this.retained = [entry];
138
- this.retainedBytes = size;
139
- }
140
- else if (this.imageLine === undefined && size < 2_097_152) {
141
- this.retained.push(entry);
142
- this.retainedBytes += size;
143
- while (this.retained.length > 200 || this.retainedBytes > 4_194_304)
144
- this.retainedBytes -= Buffer.byteLength(JSON.stringify(this.retained.shift()));
145
- }
146
- }
81
+ async read(before, signal) {
82
+ return withTranscriptIndex(this.file, async (handle, index) => {
83
+ const reset = this.revision !== index.revision;
84
+ const end = Math.min(before ?? index.lines, index.lines);
85
+ const lower = this.imageLine ?? (reset || before !== undefined ? 0 : this.nextLine);
86
+ const entries = [];
87
+ let bytes = 0, cursor = end;
88
+ for await (const row of index.rows(handle, end, lower, signal)) {
89
+ signal?.throwIfAborted();
90
+ let entry;
91
+ try {
92
+ const raw = row.bytes && visibleEvent(object(JSON.parse(row.bytes.toString())), this.source);
93
+ if (raw)
94
+ entry = { line: row.line, raw: this.imageLine === row.line ? raw : chatFrame(raw, this.source) };
95
+ }
96
+ catch { /* A malformed old row cannot block the next readable page. */ }
97
+ if (entry) {
98
+ const size = Buffer.byteLength(JSON.stringify(entry));
99
+ if (this.imageLine !== undefined || size < 2_097_152) {
100
+ // Leave an entry that doesn't fit for the following history page.
101
+ if (this.imageLine === undefined && bytes + size > 4_194_304)
102
+ break;
103
+ entries.push(entry);
104
+ bytes += size;
147
105
  }
148
- catch { /* A malformed or oversized old row cannot block newer messages. */ }
149
106
  }
107
+ cursor = row.line;
108
+ if (entries.length >= 200)
109
+ break;
110
+ }
111
+ if (before === undefined) {
112
+ this.revision = index.revision;
113
+ this.nextLine = index.lines;
150
114
  }
151
- const entries = reset || before !== undefined ? this.retained : this.retained.filter(e => e.line >= start);
152
- return { entries, totalLines: this.line, hasMore: (this.retained[0]?.line ?? 0) > 0, reset };
153
- }
154
- finally {
155
- await handle.close();
156
- }
115
+ return { entries: entries.reverse(), totalLines: index.lines, startLine: cursor, hasMore: cursor > 0, reset };
116
+ }, signal);
157
117
  }
158
118
  }
159
119
  export async function historicalImage(file, line, block, source) {
@@ -3714,7 +3714,7 @@ import { createServer as createServer2 } from "node:http";
3714
3714
  import { chmod as chmod2, mkdir as mkdir4, lstat as lstat3, unlink as unlink3, writeFile as writeFile3, readFile as readFile3 } from "node:fs/promises";
3715
3715
  import { hostname as hostname3 } from "node:os";
3716
3716
  import path7 from "node:path";
3717
- import { randomUUID as randomUUID4 } from "node:crypto";
3717
+ import { randomUUID as randomUUID5 } from "node:crypto";
3718
3718
 
3719
3719
  // ../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/wrapper.mjs
3720
3720
  var import_stream = __toESM(require_stream(), 1);
@@ -18579,7 +18579,9 @@ async function snapshot(server) {
18579
18579
  return object2((await rpc(server, "session.snapshot")).snapshot);
18580
18580
  }
18581
18581
  function workspaceSnapshot(s) {
18582
- return { kind: "herdr", groups: objects(s.workspaces).map((w) => ({
18582
+ const focusedPane = objects(s.panes).find((p) => p.pane_id === s.focused_pane_id && p.tab_id === s.focused_tab_id && p.workspace_id === s.focused_workspace_id);
18583
+ const focus = focusedPane && id.safeParse(s.focused_workspace_id).success && id.safeParse(s.focused_tab_id).success && id.safeParse(s.focused_pane_id).success && objects(s.tabs).some((t) => t.tab_id === s.focused_tab_id && t.workspace_id === s.focused_workspace_id) && objects(s.workspaces).some((w) => w.workspace_id === s.focused_workspace_id) ? { workspaceID: s.focused_workspace_id, tabID: s.focused_tab_id, paneID: s.focused_pane_id } : void 0;
18584
+ return { kind: "herdr", focus, groups: objects(s.workspaces).map((w) => ({
18583
18585
  id: w.workspace_id,
18584
18586
  label: w.label,
18585
18587
  children: objects(s.tabs).filter((t) => t.workspace_id === w.workspace_id).map((t) => {
@@ -18744,7 +18746,7 @@ async function webServers() {
18744
18746
  }
18745
18747
 
18746
18748
  // src/bridge/transcripts.ts
18747
- import { open, realpath as realpath2 } from "node:fs/promises";
18749
+ import { realpath as realpath2 } from "node:fs/promises";
18748
18750
  import { homedir as homedir3 } from "node:os";
18749
18751
  import path5 from "node:path";
18750
18752
 
@@ -21732,6 +21734,130 @@ var Ui = Object.assign(ts, { stream: Bt, iterate: Ut });
21732
21734
  var Ze = Object.assign(Je, { glob: Je, globSync: ts, sync: Ui, globStream: Qe, stream: Ii, globStreamSync: Bt, streamSync: ji, globIterate: es, iterate: Bi, globIterateSync: Ut, iterateSync: zi, Glob: I, hasMagic: le, escape: tt, unescape: W });
21733
21735
  Ze.glob = Ze;
21734
21736
 
21737
+ // src/bridge/transcript-index.ts
21738
+ import { open } from "node:fs/promises";
21739
+ import { randomUUID as randomUUID3 } from "node:crypto";
21740
+ var BLOCK = 65536;
21741
+ var CHECKPOINT_BYTES = 524288;
21742
+ var MAX_ROW_BYTES = 67108864;
21743
+ var TranscriptIndex = class {
21744
+ constructor(file2) {
21745
+ this.file = file2;
21746
+ }
21747
+ file;
21748
+ revision = randomUUID3();
21749
+ lines = 0;
21750
+ identity = "";
21751
+ modified = 0;
21752
+ scanned = 0;
21753
+ complete = 0;
21754
+ checkpoints = [{ line: 0, offset: 0 }];
21755
+ tail = Promise.resolve();
21756
+ use(read, signal) {
21757
+ const task = this.tail.then(async () => {
21758
+ signal?.throwIfAborted();
21759
+ const handle = await open(this.file, "r");
21760
+ try {
21761
+ await this.refresh(handle, signal);
21762
+ return await read(handle, this);
21763
+ } finally {
21764
+ await handle.close();
21765
+ }
21766
+ });
21767
+ this.tail = task.catch(() => {
21768
+ });
21769
+ return task;
21770
+ }
21771
+ async refresh(handle, signal) {
21772
+ const meta3 = await handle.stat();
21773
+ if (!meta3.isFile() || meta3.size > 4294967296) throw new BridgeError(413, "This conversation exceeds the transcript limit.");
21774
+ const identity = `${meta3.dev}:${meta3.ino}`;
21775
+ if (identity !== this.identity || meta3.size < this.scanned || meta3.size === this.scanned && meta3.mtimeMs !== this.modified) {
21776
+ this.identity = identity;
21777
+ this.revision = randomUUID3();
21778
+ this.scanned = 0;
21779
+ this.complete = 0;
21780
+ this.lines = 0;
21781
+ this.checkpoints = [{ line: 0, offset: 0 }];
21782
+ }
21783
+ this.modified = meta3.mtimeMs;
21784
+ const buffer = Buffer.alloc(BLOCK);
21785
+ while (this.scanned < meta3.size) {
21786
+ signal?.throwIfAborted();
21787
+ const { bytesRead } = await handle.read(buffer, 0, Math.min(BLOCK, meta3.size - this.scanned), this.scanned);
21788
+ if (!bytesRead) throw new BridgeError(409, "The transcript changed while loading. Refresh the conversation.");
21789
+ for (let newline = buffer.indexOf(10); newline >= 0 && newline < bytesRead; newline = buffer.indexOf(10, newline + 1)) {
21790
+ this.lines++;
21791
+ this.complete = this.scanned + newline + 1;
21792
+ if (this.complete - this.checkpoints.at(-1).offset >= CHECKPOINT_BYTES) {
21793
+ this.checkpoints.push({ line: this.lines, offset: this.complete });
21794
+ }
21795
+ }
21796
+ this.scanned += bytesRead;
21797
+ }
21798
+ }
21799
+ async position(handle, line, signal) {
21800
+ if (line === this.lines) return this.complete;
21801
+ let low = 0, high = this.checkpoints.length;
21802
+ while (low + 1 < high) {
21803
+ const mid = Math.floor((low + high) / 2);
21804
+ if (this.checkpoints[mid].line <= line) low = mid;
21805
+ else high = mid;
21806
+ }
21807
+ let { offset, line: current } = this.checkpoints[low];
21808
+ const buffer = Buffer.alloc(BLOCK);
21809
+ while (current < line) {
21810
+ signal?.throwIfAborted();
21811
+ const { bytesRead } = await handle.read(buffer, 0, Math.min(BLOCK, this.complete - offset), offset);
21812
+ if (!bytesRead) throw new BridgeError(409, "The transcript changed while loading. Refresh the conversation.");
21813
+ for (let newline = buffer.indexOf(10); newline >= 0 && newline < bytesRead; newline = buffer.indexOf(10, newline + 1)) {
21814
+ if (++current === line) return offset + newline + 1;
21815
+ }
21816
+ offset += bytesRead;
21817
+ }
21818
+ return offset;
21819
+ }
21820
+ /** Read newest first and stop as soon as the caller has a page. Large rows
21821
+ * are skipped with bounded memory while keeping absolute line identities. */
21822
+ async *rows(handle, before, after, signal) {
21823
+ const endLine = Math.min(before, this.lines);
21824
+ if (endLine <= after) return;
21825
+ let cursor = await this.position(handle, endLine, signal) - 1;
21826
+ const lower = await this.position(handle, after, signal);
21827
+ let line = endLine - 1, size = 0;
21828
+ let parts = [];
21829
+ const buffer = Buffer.alloc(BLOCK);
21830
+ while (cursor > lower) {
21831
+ signal?.throwIfAborted();
21832
+ const start = Math.max(lower, cursor - BLOCK), length = cursor - start;
21833
+ const { bytesRead } = await handle.read(buffer, 0, length, start);
21834
+ if (bytesRead !== length) throw new BridgeError(409, "The transcript changed while loading. Refresh the conversation.");
21835
+ let end = bytesRead;
21836
+ while (end > 0) {
21837
+ const newline = buffer.lastIndexOf(10, end - 1), begin = newline + 1;
21838
+ size += end - begin;
21839
+ if (size <= MAX_ROW_BYTES) parts.push(Buffer.from(buffer.subarray(begin, end)));
21840
+ else parts = [];
21841
+ if (newline < 0) break;
21842
+ yield { line: line--, bytes: size <= MAX_ROW_BYTES ? Buffer.concat(parts.reverse(), size) : void 0 };
21843
+ parts = [];
21844
+ size = 0;
21845
+ end = newline;
21846
+ }
21847
+ cursor = start;
21848
+ }
21849
+ if (line >= after) yield { line, bytes: size <= MAX_ROW_BYTES ? Buffer.concat(parts.reverse(), size) : void 0 };
21850
+ }
21851
+ };
21852
+ var indexes = /* @__PURE__ */ new Map();
21853
+ function withTranscriptIndex(file2, read, signal) {
21854
+ const index = indexes.get(file2) ?? new TranscriptIndex(file2);
21855
+ indexes.delete(file2);
21856
+ indexes.set(file2, index);
21857
+ while (indexes.size > 32) indexes.delete(indexes.keys().next().value);
21858
+ return index.use(read, signal);
21859
+ }
21860
+
21735
21861
  // src/bridge/transcripts.ts
21736
21862
  function chatFrame(raw, source) {
21737
21863
  const key = source === "codex" ? "payload" : "message";
@@ -21756,7 +21882,7 @@ async function transcriptPath(source, session) {
21756
21882
  function visibleEvent(raw, source) {
21757
21883
  if (source === "codex") {
21758
21884
  const p = object2(raw.payload);
21759
- if (raw.type === "event_msg" && ["token_count", "task_started", "task_complete", "task_completed", "turn_aborted", "error"].includes(String(p.type))) return raw;
21885
+ if (raw.type === "event_msg" && ["token_count", "task_started", "task_complete", "task_completed", "turn_aborted", "task_aborted", "error"].includes(String(p.type))) return raw;
21760
21886
  if (raw.type !== "response_item") return void 0;
21761
21887
  if (p.type === "message" && ["user", "assistant"].includes(String(p.role)) && p.channel !== "analysis") return raw;
21762
21888
  if (["function_call", "custom_tool_call", "function_call_output", "custom_tool_call_output"].includes(String(p.type))) return raw;
@@ -21766,7 +21892,7 @@ function visibleEvent(raw, source) {
21766
21892
  if (typeof message.content === "string") return raw;
21767
21893
  if (Array.isArray(message.content)) return { ...raw, message: { ...message, content: objects(message.content).map((b) => ["text", "image", "tool_use", "tool_result"].includes(String(b.type)) ? b : { type: "redacted" }) } };
21768
21894
  } else {
21769
- if (raw.agentId || raw.ephemeral || !["user.message", "assistant.message", "assistant.message_delta", "tool.execution_start", "tool.execution_complete", "assistant.turn_start", "assistant.turn_end", "session.idle", "session.error", "session.usage_info", "assistant.usage"].includes(String(raw.type))) return void 0;
21895
+ if (raw.agentId || raw.ephemeral || !["user.message", "assistant.message", "assistant.message_delta", "tool.execution_start", "tool.execution_complete", "assistant.turn_start", "assistant.turn_end", "session.idle", "abort", "session.error", "session.usage_info", "assistant.usage"].includes(String(raw.type))) return void 0;
21770
21896
  const data = object2(raw.data);
21771
21897
  const allowed = ["content", "source", "messageId", "deltaContent", "toolName", "toolCallId", "arguments", "result", "error", "aborted", "inputTokens", "outputTokens", "cacheReadTokens"];
21772
21898
  return { type: raw.type, timestamp: raw.timestamp, data: Object.fromEntries(Object.entries(data).filter(([key]) => allowed.includes(key))) };
@@ -21782,78 +21908,40 @@ var TranscriptReader = class {
21782
21908
  file;
21783
21909
  source;
21784
21910
  imageLine;
21785
- offset = 0;
21786
- inode;
21787
- pending = [];
21788
- pendingBytes = 0;
21789
- skippingRow = false;
21790
- line = 0;
21791
- retained = [];
21792
- retainedBytes = 0;
21793
- async read(before) {
21794
- const handle = await open(this.file, "r");
21795
- try {
21796
- const meta3 = await handle.stat();
21797
- if (!meta3.isFile() || meta3.size > 4294967296) throw new BridgeError(413, "This conversation exceeds the transcript limit.");
21798
- const reset = this.inode !== meta3.ino || meta3.size < this.offset;
21799
- if (reset) {
21800
- this.offset = 0;
21801
- this.line = 0;
21802
- this.pending = [];
21803
- this.pendingBytes = 0;
21804
- this.skippingRow = false;
21805
- this.retained = [];
21806
- this.retainedBytes = 0;
21807
- }
21808
- this.inode = meta3.ino;
21809
- const start = this.line;
21810
- const buffer = Buffer.alloc(65536);
21811
- while (this.offset < meta3.size && (before === void 0 || this.line < before)) {
21812
- const { bytesRead } = await handle.read(buffer, 0, Math.min(buffer.length, meta3.size - this.offset), this.offset);
21813
- if (!bytesRead) break;
21814
- this.offset += bytesRead;
21815
- let cursor = 0;
21816
- while (cursor < bytesRead) {
21817
- const newline = buffer.indexOf(10, cursor);
21818
- const complete = newline >= cursor && newline < bytesRead;
21819
- const end = complete ? newline : bytesRead;
21820
- this.pendingBytes += end - cursor;
21821
- if (this.pendingBytes > 67108864) {
21822
- this.skippingRow = true;
21823
- this.pending = [];
21824
- }
21825
- if (!this.skippingRow) this.pending.push(Buffer.from(buffer.subarray(cursor, end)));
21826
- cursor = end + (complete ? 1 : 0);
21827
- if (!complete) break;
21828
- const line = this.line++;
21829
- const row = this.skippingRow ? void 0 : Buffer.concat(this.pending, this.pendingBytes);
21830
- this.pending = [];
21831
- this.pendingBytes = 0;
21832
- this.skippingRow = false;
21833
- if (!row || before !== void 0 && line >= before) continue;
21834
- try {
21835
- const raw = visibleEvent(object2(JSON.parse(row.toString())), this.source);
21836
- if (raw) {
21837
- const entry = { line, raw: this.imageLine === line ? raw : chatFrame(raw, this.source) };
21838
- const size = Buffer.byteLength(JSON.stringify(entry));
21839
- if (this.imageLine === line) {
21840
- this.retained = [entry];
21841
- this.retainedBytes = size;
21842
- } else if (this.imageLine === void 0 && size < 2097152) {
21843
- this.retained.push(entry);
21844
- this.retainedBytes += size;
21845
- while (this.retained.length > 200 || this.retainedBytes > 4194304) this.retainedBytes -= Buffer.byteLength(JSON.stringify(this.retained.shift()));
21846
- }
21847
- }
21848
- } catch {
21911
+ revision;
21912
+ nextLine = 0;
21913
+ async read(before, signal) {
21914
+ return withTranscriptIndex(this.file, async (handle, index) => {
21915
+ const reset = this.revision !== index.revision;
21916
+ const end = Math.min(before ?? index.lines, index.lines);
21917
+ const lower = this.imageLine ?? (reset || before !== void 0 ? 0 : this.nextLine);
21918
+ const entries = [];
21919
+ let bytes = 0, cursor = end;
21920
+ for await (const row of index.rows(handle, end, lower, signal)) {
21921
+ signal?.throwIfAborted();
21922
+ let entry;
21923
+ try {
21924
+ const raw = row.bytes && visibleEvent(object2(JSON.parse(row.bytes.toString())), this.source);
21925
+ if (raw) entry = { line: row.line, raw: this.imageLine === row.line ? raw : chatFrame(raw, this.source) };
21926
+ } catch {
21927
+ }
21928
+ if (entry) {
21929
+ const size = Buffer.byteLength(JSON.stringify(entry));
21930
+ if (this.imageLine !== void 0 || size < 2097152) {
21931
+ if (this.imageLine === void 0 && bytes + size > 4194304) break;
21932
+ entries.push(entry);
21933
+ bytes += size;
21849
21934
  }
21850
21935
  }
21936
+ cursor = row.line;
21937
+ if (entries.length >= 200) break;
21851
21938
  }
21852
- const entries = reset || before !== void 0 ? this.retained : this.retained.filter((e) => e.line >= start);
21853
- return { entries, totalLines: this.line, hasMore: (this.retained[0]?.line ?? 0) > 0, reset };
21854
- } finally {
21855
- await handle.close();
21856
- }
21939
+ if (before === void 0) {
21940
+ this.revision = index.revision;
21941
+ this.nextLine = index.lines;
21942
+ }
21943
+ return { entries: entries.reverse(), totalLines: index.lines, startLine: cursor, hasMore: cursor > 0, reset };
21944
+ }, signal);
21857
21945
  }
21858
21946
  };
21859
21947
  async function historicalImage(file2, line, block, source) {
@@ -21875,7 +21963,7 @@ async function historicalImage(file2, line, block, source) {
21875
21963
  // src/bridge/uploads.ts
21876
21964
  import { mkdir as mkdir3, readdir as readdir2, lstat as lstat2, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises";
21877
21965
  import path6 from "node:path";
21878
- import { randomUUID as randomUUID3 } from "node:crypto";
21966
+ import { randomUUID as randomUUID4 } from "node:crypto";
21879
21967
  function imageBytes(bytes) {
21880
21968
  return bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])) || bytes.subarray(0, 3).equals(Buffer.from([255, 216, 255])) || /^GIF8[79]a/.test(bytes.subarray(0, 6).toString()) || bytes.subarray(0, 4).toString() === "RIFF" && bytes.subarray(8, 12).toString() === "WEBP";
21881
21969
  }
@@ -21902,7 +21990,7 @@ async function saveUpload(session, name, bytes) {
21902
21990
  if (used + bytes.length > 268435456) throw new BridgeError(413, "Phren's image storage is full. Remove older uploads on the computer.");
21903
21991
  const folder = path6.join(root, session);
21904
21992
  await mkdir3(folder, { recursive: true, mode: 448 });
21905
- saved = path6.join(folder, `${randomUUID3()}-${name}`);
21993
+ saved = path6.join(folder, `${randomUUID4()}-${name}`);
21906
21994
  await writeFile2(saved, bytes, { flag: "wx", mode: 384 });
21907
21995
  });
21908
21996
  uploadQueue = task;
@@ -21959,7 +22047,7 @@ async function serve(version2) {
21959
22047
  try {
21960
22048
  computerID = (await readFile3(identityFile, "utf8")).trim();
21961
22049
  } catch {
21962
- computerID = randomUUID4();
22050
+ computerID = randomUUID5();
21963
22051
  await writeFile3(identityFile, computerID, { flag: "wx", mode: 384 });
21964
22052
  }
21965
22053
  const journal = new ActivityJournal();
@@ -22018,6 +22106,19 @@ async function serve(version2) {
22018
22106
  response.end(bytes);
22019
22107
  return;
22020
22108
  }
22109
+ case "/v1/transcripts/history": {
22110
+ const target = targetFromURL(url2);
22111
+ const before = external_exports.coerce.number().int().positive().parse(url2.searchParams.get("beforeLine"));
22112
+ const abort = new AbortController();
22113
+ response.once("close", () => {
22114
+ if (!response.writableEnded) abort.abort();
22115
+ });
22116
+ await validateTarget(target);
22117
+ const reader = new TranscriptReader(await transcriptPath(target.source, target.session), target.source);
22118
+ const page = await reader.read(before, abort.signal);
22119
+ result = { ...page, type: "older", source: target.source, session: target.session };
22120
+ break;
22121
+ }
22021
22122
  default:
22022
22123
  throw new BridgeError(404, "Unknown Phren Hook route.");
22023
22124
  }
@@ -22080,71 +22181,91 @@ async function serve(version2) {
22080
22181
  });
22081
22182
  async function stream(client, url2) {
22082
22183
  const target = targetFromURL(url2);
22083
- await validateTarget(target);
22084
- if (client.readyState !== import_websocket.default.OPEN) return;
22085
- const unwatch = agentHooks.watch(target);
22086
- client.once("close", unwatch);
22087
- const reader = url2.pathname === "/v1/transcripts" ? new TranscriptReader(await transcriptPath(target.source, target.session), target.source) : void 0;
22088
- let busy = false, closed = false, first = true;
22089
- client.on("close", () => {
22090
- closed = true;
22091
- clearInterval(timer);
22092
- });
22093
- client.on("error", () => {
22094
- closed = true;
22184
+ const abort = new AbortController();
22185
+ let reader, timer;
22186
+ let unwatch;
22187
+ let busy = false, ready = false, first = true;
22188
+ let initialPane;
22189
+ const pending = [];
22190
+ const stop = () => {
22191
+ abort.abort();
22095
22192
  clearInterval(timer);
22096
- });
22193
+ unwatch?.();
22194
+ pending.length = 0;
22195
+ };
22196
+ client.once("close", stop);
22197
+ client.once("error", stop);
22097
22198
  const tick = async () => {
22098
- if (busy || closed) return;
22199
+ if (busy || !ready || abort.signal.aborted) return;
22099
22200
  busy = true;
22100
22201
  try {
22101
- const pane = await validateTarget(target);
22102
- if (reader) {
22103
- const page = await reader.read();
22104
- if (first || page.entries.length || page.reset) send(client, {
22105
- type: first || page.reset ? "backlog" : "append",
22106
- source: target.source,
22107
- session: target.session,
22108
- entries: page.entries,
22109
- totalLines: page.totalLines,
22110
- hasMore: page.hasMore
22111
- });
22112
- } else {
22113
- const pendingApproval = agentHooks.approval(target);
22114
- send(client, { agentStatus: {
22115
- source: target.source,
22116
- session: target.session,
22117
- status: pendingApproval ? "waiting" : pane.agent_status,
22118
- pendingApproval,
22119
- capabilities
22120
- } });
22121
- }
22122
- first = false;
22202
+ if (first || pending.length === 0) {
22203
+ const pane = first ? initialPane : await validateTarget(target);
22204
+ if (reader) {
22205
+ const page = await reader.read(void 0, abort.signal);
22206
+ if (first || page.entries.length || page.reset) send(client, {
22207
+ ...page,
22208
+ type: first || page.reset ? "backlog" : "append",
22209
+ source: target.source,
22210
+ session: target.session
22211
+ });
22212
+ } else {
22213
+ const pendingApproval = agentHooks.approval(target);
22214
+ send(client, { agentStatus: {
22215
+ source: target.source,
22216
+ session: target.session,
22217
+ status: pendingApproval ? "waiting" : pane.agent_status,
22218
+ pendingApproval,
22219
+ capabilities
22220
+ } });
22221
+ }
22222
+ first = false;
22223
+ }
22224
+ while (pending.length && reader && !abort.signal.aborted) {
22225
+ const before = pending.shift();
22226
+ await validateTarget(target);
22227
+ const page = await reader.read(before, abort.signal);
22228
+ send(client, { ...page, type: "older", source: target.source, session: target.session });
22229
+ }
22123
22230
  } catch {
22231
+ stop();
22124
22232
  client.close(1011, "The conversation changed; refresh");
22125
22233
  } finally {
22126
22234
  busy = false;
22235
+ if (pending.length) void tick();
22127
22236
  }
22128
22237
  };
22129
- const timer = setInterval(() => {
22130
- void tick();
22131
- }, reader ? 500 : 1500);
22132
22238
  client.on("message", (bytes) => {
22133
- void (async () => {
22239
+ try {
22134
22240
  const message = object2(JSON.parse(bytes.toString()));
22135
- if (message.type !== "older" || !reader || busy) return;
22136
- busy = true;
22137
- try {
22138
- await validateTarget(target);
22139
- const before = external_exports.number().int().positive().parse(message.beforeLine);
22140
- const page = await new TranscriptReader(reader.file, target.source).read(before);
22141
- send(client, { type: "older", source: target.source, entries: page.entries, hasMore: page.hasMore, totalLines: page.totalLines });
22142
- } finally {
22143
- busy = false;
22144
- }
22145
- })().catch(() => client.close(1008, "Invalid history request"));
22241
+ if (message.type !== "older" || url2.pathname !== "/v1/transcripts" || abort.signal.aborted) return;
22242
+ const before = external_exports.number().int().positive().parse(message.beforeLine);
22243
+ if (pending.length >= 8) throw new Error("History queue is full");
22244
+ if (!pending.includes(before)) pending.push(before);
22245
+ void tick();
22246
+ } catch {
22247
+ stop();
22248
+ client.close(1008, "Invalid history request");
22249
+ }
22146
22250
  });
22147
- await tick();
22251
+ try {
22252
+ initialPane = await validateTarget(target);
22253
+ if (abort.signal.aborted) return;
22254
+ unwatch = agentHooks.watch(target);
22255
+ reader = url2.pathname === "/v1/transcripts" ? new TranscriptReader(await transcriptPath(target.source, target.session), target.source) : void 0;
22256
+ if (abort.signal.aborted) {
22257
+ stop();
22258
+ return;
22259
+ }
22260
+ ready = true;
22261
+ timer = setInterval(() => {
22262
+ void tick();
22263
+ }, reader ? 500 : 1500);
22264
+ await tick();
22265
+ } catch (error51) {
22266
+ stop();
22267
+ throw error51;
22268
+ }
22148
22269
  }
22149
22270
  await new Promise((resolve, reject) => {
22150
22271
  http.once("error", reject);
@@ -22563,7 +22684,7 @@ async function runBridge(args, version2) {
22563
22684
  }
22564
22685
 
22565
22686
  // src/bridge/hook-main.ts
22566
- runBridge(process.argv.slice(2), "0.2.12").then((code) => {
22687
+ runBridge(process.argv.slice(2), "0.2.14").then((code) => {
22567
22688
  process.exitCode = code;
22568
22689
  }).catch((error51) => {
22569
22690
  console.error(error51 instanceof Error ? error51.message : "Phren Hook failed.");
@@ -430,7 +430,7 @@ export function addTask(phrenPath, project, item, opts) {
430
430
  line,
431
431
  checked: false,
432
432
  priority: normalizePriority(line),
433
- createdAt: opts?.createdAt,
433
+ createdAt: opts?.createdAt ?? new Date().toISOString(),
434
434
  sessionId: opts?.sessionId,
435
435
  scope: opts?.scope,
436
436
  parentFinding: opts?.parentFinding,
@@ -468,6 +468,7 @@ export function addTasks(phrenPath, project, items, opts) {
468
468
  checked: false,
469
469
  priority: normalizePriority(line),
470
470
  scope: opts?.scope,
471
+ createdAt: new Date().toISOString(),
471
472
  });
472
473
  added.push(line);
473
474
  }
@@ -7,14 +7,8 @@ import { queryDocBySourceKey, queryRows, queryFragmentLinks, queryCrossProjectFr
7
7
  import { runtimeFile } from "../shared.js";
8
8
  import { withFileLock } from "../shared/governance.js";
9
9
  import { logger } from "../logger.js";
10
- // NOTE on naming: titles/descriptions below all say "fragment" (the entity ->
11
- // fragment rename, CHANGELOG 0.0.5), but the actual input schema key on
12
- // get_related_docs, link_findings, and cross_project_fragments is still
13
- // `entity` / `entity_type` — renaming it is a breaking change to a live MCP
14
- // tool contract, plus link_findings persists that same shape to
15
- // .runtime/manual-links.json (read back in shared/index.ts), so it is not a
16
- // same-PR-safe rename. Left as-is; flagged for a product decision rather than
17
- // changed unilaterally.
10
+ // Compatibility decision (2026-09): fragments keep the established entity /
11
+ // entity_type wire keys and manual-links.json fields. See docs/api-reference.md.
18
12
  export function register(server, ctx) {
19
13
  // ── search_fragments ──────────────────────────────────────────────────
20
14
  server.registerTool("search_fragments", {
@@ -22,7 +16,7 @@ export function register(server, ctx) {
22
16
  description: "Search named fragments in the knowledge graph (libraries, tools, concepts mentioned in findings). " +
23
17
  "Returns matching fragment names and how many findings reference each.",
24
18
  inputSchema: z.object({
25
- query: z.string().describe("Fragment name to search for (partial match)."),
19
+ query: z.string().describe("Fragment name to search for (partial match); the compatible parameter key remains entity."),
26
20
  project: z.string().optional().describe("Filter to a specific project."),
27
21
  limit: z.number().int().min(1).max(50).optional().describe("Max results (default 10)."),
28
22
  }),
@@ -74,7 +68,7 @@ export function register(server, ctx) {
74
68
  description: "Find all findings and docs that mention a specific fragment (library, tool, concept). " +
75
69
  "Use this to see how a technology is used across projects.",
76
70
  inputSchema: z.object({
77
- entity: z.string().describe("Fragment name to look up."),
71
+ entity: z.string().describe("Fragment name to look up; the compatible parameter key remains entity."),
78
72
  project: z.string().optional().describe("Filter to a specific project."),
79
73
  limit: z.number().int().min(1).max(50).optional().describe("Max docs to return (default 10)."),
80
74
  }),
@@ -206,7 +200,7 @@ export function register(server, ctx) {
206
200
  inputSchema: z.object({
207
201
  project: z.string().describe("Project name."),
208
202
  finding_text: z.string().describe("Partial text of the finding to link (used to locate the source doc)."),
209
- entity: z.string().describe("Fragment name to link to (e.g. 'Redis', 'Docker')."),
203
+ entity: z.string().describe("Fragment name to link to (e.g. 'Redis', 'Docker'); the compatible parameter key remains entity."),
210
204
  relation: z.string().optional().describe("Relationship type (default: 'mentions')."),
211
205
  entity_type: z.string().optional().describe("Fragment type (e.g. 'library', 'service', 'concept', 'architecture'). Defaults to 'fragment'."),
212
206
  }),
@@ -317,7 +311,7 @@ export function register(server, ctx) {
317
311
  description: "Find fragments (libraries, tools, concepts) shared across multiple projects. " +
318
312
  "Use this to discover how a technology or concept is used in other projects.",
319
313
  inputSchema: z.object({
320
- entity: z.string().describe("Fragment name to search for (partial match)."),
314
+ entity: z.string().describe("Fragment name to search for (partial match); the compatible parameter key remains entity."),
321
315
  exclude_project: z.string().optional().describe("Exclude a specific project from results."),
322
316
  limit: z.number().int().min(1).max(50).optional().describe("Max results (default 20)."),
323
317
  }),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phren/cli",
3
- "version": "0.2.12",
3
+ "version": "0.2.14",
4
4
  "description": "Knowledge layer for AI agents — CLI, MCP server, and data layer",
5
5
  "type": "module",
6
6
  "bin": {