@phren/cli 0.3.52 → 0.3.53

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.
@@ -26,6 +26,7 @@ import { optionalHookPeers } from "./peers.js";
26
26
  import { AppServerRpcError, AppServerUnsupportedError } from "./codex-app-server.js";
27
27
  import { codexAppServerEnabled, codexServers } from "./codex-servers.js";
28
28
  import { logger } from "../logger.js";
29
+ import { stripTerminal } from "../terminal-text.js";
29
30
  import { JobRegistry } from "./job-registry.js";
30
31
  import { atomic, BridgeError, id, launchEfforts, objects, PERMISSION_MODES, provider } from "./protocol.js";
31
32
  import { CLAUDE_NAMES, CODEX_MODES, codexModeFlags, copilotModeFlags } from "./settings-switch.js";
@@ -237,6 +238,61 @@ async function startWhenShellReady(server, pane, agent) {
237
238
  }
238
239
  }
239
240
  }
241
+ /** Retry only a demonstrated exit, and serialize starters: neither terminal
242
+ * provider supports cancelling a start already submitted to its server. */
243
+ async function startCodex(server, pane, agent) {
244
+ const terminal = terminalProvider();
245
+ const screenText = async () => stripTerminal(await terminal.readScreen?.(server, pane, { scope: "pane", source: "recent", lines: 20 }).catch(() => "") ?? "").trim();
246
+ for (let attempt = 0; attempt < 2; attempt++) {
247
+ const before = await screenText();
248
+ const deadline = Date.now() + agent.timeoutMs;
249
+ let ran = false;
250
+ let result;
251
+ const starting = startWhenShellReady(server, pane, agent).then(() => { result = {}; ran = true; }, error => { result = { error }; });
252
+ try {
253
+ for (;;) {
254
+ await Promise.race([starting, new Promise(resolve => setTimeout(resolve, 250))]);
255
+ const processes = await terminal.processes?.(server, pane).catch(() => undefined);
256
+ const state = await terminal.snapshot(server);
257
+ const current = objects(state.panes).find(row => row.pane_id === pane);
258
+ const shell = processes?.shellPid;
259
+ const atShell = processes !== undefined && shell !== undefined && processes.foregroundPids.every(pid => pid === shell);
260
+ if (processes && !atShell && current?.agent === "codex")
261
+ ran = true;
262
+ if (atShell) {
263
+ const screen = await screenText();
264
+ const exitMessage = screen !== before && /please restart codex|codex exited(?: at start)?/i.test(screen);
265
+ if (ran || exitMessage) {
266
+ // A screen or process observation cannot cancel a pending start.
267
+ // Wait for it, then observe again: it might still launch Codex.
268
+ if (!result) {
269
+ await starting;
270
+ continue;
271
+ }
272
+ if (attempt === 0)
273
+ break;
274
+ const last = screen.split(/\r?\n/).map(line => line.trim()).filter(Boolean).at(-1);
275
+ throw new BridgeError(409, `Codex exited at start: ${last || "process returned to its shell"}`);
276
+ }
277
+ }
278
+ if (result && "error" in result)
279
+ throw result.error;
280
+ if (result) {
281
+ if (!processes || ["idle", "working", "blocked", "waiting"].includes(String(current?.agent_status)) || Date.now() >= deadline)
282
+ return;
283
+ await new Promise(resolve => setTimeout(resolve, 250));
284
+ }
285
+ else if (Date.now() >= deadline) {
286
+ await starting;
287
+ }
288
+ }
289
+ }
290
+ finally {
291
+ // Even a failed process/snapshot read must not leave a starter behind.
292
+ await starting;
293
+ }
294
+ }
295
+ }
240
296
  /** The Herdr agent-name slug for a human label: "Conductor smoke 4" becomes "conductor-smoke-4". */
241
297
  export function herdrAgentName(label) {
242
298
  const slug = label.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^[^a-z]+/, "").replace(/-+$/, "").slice(0, 32).replace(/-+$/, "");
@@ -494,13 +550,16 @@ async function startSession(server, data, options) {
494
550
  briefTurn = error instanceof AppServerRpcError ? undefined : "uncertain";
495
551
  }
496
552
  }
497
- const agentArgs = structuredLaunch ? structuredLaunch.args : [...args, ...(briefLaunch ?? [])];
553
+ const agentArgs = [...(structuredLaunch ? structuredLaunch.args : [...args, ...(briefLaunch ?? [])]),
554
+ ...(kind === "codex" ? ["-c", "check_for_update_on_startup=false"] : [])];
498
555
  try {
499
- await startWhenShellReady(server, created.paneId, { name, kind, args: agentArgs, timeoutMs: timeout, ...(env ? { env } : {}) });
556
+ await (kind === "codex" ? startCodex : startWhenShellReady)(server, created.paneId, { name, kind, args: agentArgs, timeoutMs: timeout, ...(env ? { env } : {}) });
500
557
  }
501
558
  catch (error) {
502
559
  if (appServer && !agentNotReady(error))
503
560
  await codexServers.stop(appServer).catch(() => undefined);
561
+ if (error instanceof BridgeError && error.message.startsWith("Codex exited at start:"))
562
+ throw error;
504
563
  // A first-run screen (Claude's folder trust, a login notice) holds the
505
564
  // agent at startup. It did start: hand the pane back so the owner answers
506
565
  // that screen from the chat instead of stranding the workspace.
@@ -590,7 +590,9 @@ export class SessionMover {
590
590
  const deadline = this.now + handoffMs;
591
591
  try {
592
592
  const sent = await this.deps.deliver(from, handoffRequest(record.id, record.to, record.mode), `move-${record.id}`);
593
- if (sent.ok !== true && sent.queued !== true)
593
+ // A lost delivery acknowledgement can still have reached the agent;
594
+ // its marked transcript reply is authoritative for the normal window.
595
+ if (sent.state !== "uncertain" && sent.ok !== true && sent.queued !== true)
594
596
  return { reason: `the request could not be delivered (${String(sent.error ?? sent.state ?? "not confirmed")}).` };
595
597
  }
596
598
  catch (error) {
@@ -36703,7 +36703,7 @@ var init_package_metadata = __esm({
36703
36703
  __dirname = path35.dirname(fileURLToPath2(import.meta.url));
36704
36704
  ROOT = path35.join(__dirname, "..");
36705
36705
  PACKAGE_JSON_PATH = path35.join(ROOT, "package.json");
36706
- BUNDLED_VERSION = true ? "0.3.52" : "0.0.0";
36706
+ BUNDLED_VERSION = true ? "0.3.53" : "0.0.0";
36707
36707
  PACKAGE_JSON = readPackageJson();
36708
36708
  PACKAGE_NAME = PACKAGE_JSON.name || "phren";
36709
36709
  VERSION = PACKAGE_JSON.version || BUNDLED_VERSION;
@@ -52701,7 +52701,7 @@ Open or changed files are named in the conversation above and the checked Git st
52701
52701
  const deadline = this.now + handoffMs;
52702
52702
  try {
52703
52703
  const sent = await this.deps.deliver(from, handoffRequest(record4.id, record4.to, record4.mode), `move-${record4.id}`);
52704
- if (sent.ok !== true && sent.queued !== true) return { reason: `the request could not be delivered (${String(sent.error ?? sent.state ?? "not confirmed")}).` };
52704
+ if (sent.state !== "uncertain" && sent.ok !== true && sent.queued !== true) return { reason: `the request could not be delivered (${String(sent.error ?? sent.state ?? "not confirmed")}).` };
52705
52705
  } catch (error62) {
52706
52706
  return { reason: `the request could not be delivered (${error62 instanceof Error ? error62.message : String(error62)}).` };
52707
52707
  }
@@ -67101,6 +67101,62 @@ async function startWhenShellReady(server, pane, agent) {
67101
67101
  }
67102
67102
  }
67103
67103
  }
67104
+ async function startCodex(server, pane, agent) {
67105
+ const terminal2 = terminalProvider();
67106
+ const screenText = async () => stripTerminal(await terminal2.readScreen?.(
67107
+ server,
67108
+ pane,
67109
+ { scope: "pane", source: "recent", lines: 20 }
67110
+ ).catch(() => "") ?? "").trim();
67111
+ for (let attempt = 0; attempt < 2; attempt++) {
67112
+ const before = await screenText();
67113
+ const deadline = Date.now() + agent.timeoutMs;
67114
+ let ran = false;
67115
+ let result;
67116
+ const starting = startWhenShellReady(server, pane, agent).then(
67117
+ () => {
67118
+ result = {};
67119
+ ran = true;
67120
+ },
67121
+ (error62) => {
67122
+ result = { error: error62 };
67123
+ }
67124
+ );
67125
+ try {
67126
+ for (; ; ) {
67127
+ await Promise.race([starting, new Promise((resolve17) => setTimeout(resolve17, 250))]);
67128
+ const processes = await terminal2.processes?.(server, pane).catch(() => void 0);
67129
+ const state = await terminal2.snapshot(server);
67130
+ const current2 = objects(state.panes).find((row) => row.pane_id === pane);
67131
+ const shell = processes?.shellPid;
67132
+ const atShell = processes !== void 0 && shell !== void 0 && processes.foregroundPids.every((pid) => pid === shell);
67133
+ if (processes && !atShell && current2?.agent === "codex") ran = true;
67134
+ if (atShell) {
67135
+ const screen = await screenText();
67136
+ const exitMessage = screen !== before && /please restart codex|codex exited(?: at start)?/i.test(screen);
67137
+ if (ran || exitMessage) {
67138
+ if (!result) {
67139
+ await starting;
67140
+ continue;
67141
+ }
67142
+ if (attempt === 0) break;
67143
+ const last = screen.split(/\r?\n/).map((line) => line.trim()).filter(Boolean).at(-1);
67144
+ throw new BridgeError(409, `Codex exited at start: ${last || "process returned to its shell"}`);
67145
+ }
67146
+ }
67147
+ if (result && "error" in result) throw result.error;
67148
+ if (result) {
67149
+ if (!processes || ["idle", "working", "blocked", "waiting"].includes(String(current2?.agent_status)) || Date.now() >= deadline) return;
67150
+ await new Promise((resolve17) => setTimeout(resolve17, 250));
67151
+ } else if (Date.now() >= deadline) {
67152
+ await starting;
67153
+ }
67154
+ }
67155
+ } finally {
67156
+ await starting;
67157
+ }
67158
+ }
67159
+ }
67104
67160
  function herdrAgentName(label2) {
67105
67161
  const slug = label2.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^[^a-z]+/, "").replace(/-+$/, "").slice(0, 32).replace(/-+$/, "");
67106
67162
  return slug || "agent";
@@ -67268,11 +67324,15 @@ async function startSession(server, data, options) {
67268
67324
  briefTurn = error62 instanceof AppServerRpcError ? void 0 : "uncertain";
67269
67325
  }
67270
67326
  }
67271
- const agentArgs = structuredLaunch ? structuredLaunch.args : [...args, ...briefLaunch ?? []];
67327
+ const agentArgs = [
67328
+ ...structuredLaunch ? structuredLaunch.args : [...args, ...briefLaunch ?? []],
67329
+ ...kind === "codex" ? ["-c", "check_for_update_on_startup=false"] : []
67330
+ ];
67272
67331
  try {
67273
- await startWhenShellReady(server, created.paneId, { name, kind, args: agentArgs, timeoutMs: timeout, ...env ? { env } : {} });
67332
+ await (kind === "codex" ? startCodex : startWhenShellReady)(server, created.paneId, { name, kind, args: agentArgs, timeoutMs: timeout, ...env ? { env } : {} });
67274
67333
  } catch (error62) {
67275
67334
  if (appServer && !agentNotReady(error62)) await codexServers.stop(appServer).catch(() => void 0);
67335
+ if (error62 instanceof BridgeError && error62.message.startsWith("Codex exited at start:")) throw error62;
67276
67336
  const blocked = agentNotReady(error62);
67277
67337
  if (!blocked) {
67278
67338
  const host = terminalName(server);
@@ -67406,6 +67466,7 @@ var init_server_launch = __esm({
67406
67466
  init_codex_app_server();
67407
67467
  init_codex_servers();
67408
67468
  init_logger();
67469
+ init_terminal_text();
67409
67470
  init_job_registry();
67410
67471
  init_protocol();
67411
67472
  init_settings_switch();
@@ -77827,7 +77888,7 @@ async function main() {
77827
77888
  return askpass2(args[1]);
77828
77889
  }
77829
77890
  const { runBridge: runBridge2 } = await Promise.resolve().then(() => (init_command(), command_exports));
77830
- return runBridge2(args, "0.3.52");
77891
+ return runBridge2(args, "0.3.53");
77831
77892
  }
77832
77893
  main().then((code) => {
77833
77894
  process.exitCode = code;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phren/cli",
3
- "version": "0.3.52",
3
+ "version": "0.3.53",
4
4
  "description": "Knowledge layer for AI agents - CLI, MCP server, and data layer",
5
5
  "type": "module",
6
6
  "bin": {