@phren/cli 0.3.8 → 0.3.9

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.
@@ -95,6 +95,10 @@ export async function answerClaudeQuestionDialog(io, questions, answers, options
95
95
  await sleep(120);
96
96
  }
97
97
  };
98
+ // After a key that answers, Claude may take seconds to redraw on a busy
99
+ // computer; the answer was taken, so wait for the redraw instead of
100
+ // calling it refused (the phone would say it was not confirmed).
101
+ const ANSWERED_MS = 8_000;
98
102
  const initial = await settle(screen => screen);
99
103
  if (!initial)
100
104
  throw changed("The terminal is not showing Claude's question.");
@@ -146,7 +150,7 @@ export async function answerClaudeQuestionDialog(io, questions, answers, options
146
150
  else {
147
151
  await io.keys([String(screen.options[answer.options[0]].number)]);
148
152
  }
149
- if (!await settle(leaves(index)))
153
+ if (!await settle(leaves(index), ANSWERED_MS))
150
154
  throw changed("The terminal did not take the answer.");
151
155
  continue;
152
156
  }
@@ -189,12 +193,12 @@ export async function answerClaudeQuestionDialog(io, questions, answers, options
189
193
  // Tab from the typed row would stop on Next instead of leaving.
190
194
  await io.keys(screen.other && screen.cursor === screen.other.number ? ["up", "tab"] : ["tab"]);
191
195
  }
192
- if (!await settle(leaves(index)))
196
+ if (!await settle(leaves(index), ANSWERED_MS))
193
197
  throw changed("The terminal did not move past the question.");
194
198
  }
195
199
  if (!submit)
196
200
  return;
197
- const review = await settle(value => value?.kind === "review" ? value : value === undefined ? "gone" : undefined);
201
+ const review = await settle(value => value?.kind === "review" ? value : value === undefined ? "gone" : undefined, ANSWERED_MS);
198
202
  // A lone single-select question submits on its digit.
199
203
  if (review === "gone")
200
204
  return;
@@ -205,6 +209,6 @@ export async function answerClaudeQuestionDialog(io, questions, answers, options
205
209
  throw changed("Not every question has an answer in the terminal.");
206
210
  }
207
211
  await io.keys(["1"]);
208
- if (await settle(value => value === undefined ? "gone" : undefined) !== "gone")
212
+ if (await settle(value => value === undefined ? "gone" : undefined, ANSWERED_MS) !== "gone")
209
213
  throw changed("The terminal did not submit the answers.");
210
214
  }
@@ -0,0 +1,11 @@
1
+ /** The `codex` the Hook runs for its own helper calls (`codex queue`, `codex
2
+ * app-server`). `phren init` can put a session wrapper at ~/.local/bin/codex
3
+ * that runs phren's session-start hook before the real binary for every
4
+ * subcommand except a bare --help. That takes seconds (about 8 s on the Linux
5
+ * box), longer than the Hook's 5 s `codex queue --help` probe, so Codex async
6
+ * questions were reported as terminal-only, and each call opened a phren
7
+ * session. The Hook skips its own wrapper and runs the binary it names. */
8
+ export declare function codexExecutable(env?: NodeJS.ProcessEnv): string;
9
+ /** The real binary a phren session wrapper names, "" for a phren wrapper
10
+ * whose target cannot be read, undefined for anything else. */
11
+ export declare function phrenWrapperTarget(file: string): string | undefined;
@@ -0,0 +1,58 @@
1
+ import { accessSync, closeSync, constants, openSync, readSync, statSync } from "node:fs";
2
+ import path from "node:path";
3
+ /** The `codex` the Hook runs for its own helper calls (`codex queue`, `codex
4
+ * app-server`). `phren init` can put a session wrapper at ~/.local/bin/codex
5
+ * that runs phren's session-start hook before the real binary for every
6
+ * subcommand except a bare --help. That takes seconds (about 8 s on the Linux
7
+ * box), longer than the Hook's 5 s `codex queue --help` probe, so Codex async
8
+ * questions were reported as terminal-only, and each call opened a phren
9
+ * session. The Hook skips its own wrapper and runs the binary it names. */
10
+ export function codexExecutable(env = process.env) {
11
+ if (process.platform === "win32")
12
+ return "codex";
13
+ for (const directory of (env.PATH ?? "").split(path.delimiter)) {
14
+ if (!path.isAbsolute(directory))
15
+ continue;
16
+ const candidate = path.join(directory, "codex");
17
+ if (!executable(candidate))
18
+ continue;
19
+ const wrapped = phrenWrapperTarget(candidate);
20
+ if (wrapped === undefined)
21
+ return candidate;
22
+ if (wrapped && executable(wrapped))
23
+ return wrapped;
24
+ }
25
+ return "codex";
26
+ }
27
+ function executable(file) {
28
+ try {
29
+ return statSync(file).isFile() && (accessSync(file, constants.X_OK), true);
30
+ }
31
+ catch {
32
+ return false;
33
+ }
34
+ }
35
+ /** The real binary a phren session wrapper names, "" for a phren wrapper
36
+ * whose target cannot be read, undefined for anything else. */
37
+ export function phrenWrapperTarget(file) {
38
+ let head = "";
39
+ try {
40
+ const fd = openSync(file, "r");
41
+ try {
42
+ const buffer = Buffer.alloc(4096);
43
+ head = buffer.subarray(0, readSync(fd, buffer, 0, buffer.length, 0)).toString("utf8");
44
+ }
45
+ finally {
46
+ closeSync(fd);
47
+ }
48
+ }
49
+ catch {
50
+ return undefined;
51
+ }
52
+ if (!head.startsWith("#!/bin/sh") || !head.includes("phren wrapper error:"))
53
+ return undefined;
54
+ // shellEscape in hooks.ts: single quotes, an embedded quote written '\''.
55
+ const match = /^REAL_BIN='((?:[^']|'\\'')*)'$/m.exec(head);
56
+ const target = match?.[1].replace(/'\\''/g, "'");
57
+ return target && path.isAbsolute(target) ? target : "";
58
+ }
@@ -4,8 +4,9 @@ import { homedir } from "node:os";
4
4
  import { claudeConfigDir } from "../home-paths.js";
5
5
  import path from "node:path";
6
6
  import { object, objects } from "./protocol.js";
7
+ import { codexExecutable } from "./codex-binary.js";
7
8
  /** Only initialize and list. Never a thread, a prompt, or a login. */
8
- export function readCodexModels(executable = "codex") {
9
+ export function readCodexModels(executable = codexExecutable()) {
9
10
  return new Promise(resolve => {
10
11
  const child = spawn(executable, ["app-server"], { cwd: homedir(), stdio: ["pipe", "pipe", "ignore"] });
11
12
  let pending = "", bytes = 0, initialized = false, done = false;
@@ -23,14 +23,16 @@ interface PendingQuestion {
23
23
  export declare function pendingAsyncQuestions(file: string, targetID?: string): Promise<PendingQuestion[]>;
24
24
  export declare function pendingAsyncQuestion(file: string, id: string): Promise<Question[]>;
25
25
  export declare class CodexQuestions {
26
- private executable;
26
+ private readonly configured?;
27
27
  private snapshots;
28
28
  private failedSnapshots;
29
29
  private inboxAvailable;
30
30
  /** Feature discovery must never delay permission/status frames. */
31
31
  get available(): boolean;
32
32
  private probe?;
33
- constructor(executable?: string);
33
+ /** No executable: the real `codex` on PATH, past phren's session wrapper. */
34
+ constructor(configured?: string | undefined);
35
+ private get executable();
34
36
  supported(): Promise<boolean>;
35
37
  pending(target: Target): Promise<Json[]>;
36
38
  answer(target: Target, data: Json): Promise<void>;
@@ -7,6 +7,7 @@ import { z } from "zod";
7
7
  import { BridgeError, bridgeRoot, object, objects } from "./protocol.js";
8
8
  import { paneIdentity, validateTarget } from "./herdr.js";
9
9
  import { transcriptPath } from "./transcripts.js";
10
+ import { codexExecutable } from "./codex-binary.js";
10
11
  import { withTranscriptIndex } from "./transcript-index.js";
11
12
  const exec = promisify(execFile);
12
13
  const text = z.string().trim().min(1).max(4000).refine(t => !/[\x00-\x08\x0b-\x1f\x7f]/.test(t));
@@ -68,7 +69,7 @@ const answersQuestions = (reply, questions) => questions.every(q => {
68
69
  });
69
70
  export async function pendingAsyncQuestions(file, targetID) {
70
71
  return withTranscriptIndex(file, async (handle, index) => {
71
- const replies = [], acknowledged = new Set(), resolved = new Set(), pending = [];
72
+ const replies = [], acknowledged = new Set(), resolved = new Set(), seen = new Set(), pending = [];
72
73
  let bytes = 0;
73
74
  for await (const row of index.rows(handle, index.lines, Math.max(0, index.lines - 10_000))) {
74
75
  // An incomplete scan is not evidence that no questions remain. Status
@@ -106,11 +107,15 @@ export async function pendingAsyncQuestions(file, targetID) {
106
107
  if (!id || !acknowledged.has(id))
107
108
  continue;
108
109
  const questions = asyncQuestion(raw, id);
109
- if (questions && !replies.some(reply => answersQuestions(reply, questions))) {
110
+ // Codex 0.155 records one question twice under the same id: the
111
+ // request_user_input_async call and the AgentMessage delivered async.
112
+ if (questions && !seen.has(id) && !replies.some(reply => answersQuestions(reply, questions))) {
110
113
  pending.push({ id, questions });
111
114
  if (pending.length >= 64)
112
115
  throw new BridgeError(413, "Too many pending questions to verify.");
113
116
  }
117
+ if (questions)
118
+ seen.add(id);
114
119
  if (targetID && questions && id === targetID)
115
120
  return pending.filter(p => p.id === targetID);
116
121
  }
@@ -126,16 +131,18 @@ export async function pendingAsyncQuestion(file, id) {
126
131
  return pending.questions;
127
132
  }
128
133
  export class CodexQuestions {
129
- executable;
134
+ configured;
130
135
  snapshots = new Map();
131
136
  failedSnapshots = new Map();
132
137
  inboxAvailable = false;
133
138
  /** Feature discovery must never delay permission/status frames. */
134
139
  get available() { void this.supported(); return this.inboxAvailable; }
135
140
  probe;
136
- constructor(executable = "codex") {
137
- this.executable = executable;
141
+ /** No executable: the real `codex` on PATH, past phren's session wrapper. */
142
+ constructor(configured) {
143
+ this.configured = configured;
138
144
  }
145
+ get executable() { return this.configured ?? codexExecutable(); }
139
146
  supported() {
140
147
  if (!this.probe || Date.now() - this.probe.at > 300_000)
141
148
  this.probe = { at: Date.now(), result: exec(this.executable, ["queue", "--help"], { timeout: 5000, maxBuffer: 65_536 })
@@ -8,6 +8,7 @@ import { promisify } from "node:util";
8
8
  import { fanoutRoot } from "./fanouts.js";
9
9
  import { atomicInPrivateDir, bridgeRoot, object } from "./protocol.js";
10
10
  import { stripTerminal } from "../terminal-text.js";
11
+ import { codexExecutable } from "./codex-binary.js";
11
12
  const exec = promisify(execFile);
12
13
  const claudeFile = () => path.join(bridgeRoot(), "usage", "claude.json");
13
14
  const safeText = (v) => typeof v === "string" ? v.replace(/[\x00-\x1f\x7f]/g, "").slice(0, 100) : undefined;
@@ -648,7 +649,7 @@ async function liveClaudeUsage(now) {
648
649
  }
649
650
  }
650
651
  /** Only initialize and read limits. Never create a thread, prompt, or login. */
651
- export function readCodexLimits(executable = "codex") {
652
+ export function readCodexLimits(executable = codexExecutable()) {
652
653
  return new Promise(resolve => {
653
654
  const child = spawn(executable, ["app-server"], { cwd: homedir(), stdio: ["pipe", "pipe", "ignore"] });
654
655
  let pending = "", bytes = 0, initialized = false, done = false;