@phren/cli 0.3.19 → 0.3.21

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 (76) hide show
  1. package/dist/bridge/agent-hooks.d.ts +38 -20
  2. package/dist/bridge/agent-hooks.js +100 -37
  3. package/dist/bridge/approval-summary.d.ts +4 -0
  4. package/dist/bridge/approval-summary.js +12 -1
  5. package/dist/bridge/changes.d.ts +4 -0
  6. package/dist/bridge/changes.js +25 -2
  7. package/dist/bridge/code-note.d.ts +1 -0
  8. package/dist/bridge/code-note.js +2 -2
  9. package/dist/bridge/codex-binary.d.ts +5 -0
  10. package/dist/bridge/codex-binary.js +7 -0
  11. package/dist/bridge/command.js +24 -6
  12. package/dist/bridge/dispatch-command.js +1 -1
  13. package/dist/bridge/dispatch-returns.d.ts +14 -2
  14. package/dist/bridge/dispatch-returns.js +72 -16
  15. package/dist/bridge/dispatch.d.ts +23 -0
  16. package/dist/bridge/dispatch.js +169 -8
  17. package/dist/bridge/folder-trust.d.ts +13 -3
  18. package/dist/bridge/folder-trust.js +42 -4
  19. package/dist/bridge/hand-off.js +2 -1
  20. package/dist/bridge/herdr.js +6 -5
  21. package/dist/bridge/hook-fast.d.ts +13 -1
  22. package/dist/bridge/hook-fast.js +17 -2
  23. package/dist/bridge/launch-brief.d.ts +3 -1
  24. package/dist/bridge/launch-brief.js +3 -1
  25. package/dist/bridge/memory-store.d.ts +7 -0
  26. package/dist/bridge/memory-store.js +37 -1
  27. package/dist/bridge/models.d.ts +11 -1
  28. package/dist/bridge/models.js +47 -2
  29. package/dist/bridge/schedule-format.d.ts +1 -1
  30. package/dist/bridge/schedule-format.js +1 -1
  31. package/dist/bridge/schedule-launch.js +5 -0
  32. package/dist/bridge/schedule-watch.d.ts +5 -2
  33. package/dist/bridge/schedule-watch.js +59 -20
  34. package/dist/bridge/server-launch.d.ts +26 -0
  35. package/dist/bridge/server-launch.js +122 -12
  36. package/dist/bridge/server-pane-routes.js +20 -13
  37. package/dist/bridge/server-routes.d.ts +5 -0
  38. package/dist/bridge/server-routes.js +2 -2
  39. package/dist/bridge/server-stream.js +12 -0
  40. package/dist/bridge/server.js +8 -3
  41. package/dist/bridge/session-activity.d.ts +6 -0
  42. package/dist/bridge/session-activity.js +16 -0
  43. package/dist/bridge/settings-switch.d.ts +7 -0
  44. package/dist/bridge/settings-switch.js +15 -0
  45. package/dist/bridge/speech-live.d.ts +45 -0
  46. package/dist/bridge/speech-live.js +413 -0
  47. package/dist/bridge/speech-transcribe.d.ts +13 -3
  48. package/dist/bridge/speech-transcribe.js +26 -8
  49. package/dist/bridge/speech-voice.d.ts +22 -1
  50. package/dist/bridge/speech-voice.js +20 -2
  51. package/dist/bridge/speech.d.ts +24 -4
  52. package/dist/bridge/speech.js +115 -14
  53. package/dist/bridge/stalls.d.ts +9 -2
  54. package/dist/bridge/stalls.js +20 -4
  55. package/dist/bridge/transcript-claude.js +39 -10
  56. package/dist/bridge/transcript-preview.d.ts +11 -1
  57. package/dist/bridge/transcript-preview.js +37 -11
  58. package/dist/bridge/transcripts.d.ts +2 -1
  59. package/dist/bridge/transcripts.js +7 -3
  60. package/dist/bridge/turn-records.d.ts +6 -3
  61. package/dist/bridge/turn-records.js +9 -4
  62. package/dist/bridge/usage.d.ts +1 -1
  63. package/dist/bridge/usage.js +4 -3
  64. package/dist/bridge/worker-close.js +3 -1
  65. package/dist/bridge/worker-unfinished.d.ts +43 -0
  66. package/dist/bridge/worker-unfinished.js +178 -0
  67. package/dist/bridge-hook.mjs +2458 -1351
  68. package/dist/cli-registry.js +3 -2
  69. package/dist/home-paths.d.ts +2 -0
  70. package/dist/home-paths.js +4 -0
  71. package/dist/modules/registry.js +2 -2
  72. package/dist/test-global-setup.js +2 -1
  73. package/dist/test-sandbox.d.ts +15 -0
  74. package/dist/test-sandbox.js +36 -0
  75. package/package.json +1 -1
  76. package/starter/global/skills/conductor/SKILL.md +2 -1
@@ -1,4 +1,5 @@
1
1
  import { type ModuleSnapshot } from "../modules/runtime.js";
2
+ import { type ServerResponse } from "node:http";
2
3
  import { type Json, type Provider, type Target } from "./protocol.js";
3
4
  import { ToolChanges } from "./changes.js";
4
5
  import { ApprovalPushService } from "./push.js";
@@ -15,6 +16,10 @@ export { ApprovalWatchLeases, PushBindingStore, recordedSession } from "./agent-
15
16
  /** Where a held request's answer goes: the callback's HTTP response, or the
16
17
  * reply to a Codex app-server request (codex-servers.ts). Either takes the
17
18
  * PermissionRequest-shaped JSON; "{}" gives the request back to the terminal. */
19
+ /** Whether the caller hung up on `res` before it was answered. Not
20
+ * `req.destroyed`: a request body read to its end is destroyed on every
21
+ * Node this supports, so that read as a hang-up on each normal callback. */
22
+ export declare function watchHangUp(res: ServerResponse): () => boolean;
18
23
  interface HeldReply {
19
24
  end(body: string): unknown;
20
25
  readonly destroyed: boolean;
@@ -83,31 +88,28 @@ export declare const OPENCODE_APPROVAL_OPTIONS: Json[];
83
88
  * anything else. */
84
89
  export declare function opencodePermissionReply(decision: unknown): "once" | "always" | "reject" | undefined;
85
90
  export type DeliveryOutcome = "delivered" | "blocked" | "pending";
86
- /** A phone message the Hook answered as delivered or queued, kept under the
87
- * phone's delivery id so the phone can ask what became of it by that id.
88
- * Holds a hash of the prompt's words, never the prompt. */
91
+ /** A phone message typed under its delivery id, so the phone can ask what
92
+ * became of it by that id. `typed` until the Hook answers it queued; the
93
+ * typed record's own settlement moves it on by id, never by its words. */
89
94
  interface TrackedDelivery {
90
95
  source: Provider;
91
96
  session: string;
92
- key: string;
93
- state: "queued" | "delivered" | "blocked";
97
+ state: "typed" | "queued" | "delivered" | "blocked";
94
98
  at: number;
95
99
  }
96
- export type TrackedState = TrackedDelivery["state"] | "unknown";
97
- /** This socket is deliberately separate from the phone's HTTP pipe. Only local
98
- * agent callbacks can register identities or create an approval request. */
100
+ export type TrackedState = Exclude<TrackedDelivery["state"], "typed"> | "unknown";
99
101
  export declare class AgentHooks {
100
102
  readonly push: ApprovalPushService;
101
103
  private modules?;
102
104
  readonly changes: ToolChanges;
103
105
  private pending;
104
- /** Prompts Phren has typed into a pane, by their text, until the agent that
106
+ /** Prompts Phren has typed into a pane, by a hash of their words, until the agent that
105
107
  * actually receives one reports in through UserPromptSubmit. Herdr writes
106
108
  * to a pane, not a conversation; the receiving agent's hook is the only
107
109
  * party that knows which conversation consumed the text, so it is the one
108
110
  * that can refuse it when that is not the conversation the phone meant. */
109
111
  private deliveries;
110
- /** Phone messages by delivery id, until TRACK_MS: see `trackDelivery`. */
112
+ /** Phone messages by delivery id, until TRACK_MS: see `queueDelivery`. */
111
113
  private tracked;
112
114
  /** The permission request a conversation is drawing in its own terminal
113
115
  * because nobody was there to hold it: what the phone shows above its
@@ -219,23 +221,29 @@ export declare class AgentHooks {
219
221
  * text, "blocked" if another conversation in the pane tried to, or "pending"
220
222
  * after `waitMs`: a busy agent queues typed input and submits it only when
221
223
  * its turn ends, so the record outlives the wait (up to ten minutes) and a
222
- * late submission to the wrong conversation is still refused. */
223
- expectDelivery(target: Target, text: string, waitMs?: number, signal?: AbortSignal): Promise<DeliveryOutcome>;
224
+ * late submission to the wrong conversation is still refused. A phone
225
+ * message's `id` follows the record, so its outcome lands on that id. */
226
+ expectDelivery(target: Target, text: string, waitMs?: number, signal?: AbortSignal, id?: string): Promise<DeliveryOutcome>;
224
227
  /** A prompt Phren typed into `target` that its conversation has not submitted yet. */
225
228
  deliveryPending(target: Target, text: string): boolean;
226
229
  /** Wait again for a delivery `expectDelivery` already reported pending,
227
230
  * after the Hook pressed Enter a second time. */
228
231
  awaitLateDelivery(target: Target, text: string, waitMs?: number): Promise<DeliveryOutcome>;
229
- /** Remember a phone message's outcome under its delivery id. A queued one
230
- * is tracked only while its typed record still waits for the agent's hook,
231
- * so the hook's later answer always reaches it (`settleTracked`). */
232
- trackDelivery(id: string, target: Target, text: string, state: "queued" | "delivered"): void;
232
+ private track;
233
+ /** The Hook answered the phone message `id` as queued: its typed record
234
+ * still waits for the agent's hook, which settles it by this id. */
235
+ queueDelivery(id: string, target: Target): void;
233
236
  /** What became of the phone message `id` sent to `target`'s conversation:
234
237
  * queued until the agent submits it, then delivered, or blocked when
235
- * another conversation in the pane took it. Unknown when the Hook did not
236
- * track it, it was for another conversation, or it is older than TRACK_MS. */
238
+ * another conversation in the pane took it. Unknown while the Hook has not
239
+ * answered it, for another conversation, or older than TRACK_MS. A
240
+ * message answered uncertain still turns delivered once its hook takes it. */
237
241
  deliveryState(id: string, target: Target): TrackedState;
238
- /** The oldest queued message tracked for `delivery`'s conversation with these words. */
242
+ /** Every known phone message to `target`'s conversation, for its stream. */
243
+ deliveriesFor(target: Target): {
244
+ deliveryId: string;
245
+ state: TrackedState;
246
+ }[];
239
247
  private settleTracked;
240
248
  /** The conversation `target` just submitted `prompt`. Nothing Phren typed
241
249
  * matches: a locally typed prompt, always allowed. Otherwise the oldest
@@ -392,4 +400,14 @@ export declare function stopFacts(value: Json): {
392
400
  background?: number;
393
401
  reply?: string;
394
402
  };
395
- export declare function agentHook(source: Provider): Promise<void>;
403
+ /** One agent callback, run as `hook <source>`. Resolves "abandoned" when a
404
+ * tool call's callback ran out of its budget: the caller then exits at once,
405
+ * since a socket or a process read still pending would hold the agent. */
406
+ export declare function agentHook(source: Provider, elapsed?: () => number): Promise<void | "abandoned">;
407
+ /**
408
+ * Runs a callback's work. A PreToolUse or PostToolUse callback gets what is
409
+ * left of TOOL_HOOK_BUDGET_MS since its process started (hook-fast.ts says
410
+ * why): "abandoned" once that runs out, and the caller exits without an
411
+ * answer so the tool runs. Every other event runs to its own timeouts.
412
+ */
413
+ export declare function withinToolBudget<T>(event: string, work: (left: () => number) => Promise<T>, elapsed?: () => number, budgetMs?: number): Promise<T | "abandoned">;
@@ -10,6 +10,7 @@ import { createHash, randomUUID } from "node:crypto";
10
10
  import { hostname } from "node:os";
11
11
  import { atomicInPrivateDir, BridgeError, bridgeRoot, object, objects, provider, targetSchema } from "./protocol.js";
12
12
  import { findPane, knownPanes, paneForCodexSession, servers, snapshot, trustedDirectory, validateTarget } from "./herdr.js";
13
+ import { TOOL_HOOK_BUDGET_MS } from "./hook-fast.js";
13
14
  import { underCodexDaemon } from "./codex-daemon.js";
14
15
  import { codexAutoReview } from "./codex-review-mode.js";
15
16
  import { terminalPaneFromEnv, terminalProvider } from "./terminal.js";
@@ -19,7 +20,7 @@ import { phrenStoreRoot, unwrapPastedContent } from "./transcripts.js";
19
20
  import { archiveFinishedFanouts, blockedFanouts, fanoutAsking } from "./fanouts.js";
20
21
  import { ensureGrant, findGrant } from "./grants.js";
21
22
  import { ApprovalPushService } from "./push.js";
22
- import { approvalSummary } from "./approval-summary.js";
23
+ import { approvalSummary, paneProject } from "./approval-summary.js";
23
24
  import { computerDisplayName } from "./pair.js";
24
25
  import { intervalFromEnv } from "./limits.js";
25
26
  import { answerClaudeQuestionDialog, claudeQuestionDialog } from "./claude-question-dialog.js";
@@ -58,6 +59,19 @@ const FANOUT_SWEEP_MS = 5_000;
58
59
  * forward, and the card goes only when the ask is gone or the pane is dead. */
59
60
  const SERVED_ASK_MS = 60 * 60_000;
60
61
  const FANOUT_ARCHIVE_MS = 60 * 60 * 1000;
62
+ /** Where a held request's answer goes: the callback's HTTP response, or the
63
+ * reply to a Codex app-server request (codex-servers.ts). Either takes the
64
+ * PermissionRequest-shaped JSON; "{}" gives the request back to the terminal. */
65
+ /** Whether the caller hung up on `res` before it was answered. Not
66
+ * `req.destroyed`: a request body read to its end is destroyed on every
67
+ * Node this supports, so that read as a hang-up on each normal callback. */
68
+ export function watchHangUp(res) {
69
+ let closed = res.destroyed || res.socket?.destroyed === true;
70
+ const onClose = () => { if (!res.writableEnded)
71
+ closed = true; };
72
+ res.once("close", onClose);
73
+ return () => { res.off("close", onClose); return closed || res.destroyed; };
74
+ }
61
75
  /** The approval card's tool and input for an app-server request, in the
62
76
  * shapes `approvalSummary` and the phone already read for Codex's hook.
63
77
  * Undefined for questions (`item/tool/requestUserInput`) and MCP
@@ -143,21 +157,27 @@ function promptKey(text) {
143
157
  .replace(/\[Image #\d+\]/g, " ").replace(/\s+/g, " ").trim();
144
158
  }
145
159
  const PICTURE_PATH_LINE = /^\s*\/.*\.(?:png|jpe?g|gif|webp)\s*$/i;
146
- const trackKey = (text) => createHash("sha256").update(promptKey(text)).digest("hex");
160
+ const promptHash = (text) => createHash("sha256").update(promptKey(text)).digest("hex");
147
161
  /** This socket is deliberately separate from the phone's HTTP pipe. Only local
148
162
  * agent callbacks can register identities or create an approval request. */
163
+ /** The project a notification names for a pane's folder: none for the
164
+ * phren store, whose path is never shown on the phone. */
165
+ function projectField(cwd) {
166
+ const project = paneProject(cwd, phrenStoreRoot());
167
+ return project ? { project } : {};
168
+ }
149
169
  export class AgentHooks {
150
170
  push;
151
171
  modules;
152
172
  changes = new ToolChanges();
153
173
  pending = new Map();
154
- /** Prompts Phren has typed into a pane, by their text, until the agent that
174
+ /** Prompts Phren has typed into a pane, by a hash of their words, until the agent that
155
175
  * actually receives one reports in through UserPromptSubmit. Herdr writes
156
176
  * to a pane, not a conversation; the receiving agent's hook is the only
157
177
  * party that knows which conversation consumed the text, so it is the one
158
178
  * that can refuse it when that is not the conversation the phone meant. */
159
179
  deliveries = new Map();
160
- /** Phone messages by delivery id, until TRACK_MS: see `trackDelivery`. */
180
+ /** Phone messages by delivery id, until TRACK_MS: see `queueDelivery`. */
161
181
  tracked = new Map();
162
182
  /** The permission request a conversation is drawing in its own terminal
163
183
  * because nobody was there to hold it: what the phone shows above its
@@ -307,7 +327,7 @@ export class AgentHooks {
307
327
  // The held request is what stops a later sweep from pushing again; a
308
328
  // failed delivery only drops the binding and leaves the card in place.
309
329
  void this.push.notify({ binding, provider: "opencode", question: false, expiresAt: String(request.expiresAt),
310
- ...(cwd ? { project: path.basename(cwd) } : {}), computer: this.computerName, ...summary })
330
+ ...projectField(cwd), computer: this.computerName, ...summary })
311
331
  .then(delivered => { if (!delivered)
312
332
  this.pushBindings.dropAction(id); })
313
333
  .catch(() => { });
@@ -617,11 +637,14 @@ export class AgentHooks {
617
637
  * text, "blocked" if another conversation in the pane tried to, or "pending"
618
638
  * after `waitMs`: a busy agent queues typed input and submits it only when
619
639
  * its turn ends, so the record outlives the wait (up to ten minutes) and a
620
- * late submission to the wrong conversation is still refused. */
621
- expectDelivery(target, text, waitMs = 1_500, signal) {
622
- const key = promptKey(text);
623
- if (!key || signal?.aborted)
640
+ * late submission to the wrong conversation is still refused. A phone
641
+ * message's `id` follows the record, so its outcome lands on that id. */
642
+ expectDelivery(target, text, waitMs = 1_500, signal, id) {
643
+ if (!promptKey(text) || signal?.aborted)
624
644
  return Promise.resolve("pending");
645
+ const key = promptHash(text);
646
+ if (id)
647
+ this.track(id, target, "typed");
625
648
  return new Promise(resolve => {
626
649
  let settled = false;
627
650
  const list = this.deliveries.get(key) ?? [];
@@ -644,9 +667,10 @@ export class AgentHooks {
644
667
  if (outcome !== "pending") {
645
668
  clearTimeout(delivery.timer);
646
669
  remove();
670
+ this.settleTracked(delivery, outcome);
647
671
  }
648
672
  };
649
- const delivery = { source: target.source, session: target.session, settle, timer: setTimeout(() => settle("pending"), waitMs) };
673
+ const delivery = { source: target.source, session: target.session, ...(id ? { id } : {}), settle, timer: setTimeout(() => settle("pending"), waitMs) };
650
674
  // Only cancel after a provider explicitly refused before writing. A
651
675
  // possibly delivered paste keeps its guard against the wrong session.
652
676
  const cancel = () => { clearTimeout(delivery.timer); settle("pending"); remove(); };
@@ -662,12 +686,12 @@ export class AgentHooks {
662
686
  }
663
687
  /** A prompt Phren typed into `target` that its conversation has not submitted yet. */
664
688
  deliveryPending(target, text) {
665
- return !!this.deliveries.get(promptKey(text))?.some(entry => entry.source === target.source && entry.session === target.session);
689
+ return !!this.deliveries.get(promptHash(text))?.some(entry => entry.source === target.source && entry.session === target.session);
666
690
  }
667
691
  /** Wait again for a delivery `expectDelivery` already reported pending,
668
692
  * after the Hook pressed Enter a second time. */
669
693
  awaitLateDelivery(target, text, waitMs = 2_500) {
670
- const delivery = this.deliveries.get(promptKey(text))?.find(entry => entry.source === target.source && entry.session === target.session);
694
+ const delivery = this.deliveries.get(promptHash(text))?.find(entry => entry.source === target.source && entry.session === target.session);
671
695
  if (!delivery)
672
696
  return Promise.resolve("pending");
673
697
  return new Promise(resolve => {
@@ -676,34 +700,41 @@ export class AgentHooks {
676
700
  delivery.late = outcome => { clearTimeout(timer); delivery.late = undefined; resolve(outcome); };
677
701
  });
678
702
  }
679
- /** Remember a phone message's outcome under its delivery id. A queued one
680
- * is tracked only while its typed record still waits for the agent's hook,
681
- * so the hook's later answer always reaches it (`settleTracked`). */
682
- trackDelivery(id, target, text, state) {
683
- if (state === "queued" && !this.deliveryPending(target, text))
684
- return;
703
+ track(id, target, state) {
685
704
  const now = Date.now();
686
705
  for (const [key, entry] of this.tracked)
687
706
  if (now - entry.at > TRACK_MS)
688
707
  this.tracked.delete(key);
689
708
  while (this.tracked.size >= 512)
690
709
  this.tracked.delete(this.tracked.keys().next().value);
691
- this.tracked.set(id, { source: target.source, session: target.session, key: trackKey(text), state, at: now });
710
+ this.tracked.set(id, { source: target.source, session: target.session, state, at: now });
711
+ }
712
+ /** The Hook answered the phone message `id` as queued: its typed record
713
+ * still waits for the agent's hook, which settles it by this id. */
714
+ queueDelivery(id, target) {
715
+ const entry = this.tracked.get(id);
716
+ if (entry?.state === "typed" && entry.source === target.source && entry.session === target.session)
717
+ entry.state = "queued";
692
718
  }
693
719
  /** What became of the phone message `id` sent to `target`'s conversation:
694
720
  * queued until the agent submits it, then delivered, or blocked when
695
- * another conversation in the pane took it. Unknown when the Hook did not
696
- * track it, it was for another conversation, or it is older than TRACK_MS. */
721
+ * another conversation in the pane took it. Unknown while the Hook has not
722
+ * answered it, for another conversation, or older than TRACK_MS. A
723
+ * message answered uncertain still turns delivered once its hook takes it. */
697
724
  deliveryState(id, target) {
698
725
  const entry = this.tracked.get(id);
699
- return entry && entry.source === target.source && entry.session === target.session && Date.now() - entry.at <= TRACK_MS ? entry.state : "unknown";
726
+ return entry && entry.state !== "typed" && entry.source === target.source && entry.session === target.session && Date.now() - entry.at <= TRACK_MS ? entry.state : "unknown";
700
727
  }
701
- /** The oldest queued message tracked for `delivery`'s conversation with these words. */
702
- settleTracked(delivery, prompt, state) {
703
- const key = trackKey(prompt);
704
- const entry = [...this.tracked.values()].find(item => item.state === "queued" && item.key === key && item.source === delivery.source && item.session === delivery.session);
705
- if (entry)
706
- entry.state = state;
728
+ /** Every known phone message to `target`'s conversation, for its stream. */
729
+ deliveriesFor(target) {
730
+ return [...this.tracked.keys()].map(deliveryId => ({ deliveryId, state: this.deliveryState(deliveryId, target) })).filter(item => item.state !== "unknown");
731
+ }
732
+ settleTracked(delivery, outcome) {
733
+ const entry = delivery.id ? this.tracked.get(delivery.id) : undefined;
734
+ if (entry && entry.source === delivery.source && entry.session === delivery.session) {
735
+ entry.state = outcome;
736
+ entry.at = Date.now();
737
+ }
707
738
  }
708
739
  /** The conversation `target` just submitted `prompt`. Nothing Phren typed
709
740
  * matches: a locally typed prompt, always allowed. Otherwise the oldest
@@ -711,14 +742,13 @@ export class AgentHooks {
711
742
  * conversation is told to drop it, so the text is never spoken to the
712
743
  * wrong agent and the phone can safely send it again. */
713
744
  submitted(target, prompt) {
714
- const list = this.deliveries.get(promptKey(prompt));
745
+ const list = this.deliveries.get(promptHash(prompt));
715
746
  // The same words sent to two conversations at once: each one's own
716
747
  // submission settles its own record, not whichever was typed first.
717
748
  const delivery = list?.find(entry => entry.source === target.source && entry.session === target.session) ?? list?.[0];
718
749
  if (!delivery)
719
750
  return {};
720
751
  const own = delivery.source === target.source && delivery.session === target.session;
721
- this.settleTracked(delivery, prompt, own ? "delivered" : "blocked");
722
752
  if (own) {
723
753
  delivery.settle("delivered");
724
754
  return {};
@@ -734,7 +764,8 @@ export class AgentHooks {
734
764
  await recordTurn(target.server, target.pane, { event: String(body.event), terminal: pane.terminal_id, source: target.source, session: target.session,
735
765
  ...(dispatch ? { dispatch } : {}),
736
766
  ...(typeof body.background === "number" ? { background: body.background } : {}),
737
- ...(typeof body.reply === "string" ? { reply: body.reply } : {}) }).catch(() => undefined);
767
+ ...(typeof body.reply === "string" ? { reply: body.reply } : {}),
768
+ ...(body.event === "Stop" && typeof body.cwd === "string" ? { cwd: body.cwd } : {}) }).catch(() => undefined);
738
769
  }
739
770
  rememberTerminalPrompt(target, body) {
740
771
  const tool = String(body.tool || "action").slice(0, 200);
@@ -1384,7 +1415,7 @@ export class AgentHooks {
1384
1415
  const summary = entry.request ? { request: entry.request, requestKind: entry.requestKind ?? "other" }
1385
1416
  : approvalSummary({ tool: entry.tool, message: title });
1386
1417
  void this.push.notify({ binding, provider: target.source, question: entry.tool === "AskUserQuestion", expiresAt: new Date(expiresAt).toISOString(),
1387
- ...(cwd ? { project: path.basename(cwd) } : {}), computer: this.computerName, ...summary })
1418
+ ...projectField(cwd), computer: this.computerName, ...summary })
1388
1419
  .then(delivered => { if (!delivered)
1389
1420
  this.dropDialogPush(key); }).catch(() => this.dropDialogPush(key));
1390
1421
  }
@@ -1601,7 +1632,7 @@ export class AgentHooks {
1601
1632
  const binding = randomUUID();
1602
1633
  this.pushBindings.add(binding, { action, expiresAt });
1603
1634
  void this.push.notify({ binding, provider: "codex", question: false, expiresAt: new Date(expiresAt).toISOString(),
1604
- ...(cwd ? { project: path.basename(cwd) } : {}), computer: this.computerName, ...summary })
1635
+ ...projectField(cwd), computer: this.computerName, ...summary })
1605
1636
  .then(delivered => { if (!delivered)
1606
1637
  this.pushBindings.consume(binding); }).catch(() => { });
1607
1638
  }
@@ -1728,8 +1759,13 @@ export class AgentHooks {
1728
1759
  await this.recordTurn(target, pane, body, dispatch);
1729
1760
  if ((this.modules?.has("git") ?? true) && ["PreToolUse", "PostToolUse"].includes(String(body.event)) && capturesChanges(String(body.tool), input)) {
1730
1761
  const conversation = `${target.source}:${target.session}`, id = String(body.toolUseId || "").slice(0, 200);
1731
- if (body.event === "PreToolUse")
1762
+ if (body.event === "PreToolUse") {
1763
+ const hungUp = watchHangUp(res);
1732
1764
  await this.changes.before(conversation, id, typeof body.cwd === "string" && path.isAbsolute(body.cwd) ? body.cwd : await trustedDirectory(pane), command ?? "", input);
1765
+ // The callback gave up (TOOL_HOOK_BUDGET_MS) and the tool ran while this was read.
1766
+ if (hungUp())
1767
+ this.changes.drop(conversation, id);
1768
+ }
1733
1769
  else
1734
1770
  await this.changes.after(conversation, id);
1735
1771
  res.end("{}");
@@ -1805,7 +1841,7 @@ export class AgentHooks {
1805
1841
  this.pushBindings.add(binding, { action, expiresAt: pushExpiresAt });
1806
1842
  this.pushedHolds.set(action, pushExpiresAt);
1807
1843
  void this.push.notify({ binding, provider: target.source, question: body.tool === "AskUserQuestion",
1808
- expiresAt: new Date(pushExpiresAt).toISOString(), ...(cwd ? { project: path.basename(cwd) } : {}), computer: this.computerName, ...summary }).catch(() => false).then(delivered => {
1844
+ expiresAt: new Date(pushExpiresAt).toISOString(), ...projectField(cwd), computer: this.computerName, ...summary }).catch(() => false).then(delivered => {
1809
1845
  if (!delivered) {
1810
1846
  this.pushBindings.consume(binding);
1811
1847
  this.pushedHolds.delete(action);
@@ -1900,7 +1936,10 @@ export function stopFacts(value) {
1900
1936
  return { ...(tasks ? { background: tasks.length } : {}),
1901
1937
  ...(typeof value.last_assistant_message === "string" && value.last_assistant_message.trim() ? { reply: value.last_assistant_message.slice(0, 16_384) } : {}) };
1902
1938
  }
1903
- export async function agentHook(source) {
1939
+ /** One agent callback, run as `hook <source>`. Resolves "abandoned" when a
1940
+ * tool call's callback ran out of its budget: the caller then exits at once,
1941
+ * since a socket or a process read still pending would hold the agent. */
1942
+ export async function agentHook(source, elapsed = () => performance.now()) {
1904
1943
  provider.parse(source);
1905
1944
  // A missing helper must never prevent the coding agent from running.
1906
1945
  // Inside Herdr only Herdr's pane counts; elsewhere a tmux pane does.
@@ -1919,6 +1958,30 @@ export async function agentHook(source) {
1919
1958
  const target = targetSchema.parse({ server: place.server, workspace: place.workspace, tab: place.tab,
1920
1959
  pane: place.pane, source, session: value.session_id || value.sessionId });
1921
1960
  const event = String(value.hook_event_name || "SessionStart");
1961
+ return withinToolBudget(event, left => forwardHook(source, target, event, value, left), elapsed);
1962
+ }
1963
+ /**
1964
+ * Runs a callback's work. A PreToolUse or PostToolUse callback gets what is
1965
+ * left of TOOL_HOOK_BUDGET_MS since its process started (hook-fast.ts says
1966
+ * why): "abandoned" once that runs out, and the caller exits without an
1967
+ * answer so the tool runs. Every other event runs to its own timeouts.
1968
+ */
1969
+ export async function withinToolBudget(event, work, elapsed = () => performance.now(), budgetMs = TOOL_HOOK_BUDGET_MS) {
1970
+ if (!event.endsWith("ToolUse"))
1971
+ return work(() => Infinity);
1972
+ const left = () => Math.floor(budgetMs - elapsed());
1973
+ if (left() <= 0)
1974
+ return "abandoned";
1975
+ let timer;
1976
+ const expired = new Promise(resolve => { timer = setTimeout(() => resolve("abandoned"), left()); });
1977
+ try {
1978
+ return await Promise.race([work(left), expired]);
1979
+ }
1980
+ finally {
1981
+ clearTimeout(timer);
1982
+ }
1983
+ }
1984
+ async function forwardHook(source, target, event, value, left) {
1922
1985
  const modules = moduleSnapshot(defaultPhrenPath(), undefined, true);
1923
1986
  if (!modules.has("hook") || (event.endsWith("ToolUse") && !modules.has("git")))
1924
1987
  return;
@@ -1941,7 +2004,7 @@ export async function agentHook(source) {
1941
2004
  ...(event === "UserPromptSubmit" && typeof value.prompt === "string" ? { prompt: value.prompt.slice(0, 65_536) } : {}),
1942
2005
  ...(event === "Stop" ? stopFacts(value) : {}) });
1943
2006
  await new Promise(resolve => {
1944
- const req = request({ socketPath: localSocket(), path: "/hook", method: "POST", timeout: event === "PermissionRequest" ? 58_000 : event.endsWith("ToolUse") ? 8_000 : 12_000,
2007
+ const req = request({ socketPath: localSocket(), path: "/hook", method: "POST", timeout: event === "PermissionRequest" ? 58_000 : event.endsWith("ToolUse") ? Math.max(1, left()) : 12_000,
1945
2008
  headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(data) } }, res => {
1946
2009
  let result = "";
1947
2010
  res.on("data", chunk => { result += chunk.toString(); if (result.length > 16_384)
@@ -7,6 +7,10 @@ export interface ApprovalRequest {
7
7
  question?: boolean;
8
8
  }
9
9
  export declare function approvalTitle(agent: string, project?: string, computer?: string): string;
10
+ /** A pane's folder as the project a notification names: its last part, or
11
+ * none for the phren store (`~/.phren`, or `store`), whose path names no
12
+ * project and is never shown on the phone. */
13
+ export declare function paneProject(cwd: string | undefined, store?: string): string | undefined;
10
14
  /** Sanitize the whole line before shortening it for the notification. */
11
15
  export declare function redactApproval(value: string): string;
12
16
  export declare function shortApproval(value: string): string;
@@ -4,9 +4,20 @@ const fields = (value) => value && typeof value === "object" && !Array.isArray(v
4
4
  const string = (value) => typeof value === "string" && value.trim() ? value : undefined;
5
5
  const oneLine = (value) => value.replace(/\s+/g, " ").trim();
6
6
  export function approvalTitle(agent, project, computer) {
7
- const label = { claude: "Claude", codex: "Codex", opencode: "opencode", copilot: "Copilot" }[agent.toLowerCase()] ?? "Your agent";
7
+ const label = { claude: "Claude", codex: "Codex", opencode: "opencode", copilot: "Copilot", phren: "Phren" }[agent.toLowerCase()] ?? "Your agent";
8
8
  return `${label}${project ? ` · ${project}` : ""}${computer ? ` on ${computer}` : ""}`;
9
9
  }
10
+ /** A pane's folder as the project a notification names: its last part, or
11
+ * none for the phren store (`~/.phren`, or `store`), whose path names no
12
+ * project and is never shown on the phone. */
13
+ export function paneProject(cwd, store) {
14
+ if (!cwd)
15
+ return undefined;
16
+ const resolved = path.resolve(cwd);
17
+ if (path.basename(resolved) === ".phren" || (store && resolved === path.resolve(store)))
18
+ return undefined;
19
+ return path.basename(resolved) || undefined;
20
+ }
10
21
  /** Sanitize the whole line before shortening it for the notification. */
11
22
  export function redactApproval(value) {
12
23
  return value
@@ -45,6 +45,10 @@ export declare class ToolChanges {
45
45
  private discard;
46
46
  close(): Promise<void>;
47
47
  before(conversation: string, toolUseId: string, cwd: string, command: string, input?: Json): Promise<void>;
48
+ /** Forget the snapshot of a tool call whose PreToolUse callback gave up
49
+ * before the snapshot was taken: the tool may have run while it was read,
50
+ * so no diff is shown for that call rather than a wrong one. */
51
+ drop(conversation: string, toolUseId: string): void;
48
52
  private claim;
49
53
  /** Whether another conversation's call named this file while `snapshot` ran. */
50
54
  private claimedElsewhere;
@@ -232,7 +232,7 @@ export class ToolChanges {
232
232
  this.claim(conversation, toolUseId, claimed);
233
233
  if (this.snapshots.size >= 64 || this.snapshots.has(key))
234
234
  return;
235
- const snapshot = { at: Date.now(), conversation, own: new Set(claimed), trees: new Map() };
235
+ const snapshot = { at: Date.now(), conversation, own: new Set(claimed), trees: new Map(), taking: true };
236
236
  this.snapshots.set(key, snapshot);
237
237
  try {
238
238
  await this.budget(async (signal) => {
@@ -255,6 +255,11 @@ export class ToolChanges {
255
255
  }
256
256
  signal.throwIfAborted();
257
257
  });
258
+ snapshot.taking = false;
259
+ if (snapshot.dropped) {
260
+ await this.discard(snapshot);
261
+ return;
262
+ }
258
263
  if (!snapshot.trees.size) {
259
264
  this.snapshots.delete(key);
260
265
  return;
@@ -269,10 +274,24 @@ export class ToolChanges {
269
274
  snapshot.expiry.unref();
270
275
  }
271
276
  catch {
272
- this.snapshots.delete(key);
277
+ if (this.snapshots.get(key) === snapshot)
278
+ this.snapshots.delete(key);
273
279
  await this.discard(snapshot);
274
280
  }
275
281
  }
282
+ /** Forget the snapshot of a tool call whose PreToolUse callback gave up
283
+ * before the snapshot was taken: the tool may have run while it was read,
284
+ * so no diff is shown for that call rather than a wrong one. */
285
+ drop(conversation, toolUseId) {
286
+ const key = `${conversation}\0${toolUseId}`, snapshot = this.snapshots.get(key);
287
+ if (!snapshot || snapshot.result)
288
+ return;
289
+ this.snapshots.delete(key);
290
+ if (snapshot.taking)
291
+ snapshot.dropped = true;
292
+ else
293
+ void this.discard(snapshot).catch(() => { });
294
+ }
276
295
  claim(conversation, toolUseId, paths) {
277
296
  const now = Date.now();
278
297
  this.claims = this.claims.filter(claim => claim.end === undefined ? now - claim.start < 30 * 60_000 : now - claim.end < CLAIM_RETENTION);
@@ -291,6 +310,10 @@ export class ToolChanges {
291
310
  claim.end ??= Date.now();
292
311
  if (!snapshot)
293
312
  return;
313
+ if (snapshot.taking) {
314
+ this.drop(conversation, toolUseId);
315
+ return;
316
+ }
294
317
  snapshot.result ??= this.compute(snapshot);
295
318
  const files = await snapshot.result;
296
319
  if (this.snapshots.get(key) === snapshot) {
@@ -14,6 +14,7 @@ export declare const codeNoteSchema: z.ZodObject<{
14
14
  harness: z.ZodEnum<{
15
15
  claude: "claude";
16
16
  codex: "codex";
17
+ copilot: "copilot";
17
18
  opencode: "opencode";
18
19
  }>;
19
20
  }, z.core.$strict>]>>;
@@ -3,7 +3,7 @@ import { z } from "zod";
3
3
  import { addFindingToFile } from "../shared/content.js";
4
4
  import { requireCodePackage } from "./code-routes.js";
5
5
  import { BridgeError, sessionId } from "./protocol.js";
6
- import { projectName } from "./dispatch.js";
6
+ import { DISPATCH_HARNESSES, projectName } from "./dispatch.js";
7
7
  export const codeNoteSchema = z.object({
8
8
  store: z.string().min(1).max(200).optional(),
9
9
  project: projectName,
@@ -12,7 +12,7 @@ export const codeNoteSchema = z.object({
12
12
  name: z.string().min(1).max(4600).optional(), symbol: z.string().min(1).max(4600).optional(),
13
13
  file: z.string().min(1).max(4096).refine(file => !path.isAbsolute(file) && !file.includes("\0") && !file.split(/[\\/]/).includes("..")),
14
14
  line: z.number().int().positive(), text: z.string().trim().min(1).max(4500).refine(text => !/[\x00-\x08\x0b-\x1f\x7f]/.test(text)),
15
- target: z.union([z.object({ session: sessionId }).strict(), z.object({ harness: z.enum(["codex", "claude", "opencode"]) }).strict()]).optional(),
15
+ target: z.union([z.object({ session: sessionId }).strict(), z.object({ harness: z.enum(DISPATCH_HARNESSES) }).strict()]).optional(),
16
16
  }).strict();
17
17
  const noteName = (note) => {
18
18
  const name = note.name ?? note.symbol;
@@ -1,3 +1,8 @@
1
+ /** What `PHREN_CODEX_BINARY=off` resolves to: a path no spawn can run, so every
2
+ * helper call fails as if codex were not installed. The vitest config sets it:
3
+ * Codex 0.158 leaves a detached `app-server --managed-daemon` behind for the
4
+ * HOME it ran under, and a test run's throwaway HOME is deleted under it. */
5
+ export declare const CODEX_OFF = "/nonexistent/phren-codex-off";
1
6
  /** The `codex` the Hook runs for its own helper calls (`codex queue`, `codex
2
7
  * app-server`). `phren init` can put a session wrapper at ~/.local/bin/codex
3
8
  * that runs phren's session-start hook before the real binary for every
@@ -1,5 +1,10 @@
1
1
  import { accessSync, closeSync, constants, openSync, readSync, statSync } from "node:fs";
2
2
  import path from "node:path";
3
+ /** What `PHREN_CODEX_BINARY=off` resolves to: a path no spawn can run, so every
4
+ * helper call fails as if codex were not installed. The vitest config sets it:
5
+ * Codex 0.158 leaves a detached `app-server --managed-daemon` behind for the
6
+ * HOME it ran under, and a test run's throwaway HOME is deleted under it. */
7
+ export const CODEX_OFF = "/nonexistent/phren-codex-off";
3
8
  /** The `codex` the Hook runs for its own helper calls (`codex queue`, `codex
4
9
  * app-server`). `phren init` can put a session wrapper at ~/.local/bin/codex
5
10
  * that runs phren's session-start hook before the real binary for every
@@ -8,6 +13,8 @@ import path from "node:path";
8
13
  * questions were reported as terminal-only, and each call opened a phren
9
14
  * session. The Hook skips its own wrapper and runs the binary it names. */
10
15
  export function codexExecutable(env = process.env) {
16
+ if (/^(?:0|off|false|no)$/i.test(env.PHREN_CODEX_BINARY ?? ""))
17
+ return CODEX_OFF;
11
18
  if (process.platform === "win32")
12
19
  return "codex";
13
20
  for (const directory of (env.PATH ?? "").split(path.delimiter)) {