@phren/cli 0.3.69 → 0.3.71

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.
@@ -0,0 +1,24 @@
1
+ import { stripTerminal } from "../terminal-text.js";
2
+ /** Claude's permission mode from the footer line its TUI draws under the
3
+ * composer. The transcript lags it: a `permission-mode` row is written only
4
+ * when a prompt is submitted, and a fresh session has no file yet. The line may
5
+ * trail hints ("(shift+tab to cycle) · 1 agent"), so only its start counts. A
6
+ * mode the footer does not mark is `undefined`: "manual mode on" is default. */
7
+ export function claudeFooterMode(screen) {
8
+ for (const line of stripTerminal(screen).split(/\r?\n/).map(line => line.trim()).filter(Boolean).slice(-8).reverse()) {
9
+ const text = line.replace(/^[⏵⏸]+\s*/, "");
10
+ if (text === line)
11
+ continue;
12
+ if (/bypass permissions on/i.test(text))
13
+ return "bypassPermissions";
14
+ if (/^manual mode on\b/i.test(text))
15
+ return "default";
16
+ if (/^accept edits on\b/i.test(text))
17
+ return "acceptEdits";
18
+ if (/^plan mode on\b/i.test(text))
19
+ return "plan";
20
+ if (/^auto mode on\b/i.test(text))
21
+ return "auto";
22
+ }
23
+ return undefined;
24
+ }
@@ -1,3 +1,4 @@
1
+ import { joinDialogFooters } from "./terminal-dialog-text.js";
1
2
  import { BridgeError } from "./protocol.js";
2
3
  const TAB_BAR = /^\s*(?:←\s+)?((?:[☐☒]\s+\S[^☐☒✔→]*?\s*)+)(?:✔\s+Submit\s*)?(?:→\s*)?$/;
3
4
  const ROW = /^\s*(❯)?\s*(\d)\.\s+(?:\[([ ✔])\]\s+)?(.*?)\s*$/;
@@ -25,17 +26,49 @@ const GUTTER = /^(\s*)│(?: |$)/;
25
26
  * lines are not one: the last tab bar anchors it, and an active dialog ends
26
27
  * with its "Esc to cancel" footer or the review's Submit/Cancel rows. */
27
28
  export function claudeQuestionDialog(text) {
28
- const lines = text.split(/\r?\n/);
29
- let bar = -1;
30
- for (let index = lines.length - 1; index >= 0; index--)
31
- if (TAB_BAR.test(lines[index]) && /[☐☒]/.test(lines[index])) {
32
- bar = index;
33
- break;
29
+ const lines = joinDialogFooters(text.split(/\r?\n/));
30
+ let bar = -1, barEnd = -1, tabBar = "";
31
+ // A narrow pane soft-wraps the tab bar. Reading only its last physical
32
+ // row either loses tabs (a false set mismatch) or misses the dialog when
33
+ // that row contains only Submit. Keep the complete last bar and start
34
+ // the body after all of its physical rows.
35
+ for (let end = lines.length - 1; end >= 0 && bar < 0; end--) {
36
+ let candidates = [];
37
+ for (let start = end; start >= 0; start--) {
38
+ const line = lines[start];
39
+ if (!line.trim() || /^─+$/.test(line.trim()))
40
+ break;
41
+ // Terminal cell counts cannot reliably recover a wrap boundary (emoji
42
+ // sequences vary by terminal), and a capture drops the space a row
43
+ // wrapped after. Keep both joins of each wrap, no space first, while
44
+ // they still end in the Submit suffix; a complete bar wins over one
45
+ // that only has the suffix.
46
+ const joins = candidates.length ? candidates.flatMap(value => [line + value, line + " " + value]) : [line];
47
+ const viable = joins.filter(value => TAB_BAR.test(value) || /✔\s+Submit\s*(?:→\s*)?$/.test(value));
48
+ candidates = (viable.length ? viable : joins.slice(0, 1)).slice(0, 16);
49
+ const complete = candidates.find(value => TAB_BAR.test(value) && /[☐☒]/.test(value));
50
+ if (complete) {
51
+ bar = start;
52
+ barEnd = end;
53
+ tabBar = complete;
54
+ }
55
+ // The leading arrow is the start of this bar. A checkbox in earlier
56
+ // output belongs to that output, even when there is no blank row.
57
+ if (/^\s*←/.test(line))
58
+ break;
34
59
  }
60
+ }
35
61
  if (bar < 0)
36
62
  return undefined;
37
- const tabs = [...lines[bar].matchAll(/[☐☒]\s+([^☐☒✔→]+?)(?=\s{2,}|\s*[☐☒✔→]|\s*$)/g)].map(match => match[1].trim());
38
- const body = lines.slice(bar + 1);
63
+ const tabs = [...tabBar.matchAll(/[☐☒]\s+([^☐☒✔→]+?)(?=\s{2,}|\s*[☐☒✔→]|\s*$)/g)].map(match => match[1].trim());
64
+ const body = lines.slice(barEnd + 1);
65
+ const tail = body.map(line => line.trim()).filter(line => line && !/^─+$/.test(line));
66
+ if (!/^(?:Enter to .*Esc to cancel|2\. Cancel)$/.test(tail.at(-1) ?? ""))
67
+ return undefined;
68
+ if (lines.slice(0, bar).filter(line => /^\s*```/.test(line)).length % 2)
69
+ return undefined;
70
+ if (body.filter(line => ROW.exec(line)?.[1] || NEXT.exec(line)?.[1]).length !== 1)
71
+ return undefined;
39
72
  const content = body.map(line => line.replace(GUTTER, "$1").trim()).filter(line => line && !/^─+$/.test(line));
40
73
  if (content[0] === "Review your answers") {
41
74
  if (!body.some(line => /^\s*❯?\s*1\.\s+Submit answers\s*$/.test(line)))
@@ -88,7 +121,7 @@ export function claudeQuestionDialog(text) {
88
121
  rows.push({ number, label: answered ? match[4].slice(0, -2).trim() : match[4], answered, cursor: !!match[1],
89
122
  ...(match[3] ? { checked: match[3] === "✔" } : {}) });
90
123
  }
91
- if (!title || !chat || rows.length < 2)
124
+ if (!title || !chat || cursor === undefined || rows.length < 2)
92
125
  return undefined;
93
126
  // The last row above "Chat about this" is the typed answer ("Type
94
127
  // something." until something is typed there).
@@ -0,0 +1,8 @@
1
+ import { type Json } from "./protocol.js";
2
+ /** Reconcile synchronous Claude questions from the conversation's own records.
3
+ * Async Codex questions have a different lifetime and never enter this path. */
4
+ export declare function claudeQuestionResolutions(file: string, boundary?: number, signal?: AbortSignal): Promise<ReadonlySet<string>>;
5
+ /** An explicit resolution, never an invented answer. Keep it with the original
6
+ * question's stable row so backlog, reconnects and pagination agree. Existing
7
+ * clients already understand identity-matched tool_result blocks. */
8
+ export declare function projectClaudeQuestionResolutions(raw: Json, resolved: ReadonlySet<string>): Json;
@@ -0,0 +1,87 @@
1
+ import { object, objects } from "./protocol.js";
2
+ import { withTranscriptIndex } from "./transcript-index.js";
3
+ import { visibleClaudeEvent } from "./transcript-claude.js";
4
+ const states = new Map();
5
+ /** Reconcile synchronous Claude questions from the conversation's own records.
6
+ * Async Codex questions have a different lifetime and never enter this path. */
7
+ export async function claudeQuestionResolutions(file, boundary, signal) {
8
+ return withTranscriptIndex(file, async (handle, index) => {
9
+ const cached = states.get(file);
10
+ const current = cached?.revision === index.revision && cached.lines <= index.lines ? cached : undefined;
11
+ if (current?.lines === index.lines && (boundary === undefined || ![...current.pending.values()].some(ask => ask.at <= boundary)))
12
+ return current.resolved;
13
+ const state = { revision: index.revision, lines: index.lines,
14
+ pending: new Map(current?.pending), resolved: new Set(current?.resolved) };
15
+ const resolve = (id) => { state.pending.delete(id); state.resolved.add(id); };
16
+ // Scan newest first with only two newer assistant identities. Once both
17
+ // differ, every older synchronous question has necessarily been left.
18
+ // Retain no transcript bodies or per-row copy, even on an initial scan.
19
+ const assistants = new Set(), results = new Set(), added = new Map();
20
+ let owner = false;
21
+ const movedOn = (ask) => owner || results.has(ask.id) || [...assistants].some(id => id !== ask.assistant);
22
+ for await (const row of index.rows(handle, index.lines, current?.lines ?? 0, signal)) {
23
+ signal?.throwIfAborted();
24
+ if (!row.bytes)
25
+ continue;
26
+ try {
27
+ const raw = object(JSON.parse(row.bytes.toString()));
28
+ if (raw.isSidechain === true || raw.isMeta === true)
29
+ continue;
30
+ const visible = visibleClaudeEvent(raw);
31
+ if (!visible || visible.phrenQueued === true || visible.phrenExecution === "background" || visible.isCompactSummary === true)
32
+ continue;
33
+ const message = object(visible.message), blocks = objects(message.content);
34
+ if (visible.type === "assistant") {
35
+ const assistant = String(message.id ?? raw.uuid ?? row.line);
36
+ for (const block of blocks)
37
+ if (block.type === "tool_use" && block.name === "AskUserQuestion" && typeof block.id === "string") {
38
+ const ask = { id: block.id, assistant, at: Date.parse(String(raw.timestamp)) };
39
+ if (movedOn(ask))
40
+ resolve(ask.id);
41
+ else if (!state.resolved.has(ask.id))
42
+ added.set(ask.id, ask);
43
+ }
44
+ if (assistants.size < 2)
45
+ assistants.add(assistant);
46
+ if (assistants.size === 2)
47
+ results.clear();
48
+ }
49
+ if (assistants.size < 2)
50
+ for (const block of blocks) {
51
+ if (block.type === "tool_result" && typeof block.tool_use_id === "string")
52
+ results.add(block.tool_use_id);
53
+ }
54
+ if (visible.type === "user" && (typeof message.content === "string"
55
+ || blocks.some(block => ["text", "image"].includes(String(block.type)))) && !blocks.some(block => block.type === "tool_result"))
56
+ owner = true;
57
+ }
58
+ catch { /* Partial/malformed records say nothing. */ }
59
+ }
60
+ for (const ask of state.pending.values())
61
+ if (movedOn(ask))
62
+ resolve(ask.id);
63
+ for (const [id, ask] of added)
64
+ if (!state.resolved.has(id))
65
+ state.pending.set(id, ask);
66
+ if (boundary !== undefined)
67
+ for (const ask of state.pending.values()) {
68
+ if (Number.isFinite(ask.at) && ask.at <= boundary)
69
+ resolve(ask.id);
70
+ }
71
+ states.delete(file);
72
+ states.set(file, state);
73
+ while (states.size > 32)
74
+ states.delete(states.keys().next().value);
75
+ return state.resolved;
76
+ }, signal);
77
+ }
78
+ /** An explicit resolution, never an invented answer. Keep it with the original
79
+ * question's stable row so backlog, reconnects and pagination agree. Existing
80
+ * clients already understand identity-matched tool_result blocks. */
81
+ export function projectClaudeQuestionResolutions(raw, resolved) {
82
+ const message = object(raw.message), blocks = objects(message.content);
83
+ const results = blocks.filter(block => block.type === "tool_use" && block.name === "AskUserQuestion"
84
+ && typeof block.id === "string" && resolved.has(block.id)).map(block => ({ type: "tool_result", tool_use_id: block.id,
85
+ is_error: true, content: "This question is no longer pending.", phren_resolution: true }));
86
+ return results.length ? { ...raw, message: { ...message, content: [...blocks, ...results] } } : raw;
87
+ }
@@ -6,6 +6,15 @@ export declare function codexThreadSessions(limit?: number, after?: string): Pro
6
6
  /** The materialized row retains its original turn, independently of whichever
7
7
  * turn happens to be active when search catches up. */
8
8
  export declare function codexTurnSettled(session: string, turn: string | null): Promise<boolean | undefined>;
9
+ /** One request's view of Codex's SQLite stores. Reusing the connections is what
10
+ * keeps discovery of hundreds of threads from paying an open/close per item. */
11
+ export interface CodexThreadStore {
12
+ sessions(limit?: number, after?: string): Promise<string[]>;
13
+ turnSettled(session: string, turn: string | null): Promise<boolean | undefined>;
14
+ materialize(session: string, deadline?: number, maxItems?: number): Promise<string | undefined>;
15
+ close(): Promise<void>;
16
+ }
17
+ export declare function openCodexThreadStore(): CodexThreadStore;
9
18
  /** A working pane whose projection cursor stopped at an unfinished turn can
10
19
  * keep accepting input even though none of it will be readable again. */
11
20
  export declare function threadHealth(session: string, agentStatus: unknown): Promise<{
@@ -1,4 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
+ import { statSync } from "node:fs";
2
3
  import { mkdir, open, readFile, rename, rm, stat } from "node:fs/promises";
3
4
  import { codexHome } from "../home-paths.js";
4
5
  import path from "node:path";
@@ -11,10 +12,67 @@ const OUTPUT_TAIL = 4_000;
11
12
  const STALLED_AFTER_MS = 10 * 60 * 1_000;
12
13
  export function materializedRoot() { return path.join(bridgeRoot(), "codex-threads"); }
13
14
  export function materializedPath(session) { return path.join(materializedRoot(), `${session}.jsonl`); }
14
- /** Codex 0.155 threads the SQLite store knows, by stable thread identity. Search
15
- * uses this to discover threads that have no rollout file to glob. */
16
- export async function codexThreadSessions(limit = 5_000, after = "") {
17
- const history = await openReadOnly(path.join(codexHome(), "thread_history_1.sqlite"));
15
+ const historyFile = () => path.join(codexHome(), "thread_history_1.sqlite");
16
+ async function openReadOnly(file) {
17
+ try {
18
+ const sqlite = await import("node:sqlite");
19
+ return new sqlite.DatabaseSync(file, { readOnly: true });
20
+ }
21
+ catch {
22
+ return undefined;
23
+ }
24
+ }
25
+ // Windows reports no usable inode and opens without FILE_SHARE_DELETE, so the file cannot be replaced while cached.
26
+ function fileIdentity(file) {
27
+ try {
28
+ const info = statSync(file);
29
+ return info.ino === 0 ? undefined : `${info.dev}:${info.ino}`;
30
+ }
31
+ catch {
32
+ return undefined;
33
+ }
34
+ }
35
+ /** The read-only Codex stores one request shares across every thread it
36
+ * discovers or materializes. Opening the same SQLite file per thread is a real
37
+ * per-item cost, especially on Windows. A replaced or rotated file is
38
+ * detected once per get() and reopened rather than read through the old handle. */
39
+ class ReadOnlyConnections {
40
+ connections = new Map();
41
+ opening = new Map();
42
+ async get(file) {
43
+ const identity = fileIdentity(file);
44
+ const cached = this.connections.get(file);
45
+ if (cached && (identity === undefined || cached.identity === identity))
46
+ return cached.db;
47
+ if (cached) {
48
+ cached.db?.close();
49
+ this.connections.delete(file);
50
+ }
51
+ let opening = this.opening.get(file);
52
+ if (!opening) {
53
+ opening = openReadOnly(file).then(db => ({ identity, db }));
54
+ this.opening.set(file, opening);
55
+ }
56
+ const opened = await opening;
57
+ this.opening.delete(file);
58
+ const current = this.connections.get(file);
59
+ if (current && (identity === undefined || current.identity === identity))
60
+ return current.db;
61
+ current?.db?.close();
62
+ this.connections.set(file, opened);
63
+ return opened.db;
64
+ }
65
+ async close() {
66
+ const opening = [...this.opening.values()];
67
+ this.opening.clear();
68
+ for (const { db } of this.connections.values())
69
+ db?.close();
70
+ this.connections.clear();
71
+ for (const { db } of await Promise.all(opening))
72
+ db?.close();
73
+ }
74
+ }
75
+ async function sessionsFrom(history, limit, after) {
18
76
  if (!history)
19
77
  return [];
20
78
  try {
@@ -25,18 +83,21 @@ export async function codexThreadSessions(limit = 5_000, after = "") {
25
83
  catch {
26
84
  return [];
27
85
  }
86
+ }
87
+ /** Codex 0.155 threads the SQLite store knows, by stable thread identity. Search
88
+ * uses this to discover threads that have no rollout file to glob. */
89
+ export async function codexThreadSessions(limit = 5_000, after = "") {
90
+ const connections = new ReadOnlyConnections();
91
+ try {
92
+ return await sessionsFrom(await connections.get(historyFile()), limit, after);
93
+ }
28
94
  finally {
29
- history.close();
95
+ await connections.close();
30
96
  }
31
97
  }
32
- /** The materialized row retains its original turn, independently of whichever
33
- * turn happens to be active when search catches up. */
34
- export async function codexTurnSettled(session, turn) {
35
- const history = await openReadOnly(path.join(codexHome(), "thread_history_1.sqlite"));
36
- if (!history || !turn) {
37
- history?.close();
98
+ async function turnSettledFrom(history, session, turn) {
99
+ if (!history || !turn)
38
100
  return undefined;
39
- }
40
101
  try {
41
102
  const row = object(history.prepare("select status from thread_turns where thread_id = ? and turn_id = ?").get(session, turn));
42
103
  return typeof row.status === "string" ? row.status !== "inProgress" : undefined;
@@ -44,20 +105,27 @@ export async function codexTurnSettled(session, turn) {
44
105
  catch {
45
106
  return undefined;
46
107
  }
47
- finally {
48
- history.close();
49
- }
50
108
  }
51
- async function openReadOnly(file) {
109
+ /** The materialized row retains its original turn, independently of whichever
110
+ * turn happens to be active when search catches up. */
111
+ export async function codexTurnSettled(session, turn) {
112
+ const connections = new ReadOnlyConnections();
52
113
  try {
53
- await stat(file);
54
- const sqlite = await import("node:sqlite");
55
- return new sqlite.DatabaseSync(file, { readOnly: true });
114
+ return await turnSettledFrom(await connections.get(historyFile()), session, turn);
56
115
  }
57
- catch {
58
- return undefined;
116
+ finally {
117
+ await connections.close();
59
118
  }
60
119
  }
120
+ export function openCodexThreadStore() {
121
+ const connections = new ReadOnlyConnections();
122
+ return {
123
+ sessions: async (limit = 5_000, after = "") => sessionsFrom(await connections.get(historyFile()), limit, after),
124
+ turnSettled: async (session, turn) => turnSettledFrom(await connections.get(historyFile()), session, turn),
125
+ materialize: (session, deadline = Infinity, maxItems = Infinity) => runMaterialization(session, deadline, maxItems, connections),
126
+ close: () => connections.close(),
127
+ };
128
+ }
61
129
  /** A working pane whose projection cursor stopped at an unfinished turn can
62
130
  * keep accepting input even though none of it will be readable again. */
63
131
  export async function threadHealth(session, agentStatus) {
@@ -139,17 +207,16 @@ export async function codexThreadPreview(session) {
139
207
  history.close();
140
208
  }
141
209
  }
142
- /** Bring the materialized file up to date with the store. Returns the file
143
- * when the thread exists there, undefined otherwise. Safe to call often:
144
- * an unchanged thread costs one aggregate query. */
145
- export async function materializeCodexThread(session, deadline = Infinity, maxItems = Infinity) {
210
+ async function runMaterialization(session, deadline, maxItems, shared) {
146
211
  if (!sessionId.safeParse(session).success)
147
212
  return undefined;
148
213
  const key = materializedPath(session);
149
214
  const pending = materializations.get(key);
150
215
  if (pending)
151
216
  return pending;
152
- const work = materializeThread(session, deadline, maxItems);
217
+ const connections = shared ?? new ReadOnlyConnections();
218
+ const work = materializeThread(session, deadline, maxItems, connections)
219
+ .finally(() => shared ? undefined : connections.close());
153
220
  materializations.set(key, work);
154
221
  try {
155
222
  return await work;
@@ -158,10 +225,16 @@ export async function materializeCodexThread(session, deadline = Infinity, maxIt
158
225
  materializations.delete(key);
159
226
  }
160
227
  }
161
- async function materializeThread(session, deadline, maxItems) {
228
+ /** Bring the materialized file up to date with the store. Returns the file
229
+ * when the thread exists there, undefined otherwise. Safe to call often:
230
+ * an unchanged thread costs one aggregate query. */
231
+ export async function materializeCodexThread(session, deadline = Infinity, maxItems = Infinity) {
232
+ return runMaterialization(session, deadline, maxItems);
233
+ }
234
+ async function materializeThread(session, deadline, maxItems, connections) {
162
235
  if (!sessionId.safeParse(session).success)
163
236
  return undefined;
164
- const history = await openReadOnly(path.join(codexHome(), "thread_history_1.sqlite"));
237
+ const history = await connections.get(historyFile());
165
238
  if (!history)
166
239
  return undefined;
167
240
  try {
@@ -217,7 +290,7 @@ async function materializeThread(session, deadline, maxItems) {
217
290
  const stamps = new Map();
218
291
  const lines = [];
219
292
  if (fresh) {
220
- const meta = await threadMeta(session);
293
+ const meta = await threadMeta(session, connections);
221
294
  lines.push(JSON.stringify({ type: "session_meta", payload: { id: session, ...(meta.cwd ? { cwd: meta.cwd } : {}),
222
295
  source: meta.spawn ? { subagent: { thread_spawn: meta.spawn } } : "codex-thread-store" } }));
223
296
  if (meta.model)
@@ -376,9 +449,6 @@ async function materializeThread(session, deadline, maxItems) {
376
449
  catch {
377
450
  return undefined;
378
451
  }
379
- finally {
380
- history.close();
381
- }
382
452
  }
383
453
  /** The thread's items in order, with when each was created where the store records it (`created_at_ms`, absent
384
454
  * from some stores) and its turn. */
@@ -434,8 +504,8 @@ function subAgentRow(item) {
434
504
  agent_thread_id: child, agent_path: String(item.agentPath ?? item.agent_path ?? ""),
435
505
  } } };
436
506
  }
437
- async function threadMeta(session) {
438
- const db = await openReadOnly(path.join(codexHome(), "state_5.sqlite"));
507
+ async function threadMeta(session, connections) {
508
+ const db = await connections.get(path.join(codexHome(), "state_5.sqlite"));
439
509
  if (!db)
440
510
  return {};
441
511
  try {
@@ -456,9 +526,6 @@ async function threadMeta(session) {
456
526
  catch {
457
527
  return {};
458
528
  }
459
- finally {
460
- db.close();
461
- }
462
529
  }
463
530
  function finished(item) { return ["completed", "failed", "declined", "error"].includes(String(item.status)) || item.exitCode !== undefined && item.exitCode !== null; }
464
531
  function queueKey(session, id) {
@@ -4,7 +4,7 @@ import path from "node:path";
4
4
  import { claudeHomes } from "./claude-accounts.js";
5
5
  import { codexHome, copilotHome } from "../home-paths.js";
6
6
  import { redactSecretsForLog } from "../content/secrets.js";
7
- import { codexThreadSessions, codexTurnSettled, materializeCodexThread, materializedPath, materializedRoot } from "./codex-threads.js";
7
+ import { openCodexThreadStore, materializedPath, materializedRoot } from "./codex-threads.js";
8
8
  import { paneIdentity, snapshot, recentServers } from "./herdr.js";
9
9
  import { BridgeError, bridgeRoot, object, objects, sessionId } from "./protocol.js";
10
10
  import { phrenStoreRoot, selectTranscriptMatch, visibleEvent } from "./transcripts.js";
@@ -185,8 +185,13 @@ async function openIndex() {
185
185
  db.exec("PRAGMA busy_timeout = 50");
186
186
  db.exec("PRAGMA journal_mode = WAL");
187
187
  db.exec("PRAGMA synchronous = NORMAL");
188
- db.exec(SCHEMA);
189
- db.exec("PRAGMA user_version = 2");
188
+ // The schema only changes with the version above. Re-running every CREATE
189
+ // TABLE/INDEX on each search is avoidable SQLite parse work, noticeable on
190
+ // Windows where the index is opened once per request.
191
+ if (version !== 2) {
192
+ db.exec(SCHEMA);
193
+ db.exec("PRAGMA user_version = 2");
194
+ }
190
195
  return db;
191
196
  }
192
197
  function metaValue(db, key) {
@@ -263,7 +268,7 @@ async function deleteFile(db, file, deadline) {
263
268
  }
264
269
  /** Publication is a durable job: neither a large turn nor a large vocabulary
265
270
  * must finish in the request that discovers its end marker. */
266
- async function commitPending(db, row, state, deadline) {
271
+ async function commitPending(db, row, state, deadline, codex) {
267
272
  db.exec("BEGIN");
268
273
  try {
269
274
  db.prepare("UPDATE files SET publishing = 1 WHERE path = ?").run(row.path);
@@ -276,7 +281,7 @@ async function commitPending(db, row, state, deadline) {
276
281
  db.prepare("UPDATE files SET publishing = 0, publication_seq = -1 WHERE path = ?").run(row.path);
277
282
  return;
278
283
  }
279
- const settled = materializedFile(row.path) && !item.queued ? await codexTurnSettled(row.session, item.turn_id) : false;
284
+ const settled = materializedFile(row.path) && !item.queued ? await codex.turnSettled(row.session, item.turn_id) : false;
280
285
  if (item.queued || (materializedFile(row.path) ? settled !== true : item.settle_after > (rowFor(db, row.path)?.ready_until ?? -1))) {
281
286
  if (materializedFile(row.path) && !item.queued && settled === undefined)
282
287
  db.prepare("UPDATE files SET unresolved = 1 WHERE path = ?").run(row.path);
@@ -434,11 +439,11 @@ async function discoverDirectories(db, deadline) {
434
439
  }
435
440
  return !!db.prepare("SELECT 1 FROM dirs LIMIT 1").get();
436
441
  }
437
- async function discoverSqliteThreads(db, deadline) {
442
+ async function discoverSqliteThreads(db, deadline, codex) {
438
443
  let after = metaValue(db, "sqlite_after") ?? "";
439
444
  if (!after && Date.now() - Number(metaValue(db, "sqlite_cycle") ?? "0") < DISCOVERY_RESCAN_MS)
440
445
  return false;
441
- const threads = await codexThreadSessions(128, after).catch(() => []);
446
+ const threads = await codex.sessions(128, after).catch(() => []);
442
447
  for (const thread of threads) {
443
448
  if (Date.now() >= deadline)
444
449
  return true;
@@ -458,7 +463,7 @@ function updateChecked(db, file) {
458
463
  setMeta(db, "check_clock", String(tick));
459
464
  db.prepare("UPDATE files SET checked_at = ? WHERE path = ?").run(tick, file);
460
465
  }
461
- async function processRow(db, row, line, lineNumber, state, fallbackAt, deadline) {
466
+ async function processRow(db, row, line, lineNumber, state, fallbackAt, deadline, codex) {
462
467
  if (!line.trim())
463
468
  return;
464
469
  let raw;
@@ -484,11 +489,11 @@ async function processRow(db, row, line, lineNumber, state, fallbackAt, deadline
484
489
  }
485
490
  if (turnEnded(raw, row.source, state.copilotFinal)) {
486
491
  db.prepare("UPDATE files SET ready_until = ? WHERE path = ?").run(lineNumber, row.path);
487
- await commitPending(db, row, state, deadline);
492
+ await commitPending(db, row, state, deadline, codex);
488
493
  state.copilotFinal = false;
489
494
  }
490
495
  }
491
- async function scanFile(db, row, info, budget, deadline) {
496
+ async function scanFile(db, row, info, budget, deadline, codex) {
492
497
  const sidecar = sidecarPath(row.path), sidecarInfo = await stat(sidecar).catch(() => undefined);
493
498
  let replacement = row.size === null || row.dev !== String(info.dev) || row.ino !== String(info.ino)
494
499
  || info.size < Math.max(row.offset, row.scan_offset ?? 0)
@@ -559,7 +564,7 @@ async function scanFile(db, row, info, budget, deadline) {
559
564
  position += newline;
560
565
  break;
561
566
  }
562
- await processRow(db, row, line, lines, state, fallbackAt, deadline);
567
+ await processRow(db, row, line, lines, state, fallbackAt, deadline, codex);
563
568
  }
564
569
  lines++;
565
570
  chunkStart = position + newline + 1;
@@ -571,7 +576,7 @@ async function scanFile(db, row, info, budget, deadline) {
571
576
  }
572
577
  let newline;
573
578
  while (Date.now() < deadline && (newline = chunk.indexOf(10, begin)) >= 0) {
574
- await processRow(db, row, chunk.subarray(begin, newline).toString("utf8"), lines, state, fallbackAt, deadline);
579
+ await processRow(db, row, chunk.subarray(begin, newline).toString("utf8"), lines, state, fallbackAt, deadline, codex);
575
580
  lines++;
576
581
  chunkStart += newline + 1 - begin;
577
582
  offset = chunkStart;
@@ -600,14 +605,14 @@ async function scanFile(db, row, info, budget, deadline) {
600
605
  sidecarBytes = pending.length;
601
606
  scanningRow = 1;
602
607
  }
603
- await commitPending(db, row, state, deadline);
608
+ await commitPending(db, row, state, deadline, codex);
604
609
  const complete = offset >= info.size && scanningRow === 0;
605
610
  db.prepare(`UPDATE files SET size = ?, mtime_ms = ?, dev = ?, ino = ?, offset = ?, scan_offset = ?,
606
611
  scanning_row = ?, lines = ?, title = ?, cwd = ?, last_at = ?, copilot_final = ? WHERE path = ?`)
607
612
  .run(info.size, info.mtimeMs, String(info.dev), String(info.ino), offset, scanningRow ? position : offset, scanningRow, lines, state.title ?? title, state.cwd ?? cwd, state.lastAt ?? lastAt, state.copilotFinal ? 1 : 0, row.path);
608
613
  return { bytes: bytesRead, complete };
609
614
  }
610
- async function refreshFile(db, row, budget, deadline) {
615
+ async function refreshFile(db, row, budget, deadline, codex) {
611
616
  if (Date.now() >= deadline || budget.checked >= MAX_STAT_FILES || budget.scanned >= MAX_SCAN_FILES || budget.bytes >= MAX_BYTES_PER_REQUEST) {
612
617
  budget.partial = true;
613
618
  return;
@@ -637,20 +642,20 @@ async function refreshFile(db, row, budget, deadline) {
637
642
  && row.ino === String(info.ino) && row.offset >= info.size && row.scanning_row === 0;
638
643
  try {
639
644
  if (!unchanged) {
640
- const result = await scanFile(db, row, info, MAX_BYTES_PER_REQUEST - budget.bytes, deadline);
645
+ const result = await scanFile(db, row, info, MAX_BYTES_PER_REQUEST - budget.bytes, deadline, codex);
641
646
  budget.bytes += result.bytes;
642
647
  budget.scanned++;
643
648
  if (!result.complete)
644
649
  budget.partial = true;
645
650
  }
646
651
  else
647
- await commitPending(db, row, { title: row.title, cwd: row.cwd, lastAt: row.last_at, copilotFinal: false }, deadline);
652
+ await commitPending(db, row, { title: row.title, cwd: row.cwd, lastAt: row.last_at, copilotFinal: false }, deadline, codex);
648
653
  }
649
654
  catch {
650
655
  budget.partial = true;
651
656
  }
652
657
  }
653
- async function refreshFiles(db, deadline) {
658
+ async function refreshFiles(db, deadline, codex) {
654
659
  const budget = { partial: false, checked: 0, scanned: 0, bytes: 0 };
655
660
  const first = metaValue(db, "refresh_first") ?? "materialize";
656
661
  setMeta(db, "refresh_first", first === "materialize" ? "files" : "materialize");
@@ -669,7 +674,7 @@ async function refreshFiles(db, deadline) {
669
674
  budget.partial = true;
670
675
  break;
671
676
  }
672
- const file = await materializeCodexThread(row.session, deadline, 128).catch(() => undefined);
677
+ const file = await codex.materialize(row.session, deadline, 128).catch(() => undefined);
673
678
  const tick = Number(metaValue(db, "materialize_clock") ?? "0") + 1;
674
679
  setMeta(db, "materialize_clock", String(tick));
675
680
  db.prepare("UPDATE files SET materialized_at = ? WHERE path = ?").run(tick, row.path);
@@ -682,7 +687,7 @@ async function refreshFiles(db, deadline) {
682
687
  budget.partial = true;
683
688
  // If materialization ran second, index its new tail in this request
684
689
  // too, using the same total file/byte allowance as ordinary refresh.
685
- await refreshFile(db, rowFor(db, row.path) ?? row, budget, deadline);
690
+ await refreshFile(db, rowFor(db, row.path) ?? row, budget, deadline, codex);
686
691
  }
687
692
  }
688
693
  else {
@@ -695,7 +700,7 @@ async function refreshFiles(db, deadline) {
695
700
  budget.partial = true;
696
701
  break;
697
702
  }
698
- await refreshFile(db, row, budget, deadline);
703
+ await refreshFile(db, row, budget, deadline, codex);
699
704
  }
700
705
  }
701
706
  }
@@ -812,11 +817,12 @@ async function search(q, limit, cursor) {
812
817
  const tokens = textTokens(query);
813
818
  const deadline = Date.now() + MAX_REQUEST_MS;
814
819
  const db = await openIndex();
820
+ const codex = openCodexThreadStore();
815
821
  try {
816
822
  const discoveryPartial = await discoverDirectories(db, deadline);
817
- const sqlitePartial = Date.now() < deadline ? await discoverSqliteThreads(db, deadline) : true;
823
+ const sqlitePartial = Date.now() < deadline ? await discoverSqliteThreads(db, deadline, codex) : true;
818
824
  const pruningPartial = Date.now() < deadline ? await pruneIndex(db, deadline) : true;
819
- const indexingPartial = Date.now() < deadline ? await refreshFiles(db, deadline) : true;
825
+ const indexingPartial = Date.now() < deadline ? await refreshFiles(db, deadline, codex) : true;
820
826
  let partial = discoveryPartial || sqlitePartial || indexingPartial || pruningPartial;
821
827
  if (!tokens.length)
822
828
  return { results: [], cursor: null, ...(partial ? { partial: true } : {}) };
@@ -915,6 +921,7 @@ async function search(q, limit, cursor) {
915
921
  };
916
922
  }
917
923
  finally {
924
+ await codex.close();
918
925
  db.close();
919
926
  }
920
927
  }
@@ -0,0 +1,5 @@
1
+ /** Discovery is frequent by default; an owner can still cap polling explicitly.
2
+ * Confirmation has its own small, fixed budget, independent of that cap. */
3
+ export declare const DIALOG_READ_MS: number;
4
+ export declare const DIALOG_CONFIRM_MS = 300;
5
+ export declare function confirmDialogRead<T>(read: () => Promise<T>, current: () => boolean): Promise<T | undefined>;
@@ -0,0 +1,20 @@
1
+ import { intervalFromEnv } from "./limits.js";
2
+ /** Discovery is frequent by default; an owner can still cap polling explicitly.
3
+ * Confirmation has its own small, fixed budget, independent of that cap. */
4
+ export const DIALOG_READ_MS = intervalFromEnv("PHREN_DIALOG_THROTTLE_MS", 350);
5
+ export const DIALOG_CONFIRM_MS = 300;
6
+ const CONFIRM_READ_MS = 400;
7
+ export async function confirmDialogRead(read, current) {
8
+ await new Promise(resolve => setTimeout(resolve, DIALOG_CONFIRM_MS));
9
+ if (!current())
10
+ return undefined;
11
+ let timer;
12
+ try {
13
+ return await Promise.race([read().catch(() => undefined), new Promise(resolve => {
14
+ timer = setTimeout(() => resolve(undefined), CONFIRM_READ_MS);
15
+ })]);
16
+ }
17
+ finally {
18
+ clearTimeout(timer);
19
+ }
20
+ }