@phren/cli 0.3.45 → 0.3.47

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/dist/bridge/agent-hook-asks.d.ts +34 -0
  2. package/dist/bridge/agent-hook-asks.js +72 -0
  3. package/dist/bridge/agent-hook-callback.d.ts +22 -0
  4. package/dist/bridge/agent-hook-callback.js +114 -0
  5. package/dist/bridge/agent-hooks.d.ts +7 -74
  6. package/dist/bridge/agent-hooks.js +22 -186
  7. package/dist/bridge/claude-question-dialog.d.ts +6 -0
  8. package/dist/bridge/claude-question-dialog.js +29 -7
  9. package/dist/bridge/codex-app-server.d.ts +5 -0
  10. package/dist/bridge/codex-app-server.js +15 -0
  11. package/dist/bridge/codex-auth-refresh.d.ts +7 -0
  12. package/dist/bridge/codex-auth-refresh.js +22 -0
  13. package/dist/bridge/dispatch-command.js +7 -1
  14. package/dist/bridge/file-write.js +3 -1
  15. package/dist/bridge/git-host-auth.d.ts +6 -0
  16. package/dist/bridge/git-host-auth.js +45 -0
  17. package/dist/bridge/git-publish.d.ts +1 -1
  18. package/dist/bridge/git-publish.js +75 -8
  19. package/dist/bridge/git-review.js +23 -2
  20. package/dist/bridge/git-write-policy.d.ts +13 -0
  21. package/dist/bridge/git-write-policy.js +39 -0
  22. package/dist/bridge/git.d.ts +5 -1
  23. package/dist/bridge/git.js +103 -8
  24. package/dist/bridge/health.d.ts +1 -0
  25. package/dist/bridge/health.js +8 -5
  26. package/dist/bridge/lookup-cache.d.ts +17 -0
  27. package/dist/bridge/lookup-cache.js +70 -0
  28. package/dist/bridge/memory-store.js +40 -14
  29. package/dist/bridge/pair.js +4 -0
  30. package/dist/bridge/peers.js +36 -0
  31. package/dist/bridge/projects.d.ts +14 -0
  32. package/dist/bridge/projects.js +48 -1
  33. package/dist/bridge/prompt-deliveries.d.ts +38 -3
  34. package/dist/bridge/prompt-deliveries.js +196 -36
  35. package/dist/bridge/schedule-format.d.ts +7 -0
  36. package/dist/bridge/schedule-format.js +73 -2
  37. package/dist/bridge/schedule-problems.js +4 -0
  38. package/dist/bridge/schedule-update.d.ts +6 -0
  39. package/dist/bridge/schedule-update.js +63 -0
  40. package/dist/bridge/schedules.js +16 -4
  41. package/dist/bridge/scoped-gateway.d.ts +1 -0
  42. package/dist/bridge/scoped-gateway.js +10 -1
  43. package/dist/bridge/server-launch.js +6 -2
  44. package/dist/bridge/server-pane-routes.d.ts +4 -2
  45. package/dist/bridge/server-pane-routes.js +8 -2
  46. package/dist/bridge/server-routes.js +14 -4
  47. package/dist/bridge/session-servers.js +3 -0
  48. package/dist/bridge/{codex-thread-origin.d.ts → thread-origin.d.ts} +8 -0
  49. package/dist/bridge/{codex-thread-origin.js → thread-origin.js} +24 -6
  50. package/dist/bridge/usage.d.ts +4 -0
  51. package/dist/bridge/usage.js +22 -8
  52. package/dist/bridge-hook.mjs +1420 -553
  53. package/dist/cli/actions.js +4 -0
  54. package/dist/cli/namespaces-tasks.js +19 -5
  55. package/dist/cli/ops.d.ts +1 -1
  56. package/dist/cli/ops.js +2 -2
  57. package/dist/cli/schedules.js +16 -9
  58. package/dist/content/summarize.js +46 -6
  59. package/dist/content/validate.d.ts +3 -1
  60. package/dist/content/validate.js +33 -4
  61. package/dist/data/access.d.ts +8 -1
  62. package/dist/data/access.js +27 -9
  63. package/dist/data/notes.d.ts +2 -0
  64. package/dist/data/notes.js +2 -1
  65. package/dist/entrypoint.js +2 -1
  66. package/dist/generated/memory-ui-graph.browser.js +1 -1
  67. package/dist/governance/locks.js +17 -1
  68. package/dist/governance/policy.js +37 -23
  69. package/dist/mcp/profile.js +23 -4
  70. package/dist/memory-ui-graph.runtime.js +1 -1
  71. package/dist/modules/registry.js +2 -2
  72. package/dist/sync/conflict-resolve.d.ts +1 -1
  73. package/dist/sync/conflict-resolve.js +91 -8
  74. package/dist/task/lifecycle.js +5 -3
  75. package/package.json +1 -1
@@ -1,23 +1,17 @@
1
1
  import { approvalRuleContext, approvalRuleEffect } from "./approval-rules.js";
2
2
  import { recordedConductor } from "./conductor-role.js";
3
3
  import { conductorBrief, conductorContext } from "./conductor-context.js";
4
- import { defaultPhrenPath } from "../shared.js";
5
4
  import { disabledHint } from "../modules/registry.js";
6
- import { activateModules as moduleSnapshot } from "../modules/runtime.js";
7
5
  import { logger } from "../logger.js";
8
- import { request, createServer } from "node:http";
6
+ import { createServer } from "node:http";
9
7
  import { mkdir, readFile, chmod, unlink, lstat } from "node:fs/promises";
10
8
  import { watch } from "node:fs";
11
9
  import path from "node:path";
12
10
  import { randomUUID } from "node:crypto";
13
11
  import { hostname } from "node:os";
14
- import { atomicInPrivateDir, BridgeError, bridgeRoot, object, objects, provider, targetSchema } from "./protocol.js";
12
+ import { atomicInPrivateDir, BridgeError, bridgeRoot, object, objects, targetSchema } from "./protocol.js";
15
13
  import { findPane, knownPanes, paneIdentity, paneForCodexSession, servers, snapshot, trustedDirectory, validateTarget } from "./herdr.js";
16
- import { hookOutput, TOOL_HOOK_BUDGET_MS } from "./hook-fast.js";
17
- import { underCodexDaemon } from "./codex-daemon.js";
18
- import { codexAutoReview } from "./codex-review-mode.js";
19
- import { codexForeignThread } from "./codex-thread-origin.js";
20
- import { terminalPaneFromEnv, terminalProvider } from "./terminal.js";
14
+ import { terminalProvider } from "./terminal.js";
21
15
  import { readPaneText } from "./pane-text.js";
22
16
  import { capturesChanges, ToolChanges } from "./changes.js";
23
17
  import { phrenStoreRoot } from "./transcripts.js";
@@ -37,11 +31,14 @@ import { eventStatus, notePaneStatus, settleBlockedPane } from "./pane-status.js
37
31
  import { noteTurn as recordTurn } from "./turn-records.js";
38
32
  import { PromptDeliveries } from "./prompt-deliveries.js";
39
33
  import { countTick } from "./metrics.js";
40
- import { briefId, briefIdInPrompt, briefLabel, DISPATCH_ID_ENV, recordBriefArrival } from "./launch-brief.js";
34
+ import { briefId, briefIdInPrompt, briefLabel, recordBriefArrival } from "./launch-brief.js";
35
+ import { appServerApproval, appServerDecision, conductorCall, OPENCODE_APPROVAL_OPTIONS, opencodePermissionReply } from "./agent-hook-asks.js";
41
36
  import { SudoBroker } from "./sudo.js";
42
- import { CODEX_SERVER_ENV, codexServerId, codexServers } from "./codex-servers.js";
37
+ import { codexServers } from "./codex-servers.js";
43
38
  import { paneClient, paneKey, PaneServerWatcher, rootSession, servedPane } from "./opencode-panes.js";
44
39
  export { permissionPrompt, terminalChoice, visibleTerminalChoice } from "./terminal-choice.js";
40
+ export { appServerApproval, appServerDecision, conductorCall, OPENCODE_APPROVAL_OPTIONS, opencodePermissionReply } from "./agent-hook-asks.js";
41
+ export { agentHook, stopFacts, withinToolBudget } from "./agent-hook-callback.js";
45
42
  export { ApprovalWatchLeases, PushBindingStore, recordedSession } from "./agent-hook-stores.js";
46
43
  const APPROVAL_SWEEP_MS = 2_000;
47
44
  /** How recent the Herdr snapshots must be for the poll to trust "no opencode pane". */
@@ -54,6 +51,8 @@ const APPROVAL_HOLD_MS = (() => {
54
51
  return Number.isFinite(value) && value >= 50 && value <= 60_000 ? Math.floor(value) : 55_000;
55
52
  })();
56
53
  /** A pane's terminal dialog is read at most once per this window. */
54
+ /** Lines read to find Claude's question dialog: its tab bar sits above the whole question. */
55
+ const QUESTION_READ_LINES = 120;
57
56
  const DIALOG_READ_MS = intervalFromEnv("PHREN_DIALOG_THROTTLE_MS", 3_000);
58
57
  /** How long a pushed terminal dialog can be answered from its notification. */
59
58
  const DIALOG_PUSH_MS = 10 * 60_000;
@@ -77,79 +76,8 @@ export function watchHangUp(res) {
77
76
  res.once("close", onClose);
78
77
  return () => { res.off("close", onClose); return closed || res.destroyed; };
79
78
  }
80
- /** The approval card's tool and input for an app-server request, in the
81
- * shapes `approvalSummary` and the phone already read for Codex's hook.
82
- * Undefined for questions (`item/tool/requestUserInput`) and MCP
83
- * elicitations, which stay in the pane. */
84
- export function appServerApproval(request) {
85
- const params = request.params;
86
- const reason = typeof params.reason === "string" && params.reason ? { reason: params.reason } : {};
87
- if (request.method === "item/commandExecution/requestApproval") {
88
- return { tool: "Bash", input: { ...(typeof params.command === "string" ? { command: params.command } : {}),
89
- ...(typeof params.cwd === "string" ? { cwd: params.cwd } : {}), ...reason } };
90
- }
91
- if (request.method === "item/fileChange/requestApproval") {
92
- const changes = objects(params.changes);
93
- const verb = (change) => object(change.kind).type === "add" ? "Add" : object(change.kind).type === "delete" ? "Delete" : "Update";
94
- const patch = changes.filter(change => typeof change.path === "string").map(change => `*** ${verb(change)} File: ${change.path}`).join("\n");
95
- return { tool: "apply_patch", input: { ...(patch ? { patch } : {}), ...(typeof params.grantRoot === "string" ? { grantRoot: params.grantRoot } : {}), ...reason } };
96
- }
97
- if (request.method === "item/permissions/requestApproval")
98
- return { tool: "Permissions", input: { permissions: params.permissions ?? {}, ...reason } };
99
- return undefined;
100
- }
101
- /** The app-server's answer for the phone's allow or deny (T3's
102
- * CodexSessionRuntime shapes: accept / decline, a permission grant or none). */
103
- export function appServerDecision(request, allow) {
104
- if (request.method === "item/permissions/requestApproval")
105
- return { permissions: allow ? object(request.params.permissions) : {}, scope: "turn" };
106
- return { decision: allow ? "accept" : "decline" };
107
- }
108
79
  /** How long a dispatching Hook's poll keeps a worker pane's permission asks held. */
109
80
  const DISPATCH_LEASE_MS = 45_000;
110
- /** A conductor `dispatch` or `hand_off` permission ask the Hook can answer
111
- * itself under a standing grant, or offer the phone two grant-writing answers. */
112
- export function conductorCall(tool, input) {
113
- // MCP tool names vary by harness: `dispatch`, `phren.dispatch`,
114
- // `mcp__phren__dispatch`; phren_admin carries the action in its fields.
115
- const tail = /(?:^|[.:/]|__)(dispatch|hand_off|phren_admin)$/.exec(tool.replace(/^mcp_phren_/, ""))?.[1];
116
- const fields = object(input);
117
- let action;
118
- if (tail === "dispatch")
119
- action = "dispatch";
120
- else if (tail === "hand_off")
121
- action = "hand_off";
122
- else if (tail === "phren_admin" && (fields.action === "dispatch" || fields.action === "hand_off"))
123
- action = fields.action;
124
- if (!action)
125
- return undefined;
126
- const project = typeof fields.project === "string" ? fields.project : undefined;
127
- const computer = typeof fields.computer === "string" ? fields.computer : undefined;
128
- return { action, ...(project ? { project } : {}), ...(computer ? { computer } : {}) };
129
- }
130
- /** The decisions an OpenCode permission ask offers the phone. OpenCode's
131
- * `always` covers the current session, so both grant answers reply `always`;
132
- * `allow-everywhere` additionally writes an allow rule into the user's
133
- * OpenCode config. Advertised as the approval card's `options`, the same
134
- * shape the phone already renders for a provider-supplied option list. */
135
- export const OPENCODE_APPROVAL_OPTIONS = [
136
- { label: "Allow once", decision: "approve" },
137
- { label: "Allow for this project", decision: "allow-project" },
138
- { label: "Allow everywhere", decision: "allow-everywhere" },
139
- { label: "Deny", decision: "deny" },
140
- ];
141
- /** The OpenCode permission reply a card decision maps to: both grant scopes
142
- * are `always`, a plain approve is `once`, a deny is `reject`. Undefined for
143
- * anything else. */
144
- export function opencodePermissionReply(decision) {
145
- if (decision === "approve")
146
- return "once";
147
- if (decision === "deny")
148
- return "reject";
149
- if (decision === "allow-project" || decision === "allow-everywhere")
150
- return "always";
151
- return undefined;
152
- }
153
81
  /** This socket is deliberately separate from the phone's HTTP pipe. Only local
154
82
  * agent callbacks can register identities or create an approval request. */
155
83
  /** The project a notification names for a pane's folder: none for the
@@ -727,6 +655,10 @@ export class AgentHooks {
727
655
  while (this.dialogReads.size > 128)
728
656
  this.dialogReads.delete(this.dialogReads.keys().next().value);
729
657
  const text = await this.paneLines(target);
658
+ // A tall question has its tab bar above the 40 lines: look further up, for it only.
659
+ const tall = target.source === "claude" && /Chat about this/.test(text) && !claudeQuestionDialog(text)
660
+ ? await this.paneLines(target, true, QUESTION_READ_LINES).catch(() => "") : "";
661
+ const asking = target.source === "claude" && !!(claudeQuestionDialog(text) || (tall && claudeQuestionDialog(tall)));
730
662
  this.passwords.set(key, passwordLine(text));
731
663
  while (this.passwords.size > 128)
732
664
  this.passwords.delete(this.passwords.keys().next().value);
@@ -734,7 +666,7 @@ export class AgentHooks {
734
666
  // (the held request, the remembered one, or the transcript's), never as
735
667
  // a numbered dialog: its digits advance on their own and a trailing
736
668
  // Enter would land on the next tab.
737
- if (target.source === "claude" && claudeQuestionDialog(text)) {
669
+ if (asking) {
738
670
  if (entry && !question)
739
671
  this.terminalPrompts.delete(key);
740
672
  return;
@@ -747,7 +679,7 @@ export class AgentHooks {
747
679
  if (entry && !entry.dialog) {
748
680
  // The permission the pane still shows after its hook let go: keep the
749
681
  // request's own details and answer it with the dialog's rows, so the
750
- // phone can approve it long after the hold ended, as Moshi does. Not a
682
+ // phone can approve it long after the hold ended. Not a
751
683
  // `dialog`: Claude takes a row's digit at once, and an Enter after it
752
684
  // could land on the next permission.
753
685
  if (dialog?.title) {
@@ -857,7 +789,8 @@ export class AgentHooks {
857
789
  async answerClaudeQuestions(target, questions, answers, options = {}) {
858
790
  const key = JSON.stringify(target);
859
791
  await answerClaudeQuestionDialog({
860
- read: () => this.paneLines(target),
792
+ // A tall question (long text, many options) pushes its tab bar out of 40 lines.
793
+ read: () => this.paneLines(target, true, QUESTION_READ_LINES),
861
794
  keys: async (keys) => {
862
795
  if (!keys.length)
863
796
  return;
@@ -926,8 +859,8 @@ export class AgentHooks {
926
859
  return readPaneText(target.server, target.pane, { scope: "agent", source: "visible", lines: 40, stripAnsi: false, format: "ansi", timeoutMs: 2_000 });
927
860
  }
928
861
  /** Read what the pane draws, stripping ANSI unless placeholder styling is needed. */
929
- paneLines(target, stripAnsi = true) {
930
- return readPaneText(target.server, target.pane, { scope: "agent", source: "visible", lines: 40, stripAnsi, timeoutMs: 2_000 });
862
+ paneLines(target, stripAnsi = true, lines = 40) {
863
+ return readPaneText(target.server, target.pane, { scope: "agent", source: "visible", lines, stripAnsi, timeoutMs: 2_000 });
931
864
  }
932
865
  /** After the phone walks Codex's /permissions menu onto Full Access, the
933
866
  * agent draws a second "Enable full access?" confirmation. Watch the pane's
@@ -1673,7 +1606,7 @@ export class AgentHooks {
1673
1606
  // `/new` or `/resume` in a pane on the Hook's own Codex server: follow
1674
1607
  // the TUI to its new thread. Only a callback trusted to name its pane.
1675
1608
  // A prompt or a turn's end also moves a server a nested `codex exec`
1676
- // had taken (before codex-thread-origin.ts) back to the TUI's thread.
1609
+ // had taken (before thread-origin.ts) back to the TUI's thread.
1677
1610
  if (["SessionStart", "UserPromptSubmit", "Stop"].includes(String(body.event)) && target.source === "codex" && !daemon)
1678
1611
  codexServers.follow(target.server, target.pane, target.session);
1679
1612
  if (body.event === "PreCompact") {
@@ -1685,7 +1618,7 @@ export class AgentHooks {
1685
1618
  this.stopCompacting(target);
1686
1619
  if (body.event === "UserPromptSubmit") {
1687
1620
  if (typeof body.prompt === "string")
1688
- this.deliveries.submitted(target, body.prompt.slice(0, 65_536));
1621
+ await this.deliveries.submitted(target, body.prompt.slice(0, 65_536));
1689
1622
  await this.recordTurn(target, pane, body, dispatch);
1690
1623
  const context = this.modules?.has("conductor") === false ? undefined : await conductorContext(target, s).catch(() => undefined);
1691
1624
  res.end(JSON.stringify(context ? { hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: context } } : {}));
@@ -1885,100 +1818,3 @@ export class AgentHooks {
1885
1818
  this.fanoutSeen.clear();
1886
1819
  }
1887
1820
  }
1888
- /** What a Stop payload says about the turn it ends: the harness's last
1889
- * assistant message (Claude, Codex) and, from Claude Code, the background
1890
- * tasks still in flight, which will wake the conversation again when they
1891
- * finish. Absent fields are left out, so the Hook falls back to the transcript. */
1892
- export function stopFacts(value) {
1893
- const tasks = Array.isArray(value.background_tasks)
1894
- ? value.background_tasks.filter(task => !["completed", "failed", "killed", "stopped"].includes(String(object(task).status))) : undefined;
1895
- return { ...(tasks ? { background: tasks.length } : {}),
1896
- ...(typeof value.last_assistant_message === "string" && value.last_assistant_message.trim() ? { reply: value.last_assistant_message.slice(0, 16_384) } : {}) };
1897
- }
1898
- /** One agent callback, run as `hook <source>`. Resolves "abandoned" when a
1899
- * tool call's callback ran out of its budget: the caller then exits at once,
1900
- * since a socket or a process read still pending would hold the agent. */
1901
- export async function agentHook(source, elapsed = () => performance.now()) {
1902
- provider.parse(source);
1903
- // A missing helper must never prevent the coding agent from running.
1904
- // Inside Herdr only Herdr's pane counts; elsewhere a tmux pane does.
1905
- const place = await terminalPaneFromEnv();
1906
- if (!place)
1907
- return;
1908
- let input = "";
1909
- for await (const chunk of process.stdin) {
1910
- input += chunk.toString();
1911
- if (input.length > 1_048_576)
1912
- return;
1913
- }
1914
- const value = object(JSON.parse(input));
1915
- if (value.agent_id || value.agentId || value.isSidechain || value.is_sidechain)
1916
- return;
1917
- // A `codex exec` or a subagent inside a Codex pane is not the pane's conversation.
1918
- if (source === "codex" && await codexForeignThread(value.transcript_path).catch(() => false))
1919
- return;
1920
- const target = targetSchema.parse({ server: place.server, workspace: place.workspace, tab: place.tab,
1921
- pane: place.pane, source, session: value.session_id || value.sessionId });
1922
- const event = String(value.hook_event_name || "SessionStart");
1923
- return withinToolBudget(event, left => forwardHook(source, target, event, value, left), elapsed);
1924
- }
1925
- /**
1926
- * Runs a callback's work. A PreToolUse or PostToolUse callback gets what is
1927
- * left of TOOL_HOOK_BUDGET_MS since its process started (hook-fast.ts says
1928
- * why): "abandoned" once that runs out, and the caller exits without an
1929
- * answer so the tool runs. Every other event runs to its own timeouts.
1930
- */
1931
- export async function withinToolBudget(event, work, elapsed = () => performance.now(), budgetMs = TOOL_HOOK_BUDGET_MS) {
1932
- if (!event.endsWith("ToolUse"))
1933
- return work(() => Infinity);
1934
- const left = () => Math.floor(budgetMs - elapsed());
1935
- if (left() <= 0)
1936
- return "abandoned";
1937
- let timer;
1938
- const expired = new Promise(resolve => { timer = setTimeout(() => resolve("abandoned"), left()); });
1939
- try {
1940
- return await Promise.race([work(left), expired]);
1941
- }
1942
- finally {
1943
- clearTimeout(timer);
1944
- }
1945
- }
1946
- async function forwardHook(source, target, event, value, left) {
1947
- const modules = moduleSnapshot(defaultPhrenPath(), undefined, true);
1948
- if (!modules.has("hook") || (event.endsWith("ToolUse") && !modules.has("git")))
1949
- return;
1950
- // Codex 0.157 runs hooks inside its shared app-server daemon, whose pane
1951
- // variables belong to whichever pane first started it.
1952
- // The Hook's own per-pane app-server (codex-servers.ts) runs its hooks
1953
- // with that pane's variables, so they are trusted like a pane's own.
1954
- const ownServer = source === "codex" && codexServerId.safeParse(process.env[CODEX_SERVER_ENV]).success;
1955
- const daemon = source === "codex" && !ownServer && await underCodexDaemon().catch(() => false);
1956
- // Codex asks this hook before its automatic reviewer: say when that
1957
- // reviewer, not the owner, will decide.
1958
- const autoReview = source === "codex" && event === "PermissionRequest" && await codexAutoReview(value.transcript_path);
1959
- // A worker the Hook launched with its brief carries that dispatch's id. A
1960
- // daemon's variables belong to another pane, so it sends none.
1961
- const dispatchId = !daemon && (event === "SessionStart" || event === "UserPromptSubmit") && briefId.safeParse(process.env[DISPATCH_ID_ENV]).success
1962
- ? process.env[DISPATCH_ID_ENV] : undefined;
1963
- const data = JSON.stringify({ target, event, ...(daemon ? { daemon: true } : {}), ...(autoReview ? { autoReview: true } : {}), ...(dispatchId ? { dispatchId } : {}),
1964
- ...(source === "claude" && typeof value.transcript_path === "string" ? { transcript: value.transcript_path.slice(0, 4096) } : {}),
1965
- tool: value.tool_name, input: value.tool_input, toolUseId: value.tool_use_id, cwd: value.cwd,
1966
- ...(event === "UserPromptSubmit" && typeof value.prompt === "string" ? { prompt: value.prompt.slice(0, 65_536) } : {}),
1967
- ...(event === "Stop" ? stopFacts(value) : {}) });
1968
- await new Promise(resolve => {
1969
- const req = request({ socketPath: localSocket(), path: "/hook", method: "POST", timeout: event === "PermissionRequest" ? 58_000 : event.endsWith("ToolUse") ? Math.max(1, left()) : 12_000,
1970
- headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(data) } }, res => {
1971
- let result = "";
1972
- res.on("data", chunk => { result += chunk.toString(); if (result.length > 16_384)
1973
- req.destroy(); });
1974
- // Forward approval/refusal decisions and validated turn context.
1975
- // Tool callbacks stay silent, and an empty reply says nothing.
1976
- res.on("end", () => { if (res.statusCode === 200)
1977
- process.stdout.write(hookOutput(event, result)); resolve(); });
1978
- res.on("error", () => resolve());
1979
- });
1980
- req.on("error", () => resolve());
1981
- req.on("timeout", () => { req.destroy(); resolve(); });
1982
- req.end(data);
1983
- });
1984
- }
@@ -35,6 +35,12 @@ export interface ClaudeReviewScreen {
35
35
  }[];
36
36
  }
37
37
  export type ClaudeDialogScreen = ClaudeQuestionScreen | ClaudeReviewScreen;
38
+ /** Claude cuts a question at 2000 characters with "…" while the phone may send
39
+ * more, so the pane's title matches when it is the question's own head. */
40
+ export declare const sameTitle: (shown: string, asked: string) => boolean;
41
+ /** Claude collapses runs of whitespace in a label, and the Hook reads only the
42
+ * first line of one it wraps, so a long label matches by its head. */
43
+ export declare const sameLabel: (shown: string, asked: string) => boolean;
38
44
  /** The question dialog the pane is drawing now, or undefined when the last
39
45
  * lines are not one: the last tab bar anchors it, and an active dialog ends
40
46
  * with its "Esc to cancel" footer or the review's Submit/Cancel rows. */
@@ -3,6 +3,20 @@ const TAB_BAR = /^\s*(?:←\s+)?((?:[☐☒]\s+\S[^☐☒✔→]*?\s*)+)(?:✔\s
3
3
  const ROW = /^\s*(❯)?\s*(\d)\.\s+(?:\[([ ✔])\]\s+)?(.*?)\s*$/;
4
4
  const NEXT = /^\s*(❯)?\s+(?:Next|Submit)\s*$/;
5
5
  const normalize = (text) => text.replace(/\s+/g, " ").trim();
6
+ /** Claude cuts a question at 2000 characters with "…" while the phone may send
7
+ * more, so the pane's title matches when it is the question's own head. */
8
+ export const sameTitle = (shown, asked) => {
9
+ const want = normalize(asked);
10
+ if (shown === want)
11
+ return true;
12
+ return shown.endsWith("…") && shown.length > 200 && want.startsWith(shown.slice(0, -1).trimEnd());
13
+ };
14
+ /** Claude collapses runs of whitespace in a label, and the Hook reads only the
15
+ * first line of one it wraps, so a long label matches by its head. */
16
+ export const sameLabel = (shown, asked) => {
17
+ const want = normalize(asked);
18
+ return shown === want || (shown.length >= 30 && want.startsWith(shown));
19
+ };
6
20
  /** Claude Code (2.1.284) draws a question that has a line break or is wider
7
21
  * than 80 columns inside a dimmed left border, "│ " before each line, on its
8
22
  * tab and in the review. The border is not part of the question. */
@@ -81,15 +95,24 @@ export function claudeQuestionDialog(text) {
81
95
  const other = rows.pop();
82
96
  return { kind: "question", tabs, title, multiSelect: rows.some(row => row.checked !== undefined), options: rows, other, ...(cursor !== undefined ? { cursor } : {}) };
83
97
  }
84
- const changed = (message) => new BridgeError(409, `${message} Nothing else was sent; check the question and answer again, or cancel it.`);
98
+ /** A 409 that says whether any key reached the terminal: `question-not-shown`
99
+ * (nothing typed, retrying is safe) or `question-unconfirmed` (keys were sent,
100
+ * so look at the terminal before answering again). */
101
+ const refusal = (message, sent) => sent
102
+ ? new BridgeError(409, `${message} Some keys were already sent, so check the terminal before answering again, or cancel the question.`, { code: "question-unconfirmed" })
103
+ : new BridgeError(409, `${message} Nothing was sent; check the question and answer again, or cancel it.`, { code: "question-not-shown" });
85
104
  /** A typed answer, one key per character; herdr names the space bar. */
86
105
  const typedKeys = (text) => [...text].map(character => character === " " ? "space" : character);
87
106
  /** Answer `answers[i]` for question `from + i`, then submit the set when
88
107
  * `submit` is true. Each step is checked against a fresh read of the pane. */
89
108
  export async function answerClaudeQuestionDialog(io, questions, answers, options = {}) {
90
109
  const from = options.from ?? 0, submit = options.submit ?? true;
110
+ let sent = false;
111
+ const changed = (message) => refusal(message, sent);
112
+ const realKeys = io.keys.bind(io);
113
+ io = { ...io, keys: async (keys) => { sent = true; await realKeys(keys); } };
91
114
  const sleep = io.sleep ?? ((ms) => new Promise(resolve => setTimeout(resolve, ms)));
92
- const matches = (screen, index) => screen?.kind === "question" && screen.title === normalize(questions[index].question);
115
+ const matches = (screen, index) => screen?.kind === "question" && sameTitle(screen.title, questions[index].question);
93
116
  // Claude redraws a moment after a key; poll until the expected screen shows.
94
117
  const settle = async (check, ms = 2_000) => {
95
118
  for (let waited = 0;; waited += 120) {
@@ -112,10 +135,10 @@ export async function answerClaudeQuestionDialog(io, questions, answers, options
112
135
  throw changed("The terminal is asking a different set of questions.");
113
136
  const reach = async (index) => {
114
137
  const screen = await settle(value => value);
115
- if (screen?.kind === "question" && screen.title === normalize(questions[index].question))
138
+ if (screen?.kind === "question" && sameTitle(screen.title, questions[index].question))
116
139
  return screen;
117
140
  const at = screen?.kind === "review" ? questions.length
118
- : screen?.kind === "question" ? questions.findIndex(question => normalize(question.question) === screen.title) : -1;
141
+ : screen?.kind === "question" ? questions.findIndex(question => sameTitle(screen.title, question.question)) : -1;
119
142
  if (at < 0)
120
143
  throw changed("The terminal is showing a different question.");
121
144
  // Arrow keys would edit a typed answer; step off that row first.
@@ -135,7 +158,7 @@ export async function answerClaudeQuestionDialog(io, questions, answers, options
135
158
  const typed = answer.text?.trim() ?? "";
136
159
  let screen = await reach(index);
137
160
  if (screen.multiSelect !== !!question.multiSelect || screen.options.length !== question.options.length
138
- || screen.options.some((row, position) => row.label !== question.options[position].label.trim())) {
161
+ || screen.options.some((row, position) => !sameLabel(row.label, question.options[position].label))) {
139
162
  throw changed("The terminal's options differ from the question being answered.");
140
163
  }
141
164
  if (!screen.multiSelect) {
@@ -208,8 +231,7 @@ export async function answerClaudeQuestionDialog(io, questions, answers, options
208
231
  return;
209
232
  if (!review)
210
233
  throw changed("The terminal did not reach the review of the answers.");
211
- const expected = questions.map(question => normalize(question.question));
212
- if (review.answers.length !== questions.length || review.answers.some((row, position) => normalize(row.question) !== expected[position] || !row.answer)) {
234
+ if (review.answers.length !== questions.length || review.answers.some((row, position) => !sameTitle(normalize(row.question), questions[position].question) || !row.answer)) {
213
235
  throw changed("Not every question has an answer in the terminal.");
214
236
  }
215
237
  await io.keys(["1"]);
@@ -131,6 +131,11 @@ export interface SpawnAppServerOptions {
131
131
  * server in place, so the child's pid is the server's. */
132
132
  scope?: string;
133
133
  }
134
+ /** This codex build cannot listen on a unix socket (0.113 accepts only stdio://
135
+ * and ws://). Typing into the pane still works, so callers treat it as "no
136
+ * app-server here", not as a failure to report on every launch. */
137
+ export declare class AppServerUnsupportedError extends Error {
138
+ }
134
139
  /** Start one `codex app-server --listen unix://<socketPath>` and wait until its
135
140
  * socket accepts WebSocket connections. The server is the worker's; `stop()`
136
141
  * is the only owner. Extra `env` is layered over the current process's. */
@@ -23,6 +23,12 @@ export class AppServerRpcError extends Error {
23
23
  this.name = "AppServerRpcError";
24
24
  }
25
25
  }
26
+ /** This codex build cannot listen on a unix socket (0.113 accepts only stdio://
27
+ * and ws://). Typing into the pane still works, so callers treat it as "no
28
+ * app-server here", not as a failure to report on every launch. */
29
+ export class AppServerUnsupportedError extends Error {
30
+ }
31
+ const unixListenUnsupported = new Map();
26
32
  /** Start one `codex app-server --listen unix://<socketPath>` and wait until its
27
33
  * socket accepts WebSocket connections. The server is the worker's; `stop()`
28
34
  * is the only owner. Extra `env` is layered over the current process's. */
@@ -30,6 +36,9 @@ export async function spawnAppServer(options) {
30
36
  const env = { ...(options.replaceEnv ? {} : process.env), ...(options.env ?? {}), ...(options.codexHome ? { CODEX_HOME: options.codexHome } : {}) };
31
37
  // The merged environment's PATH, so a caller's partial `env` still finds codex.
32
38
  const codexBin = options.codexBin ?? codexExecutable(env);
39
+ const known = unixListenUnsupported.get(codexBin);
40
+ if (known)
41
+ throw new AppServerUnsupportedError(known);
33
42
  await mkdir(path.dirname(options.socketPath), { recursive: true, mode: 0o700 });
34
43
  // A socket file left by a dead server would pass the stat below and block the bind.
35
44
  await rm(options.socketPath, { force: true });
@@ -65,6 +74,12 @@ export async function spawnAppServer(options) {
65
74
  if (failure)
66
75
  throw new Error(`codex app-server could not start: ${failure.message}`);
67
76
  if (child.exitCode !== null || child.signalCode !== null) {
77
+ const detail = await why();
78
+ if (/unsupported --listen URL/.test(detail)) {
79
+ const message = `this codex build cannot listen on a unix socket (needs a newer codex)${detail}`;
80
+ unixListenUnsupported.set(codexBin, message);
81
+ throw new AppServerUnsupportedError(message);
82
+ }
68
83
  throw new Error(`codex app-server exited before ${options.socketPath} was ready (${child.exitCode ?? child.signalCode})${await why()}`);
69
84
  }
70
85
  if (await socketAccepts(options.socketPath))
@@ -14,6 +14,13 @@ export declare const REFRESH_AFTER_MS: number;
14
14
  /** The sign-in's last refresh, or undefined when auth.json holds no ChatGPT
15
15
  * sign-in (an API key, no file) and there is nothing to refresh. */
16
16
  export declare function lastCodexRefresh(file?: string): Promise<number | undefined>;
17
+ /** A doctor line for the ChatGPT sign-in Codex shares on this computer, or undefined when there is none
18
+ * to judge (no Codex, or an API key). A refresh token that has gone unused for over 9 days has expired
19
+ * server-side, and every `codex exec` and Hook-run worker then fails with a 401 until `codex login`. */
20
+ export declare function codexSignInCheck(file?: string, now?: number): Promise<{
21
+ ok: boolean;
22
+ message: string;
23
+ } | undefined>;
17
24
  export declare function codexAuthRefreshEnabled(env?: NodeJS.ProcessEnv): boolean;
18
25
  export interface CodexAuthRefresher {
19
26
  /** One proactive refresh through Codex's own flow (`account/read` with
@@ -2,6 +2,7 @@ import { readFile } from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { codexHome } from "../home-paths.js";
4
4
  import { logger } from "../logger.js";
5
+ import { AppServerUnsupportedError } from "./codex-app-server.js";
5
6
  import { object } from "./protocol.js";
6
7
  /**
7
8
  * Every Codex process on a computer shares one ChatGPT sign-in in
@@ -30,6 +31,21 @@ export async function lastCodexRefresh(file = path.join(codexHome(), "auth.json"
30
31
  return undefined;
31
32
  }
32
33
  }
34
+ /** Codex's own refresh threshold; a sign-in refreshed longer ago than this plus a day has not been kept alive. */
35
+ const CODEX_SIGNIN_STALE_MS = 9 * 86_400_000;
36
+ /** A doctor line for the ChatGPT sign-in Codex shares on this computer, or undefined when there is none
37
+ * to judge (no Codex, or an API key). A refresh token that has gone unused for over 9 days has expired
38
+ * server-side, and every `codex exec` and Hook-run worker then fails with a 401 until `codex login`. */
39
+ export async function codexSignInCheck(file, now = Date.now()) {
40
+ const at = await lastCodexRefresh(file);
41
+ if (at === undefined)
42
+ return undefined;
43
+ const days = Math.floor((now - at) / 86_400_000);
44
+ if (at === 0 || now - at > CODEX_SIGNIN_STALE_MS) {
45
+ return { ok: false, message: `Codex sign-in was last refreshed ${at === 0 ? "at an unknown time" : `${days} days ago`} and has probably expired (run: codex login)` };
46
+ }
47
+ return { ok: true, message: `Codex sign-in refreshed ${days === 0 ? "today" : `${days} day${days === 1 ? "" : "s"} ago`}` };
48
+ }
33
49
  export function codexAuthRefreshEnabled(env = process.env) {
34
50
  return !/^(?:0|off|false|no)$/i.test(env.PHREN_CODEX_AUTH_REFRESH ?? "");
35
51
  }
@@ -57,6 +73,12 @@ export class CodexAuthKeeper {
57
73
  await this.refresher.refreshAuth();
58
74
  }
59
75
  catch (error) {
76
+ // An old codex cannot run the server the refresh needs; that is a fact about this
77
+ // computer, not a failure to repeat in the log every hour.
78
+ if (error instanceof AppServerUnsupportedError) {
79
+ logger.debug("codex-auth", `Sign-in refresh skipped: ${error.message}`);
80
+ return false;
81
+ }
60
82
  logger.warn("codex-auth", `Could not refresh the Codex sign-in ahead of its workers: ${error instanceof Error ? error.message : String(error)}`);
61
83
  return false;
62
84
  }
@@ -63,8 +63,14 @@ export async function runDispatch(args) {
63
63
  } : undefined;
64
64
  const { "permission-mode": permissionMode, "keep-open": keepOpen, ...rest } = values;
65
65
  const ordinary = { ...Object.fromEntries(Object.entries(rest).filter(([key]) => !key.startsWith("parent-"))), ...(permissionMode !== undefined ? { permissionMode } : {}), ...(keepOpen ? { closeOnFinish: false } : {}) };
66
- const input = dispatchSchema.parse({ computer: positionals[0], project: positionals[1], ...ordinary,
66
+ const parsed = dispatchSchema.safeParse({ computer: positionals[0], project: positionals[1], ...ordinary,
67
67
  ...(parent ? { parent, parentTarget } : {}) });
68
+ if (!parsed.success) {
69
+ // Name the flag, not a schema path: a missing --label or --prompt is the usual slip.
70
+ const flag = (path) => path.length ? (["computer", "project"].includes(String(path[0])) ? `<${String(path[0])}>` : `--${String(path[0]).replace(/[A-Z]/g, c => `-${c.toLowerCase()}`)}`) : "input";
71
+ throw new Error(`phren dispatch: ${parsed.error.issues.map(issue => `${flag(issue.path)} ${issue.code === "invalid_type" && /received undefined/.test(issue.message) ? "is required" : issue.message}`).join("; ")}. Run phren dispatch for usage.`);
72
+ }
73
+ const input = parsed.data;
68
74
  // Run inside an agent's pane, the dispatch remembers that pane for return notices.
69
75
  const origin = await terminalPaneFromEnv();
70
76
  const result = await hookRequest("/v1/dispatch", { ...input, ...(origin ? { origin } : {}) }, undefined, 180_000);
@@ -30,7 +30,9 @@ async function serialized(key, work) {
30
30
  }
31
31
  }
32
32
  export async function writeRepoFile(root, requested, content, expectedVersion) {
33
- const key = `${await realpath(root).catch(() => root)}\u0000${requested}`;
33
+ // `f.txt` and `./f.txt` name one file, so they must share one lock.
34
+ const name = typeof requested === "string" ? path.posix.normalize(requested) : requested;
35
+ const key = `${await realpath(root).catch(() => root)}\u0000${name}`;
34
36
  return serialized(key, () => writeRepoFileNow(root, requested, content, expectedVersion));
35
37
  }
36
38
  async function writeRepoFileNow(root, requested, content, expectedVersion) {
@@ -1,3 +1,4 @@
1
+ import type { GitHost } from "./git-hosts.js";
1
2
  /** Tokens for the git hosts the Hook reads over HTTP (GitLab, gitboy). GitHub
2
3
  * goes through gh, which keeps its own sign-in.
3
4
  *
@@ -29,3 +30,8 @@ export declare function listHostTokens(file?: string): Promise<{
29
30
  user?: string;
30
31
  savedAt?: string;
31
32
  }[] | "unsafe">;
33
+ /** Credential fingerprint only: raw credentials never enter lookup keys.
34
+ * gh logout/switch-user rewrites hosts.yml even when its token is in a keychain. */
35
+ /** The lines of gh's hosts.yml under one host key (its user, protocol and any plain token). */
36
+ export declare function ghHostBlock(hostsYml: string, domain: string): string;
37
+ export declare function hostCredentialIdentity(host: GitHost): Promise<string>;
@@ -1,3 +1,6 @@
1
+ import { createHash } from "node:crypto";
2
+ import { homeDir } from "../home-paths.js";
3
+ import { invalidatePullsForDomain } from "./git.js";
1
4
  import { execFile } from "node:child_process";
2
5
  import { mkdir, readFile, stat } from "node:fs/promises";
3
6
  import path from "node:path";
@@ -58,6 +61,7 @@ export async function writeHostToken(domain, kind, token, user, file = gitHostsF
58
61
  delete hosts[key];
59
62
  await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
60
63
  await atomic(file, JSON.stringify({ hosts }, null, 2) + "\n", 0o600);
64
+ invalidatePullsForDomain(key);
61
65
  }
62
66
  /** The environment variables each host's own tools read. GITLAB_TOKEN is
63
67
  * glab's; it applies to gitlab.com, or to the domain GITLAB_HOST names.
@@ -108,3 +112,44 @@ export async function listHostTokens(file = gitHostsFile()) {
108
112
  return "unsafe";
109
113
  return Object.entries(store?.hosts ?? {}).map(([domain, { kind, user, savedAt }]) => ({ domain, kind, ...(user ? { user } : {}), ...(savedAt ? { savedAt } : {}) }));
110
114
  }
115
+ /** Credential fingerprint only: raw credentials never enter lookup keys.
116
+ * gh logout/switch-user rewrites hosts.yml even when its token is in a keychain. */
117
+ /** The lines of gh's hosts.yml under one host key (its user, protocol and any plain token). */
118
+ export function ghHostBlock(hostsYml, domain) {
119
+ const want = domain.trim().toLowerCase().replace(/\.$/, "");
120
+ const out = [];
121
+ let inside = false;
122
+ for (const line of hostsYml.split(/\r?\n/)) {
123
+ const top = /^(\S[^:]*):\s*$/.exec(line);
124
+ if (top) {
125
+ inside = top[1].trim().replace(/^["']|["']$/g, "").toLowerCase() === want;
126
+ if (inside)
127
+ out.push(line);
128
+ continue;
129
+ }
130
+ if (inside && (line.startsWith(" ") || line.startsWith("\t") || line.trim() === ""))
131
+ out.push(line);
132
+ else if (line.trim())
133
+ inside = false;
134
+ }
135
+ return out.join("\n").trimEnd();
136
+ }
137
+ export async function hostCredentialIdentity(host) {
138
+ let state = null;
139
+ if (host.kind === "github") {
140
+ const dir = process.env.GH_CONFIG_DIR || path.join(process.env.XDG_CONFIG_HOME || path.join(homeDir(), ".config"), "gh");
141
+ // Only this host's block of gh's hosts.yml: signing into another host must not change it.
142
+ const hosts = await readFile(path.join(dir, "hosts.yml"), "utf8").catch(() => "");
143
+ state = [
144
+ process.env.GH_TOKEN, process.env.GITHUB_TOKEN,
145
+ process.env.GH_ENTERPRISE_TOKEN, process.env.GITHUB_ENTERPRISE_TOKEN,
146
+ ghHostBlock(hosts, host.domain ?? "github.com"),
147
+ ];
148
+ }
149
+ else if (host.kind && host.domain) {
150
+ const store = await readStore();
151
+ state = [await resolveHostToken(host.kind, host.domain),
152
+ store && store !== "unsafe" ? store.hosts[normalDomain(host.domain)] : store];
153
+ }
154
+ return createHash("sha256").update(JSON.stringify(state)).digest("hex");
155
+ }
@@ -7,7 +7,7 @@ interface Run {
7
7
  }
8
8
  /** One process with stdout and stderr interleaved in arrival order, bounded,
9
9
  * never attached to a terminal and never prompting. */
10
- export declare function runCombined(command: string, args: string[], cwd: string, timeout: number, extraEnv?: NodeJS.ProcessEnv): Promise<Run>;
10
+ export declare function runCombined(command: string, args: string[], cwd: string, timeout: number, extraEnv?: NodeJS.ProcessEnv, killGraceMs?: number): Promise<Run>;
11
11
  /** `git commit` of the index only: no `-a`, no `--no-verify`, no amend. A
12
12
  * hook's refusal comes back as `{ ok: false, output }`, exactly as printed. */
13
13
  export declare function gitCommit(cwd: string, message: unknown): Promise<Json>;