@phren/cli 0.3.30 → 0.3.32

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 (81) hide show
  1. package/dist/bridge/agent-hooks.d.ts +5 -55
  2. package/dist/bridge/agent-hooks.js +45 -162
  3. package/dist/bridge/approval-rules.d.ts +70 -0
  4. package/dist/bridge/approval-rules.js +231 -0
  5. package/dist/bridge/authority.d.ts +1 -2
  6. package/dist/bridge/authority.js +2 -7
  7. package/dist/bridge/changes.d.ts +4 -0
  8. package/dist/bridge/changes.js +47 -33
  9. package/dist/bridge/claude-suggestion.js +1 -1
  10. package/dist/bridge/codex-servers.d.ts +12 -0
  11. package/dist/bridge/codex-servers.js +35 -3
  12. package/dist/bridge/codex-thread-origin.d.ts +12 -0
  13. package/dist/bridge/codex-thread-origin.js +31 -0
  14. package/dist/bridge/dispatch.js +1 -1
  15. package/dist/bridge/enroll.d.ts +6 -0
  16. package/dist/bridge/enroll.js +10 -4
  17. package/dist/bridge/git-worktrees.js +14 -17
  18. package/dist/bridge/git.d.ts +10 -2
  19. package/dist/bridge/git.js +148 -107
  20. package/dist/bridge/hand-off-queue.d.ts +10 -0
  21. package/dist/bridge/hand-off-queue.js +33 -10
  22. package/dist/bridge/health.js +9 -5
  23. package/dist/bridge/herdr.js +6 -1
  24. package/dist/bridge/hook-main.js +12 -2
  25. package/dist/bridge/locate.js +14 -1
  26. package/dist/bridge/projects.d.ts +8 -0
  27. package/dist/bridge/projects.js +142 -24
  28. package/dist/bridge/prompt-deliveries.d.ts +99 -0
  29. package/dist/bridge/prompt-deliveries.js +327 -0
  30. package/dist/bridge/prompt-once.d.ts +2 -0
  31. package/dist/bridge/prompt-once.js +2 -0
  32. package/dist/bridge/schedule-format.d.ts +10 -0
  33. package/dist/bridge/schedule-format.js +24 -1
  34. package/dist/bridge/schedules.d.ts +3 -1
  35. package/dist/bridge/schedules.js +96 -40
  36. package/dist/bridge/server-launch.js +39 -15
  37. package/dist/bridge/server-pane-routes.js +91 -45
  38. package/dist/bridge/server-routes.d.ts +3 -0
  39. package/dist/bridge/server-routes.js +36 -8
  40. package/dist/bridge/server-stream.js +4 -2
  41. package/dist/bridge/server.js +12 -3
  42. package/dist/bridge/speech-key.d.ts +2 -9
  43. package/dist/bridge/speech-key.js +4 -37
  44. package/dist/bridge/sudo.d.ts +1 -1
  45. package/dist/bridge/sudo.js +51 -17
  46. package/dist/bridge/terminal-tmux.js +22 -4
  47. package/dist/bridge/tmux-test-server.d.ts +13 -0
  48. package/dist/bridge/tmux-test-server.js +103 -0
  49. package/dist/bridge/transcript-claude.d.ts +3 -3
  50. package/dist/bridge/transcript-claude.js +7 -7
  51. package/dist/bridge/transcript-codex.js +6 -4
  52. package/dist/bridge/transcript-preview.js +1 -1
  53. package/dist/bridge/transcripts.js +14 -3
  54. package/dist/bridge-hook.mjs +16011 -14121
  55. package/dist/cli/schedules.js +8 -2
  56. package/dist/cli/session-stop.js +9 -1
  57. package/dist/cli-registry.js +1 -1
  58. package/dist/core/project-registry.d.ts +1 -0
  59. package/dist/core/project-registry.js +6 -2
  60. package/dist/core/project.d.ts +1 -0
  61. package/dist/core/project.js +5 -0
  62. package/dist/generated/memory-ui-graph.browser.js +328 -333
  63. package/dist/init/setup.js +2 -2
  64. package/dist/memory-ui-graph.runtime.js +328 -333
  65. package/dist/modules/registry.js +9 -7
  66. package/dist/phren-core.js +1 -1
  67. package/dist/phren-paths.d.ts +2 -2
  68. package/dist/phren-paths.js +2 -2
  69. package/dist/store-routing.d.ts +2 -2
  70. package/dist/store-routing.js +2 -2
  71. package/dist/sync/git-state.d.ts +13 -0
  72. package/dist/sync/git-state.js +22 -0
  73. package/dist/sync/store-merge.d.ts +2 -0
  74. package/dist/sync/store-merge.js +6 -1
  75. package/dist/test-global-setup.js +7 -0
  76. package/dist/tools/data.js +1 -1
  77. package/dist/tools/finding.js +1 -1
  78. package/dist/tools/search.js +1 -1
  79. package/dist/tools/tasks.js +1 -1
  80. package/package.json +8 -8
  81. package/starter/global/skills/conductor/SKILL.md +2 -2
@@ -7,6 +7,7 @@ import { type RequestKind } from "./approval-summary.js";
7
7
  import { type DialogAnswer, type DialogQuestion } from "./claude-question-dialog.js";
8
8
  import { type TerminalChoice } from "./terminal-choice.js";
9
9
  import { ApprovalWatchLeases } from "./agent-hook-stores.js";
10
+ import { PromptDeliveries } from "./prompt-deliveries.js";
10
11
  import { SudoBroker } from "./sudo.js";
11
12
  import type { AppServerRequestId, PendingServerRequest } from "./codex-app-server.js";
12
13
  import { PaneServerWatcher, type PaneAsks } from "./opencode-panes.js";
@@ -87,30 +88,14 @@ export declare const OPENCODE_APPROVAL_OPTIONS: Json[];
87
88
  * are `always`, a plain approve is `once`, a deny is `reject`. Undefined for
88
89
  * anything else. */
89
90
  export declare function opencodePermissionReply(decision: unknown): "once" | "always" | "reject" | undefined;
90
- export type DeliveryOutcome = "delivered" | "blocked" | "pending";
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. */
94
- interface TrackedDelivery {
95
- source: Provider;
96
- session: string;
97
- state: "typed" | "queued" | "delivered" | "blocked";
98
- at: number;
99
- }
100
- export type TrackedState = Exclude<TrackedDelivery["state"], "typed"> | "unknown";
101
91
  export declare class AgentHooks {
102
92
  readonly push: ApprovalPushService;
103
93
  private modules?;
104
94
  readonly changes: ToolChanges;
105
95
  private pending;
106
- /** Prompts Phren has typed into a pane, by a hash of their words, until the agent that
107
- * actually receives one reports in through UserPromptSubmit. Herdr writes
108
- * to a pane, not a conversation; the receiving agent's hook is the only
109
- * party that knows which conversation consumed the text, so it is the one
110
- * that can refuse it when that is not the conversation the phone meant. */
111
- private deliveries;
112
- /** Phone messages by delivery id, until TRACK_MS: see `queueDelivery`. */
113
- private tracked;
96
+ /** Phone messages Phren typed into a pane, until a conversation there
97
+ * submits them through UserPromptSubmit: see prompt-deliveries.ts. */
98
+ readonly deliveries: PromptDeliveries;
114
99
  /** The permission request a conversation is drawing in its own terminal
115
100
  * because nobody was there to hold it: what the phone shows above its
116
101
  * answer keys until the pane stops waiting. `dialog` marks a choice parsed
@@ -173,7 +158,7 @@ export declare class AgentHooks {
173
158
  private computerName;
174
159
  /** sudo -A requests from askpass, answered from the phone (sudo.ts). */
175
160
  readonly sudo: SudoBroker;
176
- constructor(push?: ApprovalPushService, modules?: ModuleSnapshot | undefined);
161
+ constructor(push?: ApprovalPushService, modules?: ModuleSnapshot | undefined, deliveriesFile?: string);
177
162
  private approvalsDirectory;
178
163
  private scheduleOpencodeSweep;
179
164
  /** Read every live opencode request file, map it to a target through the
@@ -216,41 +201,6 @@ export declare class AgentHooks {
216
201
  * fails never takes the Hook down. */
217
202
  private sweepFanoutArchive;
218
203
  watch(target: Target): () => void;
219
- /** Register a prompt about to be typed into `target`'s pane. The returned
220
- * promise settles "delivered" once that conversation's own hook submits the
221
- * text, "blocked" if another conversation in the pane tried to, or "pending"
222
- * after `waitMs`: a busy agent queues typed input and submits it only when
223
- * its turn ends, so the record outlives the wait (up to ten minutes) and a
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>;
227
- /** A prompt Phren typed into `target` that its conversation has not submitted yet. */
228
- deliveryPending(target: Target, text: string): boolean;
229
- /** Wait again for a delivery `expectDelivery` already reported pending,
230
- * after the Hook pressed Enter a second time. */
231
- awaitLateDelivery(target: Target, text: string, waitMs?: number): Promise<DeliveryOutcome>;
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;
236
- /** What became of the phone message `id` sent to `target`'s conversation:
237
- * queued until the agent submits it, then delivered, or blocked when
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. */
241
- deliveryState(id: string, target: Target): TrackedState;
242
- /** Every known phone message to `target`'s conversation, for its stream. */
243
- deliveriesFor(target: Target): {
244
- deliveryId: string;
245
- state: TrackedState;
246
- }[];
247
- private settleTracked;
248
- /** The conversation `target` just submitted `prompt`. Nothing Phren typed
249
- * matches: a locally typed prompt, always allowed. Otherwise the oldest
250
- * matching delivery decides: its own conversation consumes it; any other
251
- * conversation is told to drop it, so the text is never spoken to the
252
- * wrong agent and the phone can safely send it again. */
253
- private submitted;
254
204
  /** The conversation's own turn events, for dispatch returns (turn-records.ts).
255
205
  * A failed write never fails the agent's callback. */
256
206
  private recordTurn;
@@ -1,5 +1,6 @@
1
+ import { approvalRuleContext, approvalRuleEffect } from "./approval-rules.js";
1
2
  import { recordedConductor } from "./conductor-role.js";
2
- import { conductorContext } from "./conductor-context.js";
3
+ import { conductorBrief, conductorContext } from "./conductor-context.js";
3
4
  import { defaultPhrenPath } from "../shared.js";
4
5
  import { disabledHint } from "../modules/registry.js";
5
6
  import { activateModules as moduleSnapshot } from "../modules/runtime.js";
@@ -8,17 +9,18 @@ import { request, createServer } from "node:http";
8
9
  import { mkdir, readFile, chmod, unlink, lstat } from "node:fs/promises";
9
10
  import { watch } from "node:fs";
10
11
  import path from "node:path";
11
- import { createHash, randomUUID } from "node:crypto";
12
+ import { randomUUID } from "node:crypto";
12
13
  import { hostname } from "node:os";
13
14
  import { atomicInPrivateDir, BridgeError, bridgeRoot, object, objects, provider, targetSchema } from "./protocol.js";
14
15
  import { findPane, knownPanes, paneIdentity, paneForCodexSession, servers, snapshot, trustedDirectory, validateTarget } from "./herdr.js";
15
16
  import { hookOutput, TOOL_HOOK_BUDGET_MS } from "./hook-fast.js";
16
17
  import { underCodexDaemon } from "./codex-daemon.js";
17
18
  import { codexAutoReview } from "./codex-review-mode.js";
19
+ import { codexForeignThread } from "./codex-thread-origin.js";
18
20
  import { terminalPaneFromEnv, terminalProvider } from "./terminal.js";
19
21
  import { readPaneText } from "./pane-text.js";
20
22
  import { capturesChanges, ToolChanges } from "./changes.js";
21
- import { phrenStoreRoot, unwrapPastedContent } from "./transcripts.js";
23
+ import { phrenStoreRoot } from "./transcripts.js";
22
24
  import { archiveFinishedFanouts, blockedFanouts, fanoutAsking } from "./fanouts.js";
23
25
  import { ensureGrant, findGrant } from "./grants.js";
24
26
  import { ApprovalPushService } from "./push.js";
@@ -33,6 +35,7 @@ import { ApprovalWatchLeases, bindingPath, localSocket, PushBindingStore } from
33
35
  import { notePaneTranscript, paneAccountKey } from "./pane-accounts.js";
34
36
  import { eventStatus, notePaneStatus, settleBlockedPane } from "./pane-status.js";
35
37
  import { noteTurn as recordTurn } from "./turn-records.js";
38
+ import { PromptDeliveries } from "./prompt-deliveries.js";
36
39
  import { countTick } from "./metrics.js";
37
40
  import { briefId, briefIdInPrompt, briefLabel, DISPATCH_ID_ENV, recordBriefArrival } from "./launch-brief.js";
38
41
  import { SudoBroker } from "./sudo.js";
@@ -109,7 +112,7 @@ const DISPATCH_LEASE_MS = 45_000;
109
112
  export function conductorCall(tool, input) {
110
113
  // MCP tool names vary by harness: `dispatch`, `phren.dispatch`,
111
114
  // `mcp__phren__dispatch`; phren_admin carries the action in its fields.
112
- const tail = /(?:^|[.:/]|__)(dispatch|hand_off|phren_admin)$/.exec(tool)?.[1];
115
+ const tail = /(?:^|[.:/]|__)(dispatch|hand_off|phren_admin)$/.exec(tool.replace(/^mcp_phren_/, ""))?.[1];
113
116
  const fields = object(input);
114
117
  let action;
115
118
  if (tail === "dispatch")
@@ -147,19 +150,6 @@ export function opencodePermissionReply(decision) {
147
150
  return "always";
148
151
  return undefined;
149
152
  }
150
- /** As long as a typed prompt's own record guards it (`expectDelivery`). */
151
- const TRACK_MS = 600_000;
152
- /** What the agent hands its UserPromptSubmit hook is the terminal's pasted
153
- * form of what Phren typed; compare the words, not the wrapping. Claude Code
154
- * also takes each attached picture's path line out of the text and puts an
155
- * "[Image #N]" label at the front, so neither side keeps picture paths or
156
- * labels. */
157
- function promptKey(text) {
158
- return unwrapPastedContent(text).split("\n").filter(line => !PICTURE_PATH_LINE.test(line)).join("\n")
159
- .replace(/\[Image #\d+\]/g, " ").replace(/\s+/g, " ").trim();
160
- }
161
- const PICTURE_PATH_LINE = /^\s*\/.*\.(?:png|jpe?g|gif|webp)\s*$/i;
162
- const promptHash = (text) => createHash("sha256").update(promptKey(text)).digest("hex");
163
153
  /** This socket is deliberately separate from the phone's HTTP pipe. Only local
164
154
  * agent callbacks can register identities or create an approval request. */
165
155
  /** The project a notification names for a pane's folder: none for the
@@ -173,14 +163,9 @@ export class AgentHooks {
173
163
  modules;
174
164
  changes = new ToolChanges();
175
165
  pending = new Map();
176
- /** Prompts Phren has typed into a pane, by a hash of their words, until the agent that
177
- * actually receives one reports in through UserPromptSubmit. Herdr writes
178
- * to a pane, not a conversation; the receiving agent's hook is the only
179
- * party that knows which conversation consumed the text, so it is the one
180
- * that can refuse it when that is not the conversation the phone meant. */
181
- deliveries = new Map();
182
- /** Phone messages by delivery id, until TRACK_MS: see `queueDelivery`. */
183
- tracked = new Map();
166
+ /** Phone messages Phren typed into a pane, until a conversation there
167
+ * submits them through UserPromptSubmit: see prompt-deliveries.ts. */
168
+ deliveries;
184
169
  /** The permission request a conversation is drawing in its own terminal
185
170
  * because nobody was there to hold it: what the phone shows above its
186
171
  * answer keys until the pane stops waiting. `dialog` marks a choice parsed
@@ -243,9 +228,10 @@ export class AgentHooks {
243
228
  computerName = hostname().replace(/\.local$/i, "").split(".")[0] || "Computer";
244
229
  /** sudo -A requests from askpass, answered from the phone (sudo.ts). */
245
230
  sudo;
246
- constructor(push = new ApprovalPushService(), modules) {
231
+ constructor(push = new ApprovalPushService(), modules, deliveriesFile) {
247
232
  this.push = push;
248
233
  this.modules = modules;
234
+ this.deliveries = new PromptDeliveries(deliveriesFile);
249
235
  void computerDisplayName().then(name => { this.computerName = name; }, () => { });
250
236
  this.sudo = new SudoBroker({ computer: () => this.computerName, push, label: briefLabel,
251
237
  describe: async (place) => {
@@ -634,130 +620,6 @@ export class AgentHooks {
634
620
  else
635
621
  this.watching.delete(key); };
636
622
  }
637
- /** Register a prompt about to be typed into `target`'s pane. The returned
638
- * promise settles "delivered" once that conversation's own hook submits the
639
- * text, "blocked" if another conversation in the pane tried to, or "pending"
640
- * after `waitMs`: a busy agent queues typed input and submits it only when
641
- * its turn ends, so the record outlives the wait (up to ten minutes) and a
642
- * late submission to the wrong conversation is still refused. A phone
643
- * message's `id` follows the record, so its outcome lands on that id. */
644
- expectDelivery(target, text, waitMs = 1_500, signal, id) {
645
- if (!promptKey(text) || signal?.aborted)
646
- return Promise.resolve("pending");
647
- const key = promptHash(text);
648
- if (id)
649
- this.track(id, target, "typed");
650
- return new Promise(resolve => {
651
- let settled = false;
652
- const list = this.deliveries.get(key) ?? [];
653
- const remove = () => {
654
- signal?.removeEventListener("abort", cancel);
655
- const current = this.deliveries.get(key) ?? [];
656
- const index = current.indexOf(delivery);
657
- if (index >= 0)
658
- current.splice(index, 1);
659
- if (!current.length)
660
- this.deliveries.delete(key);
661
- };
662
- const settle = (outcome) => {
663
- if (!settled) {
664
- settled = true;
665
- resolve(outcome);
666
- }
667
- else if (outcome !== "pending")
668
- delivery.late?.(outcome);
669
- if (outcome !== "pending") {
670
- clearTimeout(delivery.timer);
671
- remove();
672
- this.settleTracked(delivery, outcome);
673
- }
674
- };
675
- const delivery = { source: target.source, session: target.session, ...(id ? { id } : {}), settle, timer: setTimeout(() => settle("pending"), waitMs) };
676
- // Only cancel after a provider explicitly refused before writing. A
677
- // possibly delivered paste keeps its guard against the wrong session.
678
- const cancel = () => { clearTimeout(delivery.timer); settle("pending"); remove(); };
679
- signal?.addEventListener("abort", cancel, { once: true });
680
- delivery.timer.unref?.();
681
- const expiry = setTimeout(remove, 600_000);
682
- expiry.unref?.();
683
- list.push(delivery);
684
- this.deliveries.set(key, list);
685
- while (this.deliveries.size > 256)
686
- this.deliveries.delete(this.deliveries.keys().next().value);
687
- });
688
- }
689
- /** A prompt Phren typed into `target` that its conversation has not submitted yet. */
690
- deliveryPending(target, text) {
691
- return !!this.deliveries.get(promptHash(text))?.some(entry => entry.source === target.source && entry.session === target.session);
692
- }
693
- /** Wait again for a delivery `expectDelivery` already reported pending,
694
- * after the Hook pressed Enter a second time. */
695
- awaitLateDelivery(target, text, waitMs = 2_500) {
696
- const delivery = this.deliveries.get(promptHash(text))?.find(entry => entry.source === target.source && entry.session === target.session);
697
- if (!delivery)
698
- return Promise.resolve("pending");
699
- return new Promise(resolve => {
700
- const timer = setTimeout(() => { delivery.late = undefined; resolve("pending"); }, waitMs);
701
- timer.unref?.();
702
- delivery.late = outcome => { clearTimeout(timer); delivery.late = undefined; resolve(outcome); };
703
- });
704
- }
705
- track(id, target, state) {
706
- const now = Date.now();
707
- for (const [key, entry] of this.tracked)
708
- if (now - entry.at > TRACK_MS)
709
- this.tracked.delete(key);
710
- while (this.tracked.size >= 512)
711
- this.tracked.delete(this.tracked.keys().next().value);
712
- this.tracked.set(id, { source: target.source, session: target.session, state, at: now });
713
- }
714
- /** The Hook answered the phone message `id` as queued: its typed record
715
- * still waits for the agent's hook, which settles it by this id. */
716
- queueDelivery(id, target) {
717
- const entry = this.tracked.get(id);
718
- if (entry?.state === "typed" && entry.source === target.source && entry.session === target.session)
719
- entry.state = "queued";
720
- }
721
- /** What became of the phone message `id` sent to `target`'s conversation:
722
- * queued until the agent submits it, then delivered, or blocked when
723
- * another conversation in the pane took it. Unknown while the Hook has not
724
- * answered it, for another conversation, or older than TRACK_MS. A
725
- * message answered uncertain still turns delivered once its hook takes it. */
726
- deliveryState(id, target) {
727
- const entry = this.tracked.get(id);
728
- return entry && entry.state !== "typed" && entry.source === target.source && entry.session === target.session && Date.now() - entry.at <= TRACK_MS ? entry.state : "unknown";
729
- }
730
- /** Every known phone message to `target`'s conversation, for its stream. */
731
- deliveriesFor(target) {
732
- return [...this.tracked.keys()].map(deliveryId => ({ deliveryId, state: this.deliveryState(deliveryId, target) })).filter(item => item.state !== "unknown");
733
- }
734
- settleTracked(delivery, outcome) {
735
- const entry = delivery.id ? this.tracked.get(delivery.id) : undefined;
736
- if (entry && entry.source === delivery.source && entry.session === delivery.session) {
737
- entry.state = outcome;
738
- entry.at = Date.now();
739
- }
740
- }
741
- /** The conversation `target` just submitted `prompt`. Nothing Phren typed
742
- * matches: a locally typed prompt, always allowed. Otherwise the oldest
743
- * matching delivery decides: its own conversation consumes it; any other
744
- * conversation is told to drop it, so the text is never spoken to the
745
- * wrong agent and the phone can safely send it again. */
746
- submitted(target, prompt) {
747
- const list = this.deliveries.get(promptHash(prompt));
748
- // The same words sent to two conversations at once: each one's own
749
- // submission settles its own record, not whichever was typed first.
750
- const delivery = list?.find(entry => entry.source === target.source && entry.session === target.session) ?? list?.[0];
751
- if (!delivery)
752
- return {};
753
- const own = delivery.source === target.source && delivery.session === target.session;
754
- if (own) {
755
- delivery.settle("delivered");
756
- return {};
757
- }
758
- delivery.settle("blocked");
759
- return { decision: "block", reason: "Phren sent this message to a different conversation in this pane; it was not delivered here. Send it again from the phone." };
760
- }
761
623
  /** The conversation's own turn events, for dispatch returns (turn-records.ts).
762
624
  * A failed write never fails the agent's callback. */
763
625
  async recordTurn(target, pane, body, dispatch) {
@@ -1676,7 +1538,7 @@ export class AgentHooks {
1676
1538
  chunks.push(bytes);
1677
1539
  }
1678
1540
  const body = object(JSON.parse(Buffer.concat(chunks).toString()));
1679
- // OpenCode asks when building the root session's system prompt. Resolve
1541
+ // OpenCode and phren-agent ask when building the root session's system prompt. Resolve
1680
1542
  // its process against the current conductor; no inherited pane env or
1681
1543
  // plugin callback may create a session binding or a turn record here.
1682
1544
  if (req.url === "/conductor-context") {
@@ -1693,7 +1555,7 @@ export class AgentHooks {
1693
1555
  }
1694
1556
  const s = await snapshot(role.server);
1695
1557
  const pane = objects(s.panes).find(p => p.pane_id === role.pane);
1696
- if (!pane || pane.agent !== "opencode" || (role.terminal && pane.terminal_id !== role.terminal)) {
1558
+ if (!pane || !["opencode", "phren"].includes(String(pane.agent)) || (role.terminal && pane.terminal_id !== role.terminal)) {
1697
1559
  res.end("{}");
1698
1560
  return;
1699
1561
  }
@@ -1703,9 +1565,9 @@ export class AgentHooks {
1703
1565
  return;
1704
1566
  }
1705
1567
  const target = targetSchema.parse({ server: role.server, workspace: pane.workspace_id, tab: pane.tab_id,
1706
- pane: role.pane, source: "opencode", session: body.session });
1568
+ pane: role.pane, source: pane.agent, session: body.session });
1707
1569
  const context = await conductorContext(target, s);
1708
- res.end(JSON.stringify(context ? { context } : {}));
1570
+ res.end(JSON.stringify(context ? { context: pane.agent === "phren" ? `${context}\n\n${await conductorBrief()}` : context } : {}));
1709
1571
  return;
1710
1572
  }
1711
1573
  let target = targetSchema.parse(body.target);
@@ -1772,7 +1634,9 @@ export class AgentHooks {
1772
1634
  }
1773
1635
  // `/new` or `/resume` in a pane on the Hook's own Codex server: follow
1774
1636
  // the TUI to its new thread. Only a callback trusted to name its pane.
1775
- if (body.event === "SessionStart" && target.source === "codex" && !daemon)
1637
+ // A prompt or a turn's end also moves a server a nested `codex exec`
1638
+ // had taken (before codex-thread-origin.ts) back to the TUI's thread.
1639
+ if (["SessionStart", "UserPromptSubmit", "Stop"].includes(String(body.event)) && target.source === "codex" && !daemon)
1776
1640
  codexServers.follow(target.server, target.pane, target.session);
1777
1641
  if (body.event === "PreCompact") {
1778
1642
  this.startCompacting(target);
@@ -1782,14 +1646,15 @@ export class AgentHooks {
1782
1646
  if (["SessionStart", "UserPromptSubmit", "Stop"].includes(String(body.event)))
1783
1647
  this.stopCompacting(target);
1784
1648
  if (body.event === "UserPromptSubmit") {
1785
- const answer = typeof body.prompt === "string" ? this.submitted(target, body.prompt.slice(0, 65_536)) : {};
1786
- // A prompt refused here never starts a turn in this conversation.
1787
- if (answer.decision !== "block")
1788
- await this.recordTurn(target, pane, body, dispatch);
1789
- const context = answer.decision === "block" || this.modules?.has("conductor") === false ? undefined : await conductorContext(target, s).catch(() => undefined);
1790
- res.end(JSON.stringify({ ...answer, ...(context ? { hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: context } } : {}) }));
1649
+ if (typeof body.prompt === "string")
1650
+ this.deliveries.submitted(target, body.prompt.slice(0, 65_536));
1651
+ await this.recordTurn(target, pane, body, dispatch);
1652
+ const context = this.modules?.has("conductor") === false ? undefined : await conductorContext(target, s).catch(() => undefined);
1653
+ res.end(JSON.stringify(context ? { hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: context } } : {}));
1791
1654
  return;
1792
1655
  }
1656
+ if (body.event === "Stop")
1657
+ this.deliveries.stopped(target);
1793
1658
  if (body.event === "SessionStart" || body.event === "Stop")
1794
1659
  await this.recordTurn(target, pane, body, dispatch);
1795
1660
  if (body.event === "SessionStart") {
@@ -1811,9 +1676,24 @@ export class AgentHooks {
1811
1676
  res.end("{}");
1812
1677
  return;
1813
1678
  }
1679
+ // Validate applicable shell restrictions before any directory/Git reads.
1680
+ const ruleEffect = body.event === "PermissionRequest" && target.source === "claude"
1681
+ ? await approvalRuleEffect(String(body.tool), body.input, async () => {
1682
+ if (typeof body.cwd !== "string" || !path.isAbsolute(body.cwd))
1683
+ return undefined;
1684
+ const [paneContext, requestContext] = await Promise.all([
1685
+ trustedDirectory(pane).then(cwd => approvalRuleContext(cwd, target.source, target.session)).catch(() => undefined),
1686
+ approvalRuleContext(body.cwd, target.source, target.session),
1687
+ ]);
1688
+ return paneContext && requestContext?.project === paneContext.project ? requestContext : undefined;
1689
+ }, undefined, { harness: target.source, session: target.session, computer: hostname() }) : undefined;
1690
+ if (ruleEffect === "deny") {
1691
+ res.end(JSON.stringify({ hookSpecificOutput: { hookEventName: "PermissionRequest", decision: { behavior: "deny", message: "Denied by an owner approval rule." } } }));
1692
+ return;
1693
+ }
1814
1694
  if (body.event === "PermissionRequest")
1815
1695
  this.terminalPrompts.delete(JSON.stringify(target));
1816
- if (body.event === "PermissionRequest") {
1696
+ if (body.event === "PermissionRequest" && ruleEffect !== "always-ask") {
1817
1697
  const conductor = conductorCall(String(body.tool || "action"), body.input);
1818
1698
  if (conductor) {
1819
1699
  // A standing grant answers the call before it becomes an approval card.
@@ -1995,6 +1875,9 @@ export async function agentHook(source, elapsed = () => performance.now()) {
1995
1875
  const value = object(JSON.parse(input));
1996
1876
  if (value.agent_id || value.agentId || value.isSidechain || value.is_sidechain)
1997
1877
  return;
1878
+ // A `codex exec` or a subagent inside a Codex pane is not the pane's conversation.
1879
+ if (source === "codex" && await codexForeignThread(value.transcript_path).catch(() => false))
1880
+ return;
1998
1881
  const target = targetSchema.parse({ server: place.server, workspace: place.workspace, tab: place.tab,
1999
1882
  pane: place.pane, source, session: value.session_id || value.sessionId });
2000
1883
  const event = String(value.hook_event_name || "SessionStart");
@@ -0,0 +1,70 @@
1
+ import { z } from "zod";
2
+ export declare const approvalRuleDraftSchema: z.ZodObject<{
3
+ tool: z.ZodLiteral<"Bash">;
4
+ command: z.ZodString;
5
+ match: z.ZodEnum<{
6
+ exact: "exact";
7
+ glob: "glob";
8
+ prefix: "prefix";
9
+ }>;
10
+ effect: z.ZodEnum<{
11
+ "always-ask": "always-ask";
12
+ deny: "deny";
13
+ }>;
14
+ scope: z.ZodObject<{
15
+ project: z.ZodString;
16
+ harness: z.ZodOptional<z.ZodEnum<{
17
+ claude: "claude";
18
+ codex: "codex";
19
+ copilot: "copilot";
20
+ opencode: "opencode";
21
+ phren: "phren";
22
+ }>>;
23
+ session: z.ZodOptional<z.ZodString>;
24
+ computer: z.ZodOptional<z.ZodString>;
25
+ }, z.core.$strict>;
26
+ projectName: z.ZodString;
27
+ until: z.ZodOptional<z.ZodString>;
28
+ }, z.core.$strict>;
29
+ export type ApprovalRuleDraft = z.infer<typeof approvalRuleDraftSchema>;
30
+ export interface ApprovalRule extends ApprovalRuleDraft {
31
+ id: string;
32
+ createdAt: string;
33
+ owner: string;
34
+ enabled: boolean;
35
+ }
36
+ export declare function listApprovalRules(root?: string, pairedKey?: string): Promise<{
37
+ tool: "Bash";
38
+ command: string;
39
+ match: "exact" | "glob" | "prefix";
40
+ effect: "always-ask" | "deny";
41
+ scope: {
42
+ project: string;
43
+ harness?: "claude" | "codex" | "copilot" | "opencode" | "phren" | undefined;
44
+ session?: string | undefined;
45
+ computer?: string | undefined;
46
+ };
47
+ projectName: string;
48
+ until?: string | undefined;
49
+ id: string;
50
+ createdAt: string;
51
+ owner: string;
52
+ enabled: boolean;
53
+ signerFingerprint: string;
54
+ matchesPairedKey: boolean;
55
+ }[]>;
56
+ /** The signed operations remain on disk and are verified again at every decision. */
57
+ export declare function changeApprovalRule(input: unknown, method: "POST" | "DELETE", root?: string): Promise<{
58
+ ok: boolean;
59
+ }>;
60
+ export interface ApprovalRuleContext {
61
+ project: string;
62
+ harness: NonNullable<ApprovalRuleDraft["scope"]["harness"]>;
63
+ session: string;
64
+ computer: string;
65
+ }
66
+ /** Bind project scope to the main repository, including linked worktrees. */
67
+ export declare function approvalRuleContext(cwd: string, harness: string, session: string): Promise<ApprovalRuleContext | undefined>;
68
+ /** Rules can only restrict a request the harness has already raised. Invalid policy
69
+ * falls back to that ordinary approval path; Settings reports the load error. */
70
+ export declare function approvalRuleEffect(tool: string, input: unknown, context: ApprovalRuleContext | undefined | (() => Promise<ApprovalRuleContext | undefined>), root?: string, knownScope?: Partial<ApprovalRuleContext>): Promise<"always-ask" | "deny" | undefined>;