@phren/cli 0.3.20 → 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 (53) hide show
  1. package/dist/bridge/agent-hooks.d.ts +22 -19
  2. package/dist/bridge/agent-hooks.js +49 -33
  3. package/dist/bridge/approval-summary.d.ts +4 -0
  4. package/dist/bridge/approval-summary.js +12 -1
  5. package/dist/bridge/code-note.d.ts +1 -0
  6. package/dist/bridge/code-note.js +2 -2
  7. package/dist/bridge/codex-binary.d.ts +5 -0
  8. package/dist/bridge/codex-binary.js +7 -0
  9. package/dist/bridge/dispatch-command.js +1 -1
  10. package/dist/bridge/dispatch-returns.d.ts +3 -2
  11. package/dist/bridge/dispatch-returns.js +27 -11
  12. package/dist/bridge/dispatch.d.ts +4 -0
  13. package/dist/bridge/dispatch.js +5 -3
  14. package/dist/bridge/folder-trust.d.ts +13 -3
  15. package/dist/bridge/folder-trust.js +42 -4
  16. package/dist/bridge/hand-off.js +2 -1
  17. package/dist/bridge/herdr.js +6 -5
  18. package/dist/bridge/launch-brief.d.ts +3 -1
  19. package/dist/bridge/launch-brief.js +3 -1
  20. package/dist/bridge/memory-store.d.ts +7 -0
  21. package/dist/bridge/memory-store.js +37 -1
  22. package/dist/bridge/schedule-format.d.ts +1 -1
  23. package/dist/bridge/schedule-format.js +1 -1
  24. package/dist/bridge/schedule-launch.js +5 -0
  25. package/dist/bridge/schedule-watch.d.ts +5 -2
  26. package/dist/bridge/schedule-watch.js +59 -20
  27. package/dist/bridge/server-launch.d.ts +6 -0
  28. package/dist/bridge/server-launch.js +59 -11
  29. package/dist/bridge/server-pane-routes.js +20 -13
  30. package/dist/bridge/server-routes.d.ts +1 -0
  31. package/dist/bridge/server-routes.js +1 -1
  32. package/dist/bridge/server-stream.js +12 -0
  33. package/dist/bridge/server.js +2 -2
  34. package/dist/bridge/session-activity.d.ts +6 -0
  35. package/dist/bridge/session-activity.js +16 -0
  36. package/dist/bridge/settings-switch.d.ts +7 -0
  37. package/dist/bridge/settings-switch.js +15 -0
  38. package/dist/bridge/speech-transcribe.d.ts +8 -1
  39. package/dist/bridge/speech-transcribe.js +18 -3
  40. package/dist/bridge/transcript-claude.js +39 -10
  41. package/dist/bridge/worker-close.js +3 -2
  42. package/dist/bridge/worker-unfinished.d.ts +8 -2
  43. package/dist/bridge/worker-unfinished.js +57 -24
  44. package/dist/bridge-hook.mjs +513 -277
  45. package/dist/cli-registry.js +1 -1
  46. package/dist/home-paths.d.ts +2 -0
  47. package/dist/home-paths.js +4 -0
  48. package/dist/modules/registry.js +1 -1
  49. package/dist/test-global-setup.js +2 -1
  50. package/dist/test-sandbox.d.ts +15 -0
  51. package/dist/test-sandbox.js +36 -0
  52. package/package.json +1 -1
  53. package/starter/global/skills/conductor/SKILL.md +2 -1
@@ -88,31 +88,28 @@ export declare const OPENCODE_APPROVAL_OPTIONS: Json[];
88
88
  * anything else. */
89
89
  export declare function opencodePermissionReply(decision: unknown): "once" | "always" | "reject" | undefined;
90
90
  export type DeliveryOutcome = "delivered" | "blocked" | "pending";
91
- /** A phone message the Hook answered as delivered or queued, kept under the
92
- * phone's delivery id so the phone can ask what became of it by that id.
93
- * 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. */
94
94
  interface TrackedDelivery {
95
95
  source: Provider;
96
96
  session: string;
97
- key: string;
98
- state: "queued" | "delivered" | "blocked";
97
+ state: "typed" | "queued" | "delivered" | "blocked";
99
98
  at: number;
100
99
  }
101
- export type TrackedState = TrackedDelivery["state"] | "unknown";
102
- /** This socket is deliberately separate from the phone's HTTP pipe. Only local
103
- * agent callbacks can register identities or create an approval request. */
100
+ export type TrackedState = Exclude<TrackedDelivery["state"], "typed"> | "unknown";
104
101
  export declare class AgentHooks {
105
102
  readonly push: ApprovalPushService;
106
103
  private modules?;
107
104
  readonly changes: ToolChanges;
108
105
  private pending;
109
- /** 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
110
107
  * actually receives one reports in through UserPromptSubmit. Herdr writes
111
108
  * to a pane, not a conversation; the receiving agent's hook is the only
112
109
  * party that knows which conversation consumed the text, so it is the one
113
110
  * that can refuse it when that is not the conversation the phone meant. */
114
111
  private deliveries;
115
- /** Phone messages by delivery id, until TRACK_MS: see `trackDelivery`. */
112
+ /** Phone messages by delivery id, until TRACK_MS: see `queueDelivery`. */
116
113
  private tracked;
117
114
  /** The permission request a conversation is drawing in its own terminal
118
115
  * because nobody was there to hold it: what the phone shows above its
@@ -224,23 +221,29 @@ export declare class AgentHooks {
224
221
  * text, "blocked" if another conversation in the pane tried to, or "pending"
225
222
  * after `waitMs`: a busy agent queues typed input and submits it only when
226
223
  * its turn ends, so the record outlives the wait (up to ten minutes) and a
227
- * late submission to the wrong conversation is still refused. */
228
- 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>;
229
227
  /** A prompt Phren typed into `target` that its conversation has not submitted yet. */
230
228
  deliveryPending(target: Target, text: string): boolean;
231
229
  /** Wait again for a delivery `expectDelivery` already reported pending,
232
230
  * after the Hook pressed Enter a second time. */
233
231
  awaitLateDelivery(target: Target, text: string, waitMs?: number): Promise<DeliveryOutcome>;
234
- /** Remember a phone message's outcome under its delivery id. A queued one
235
- * is tracked only while its typed record still waits for the agent's hook,
236
- * so the hook's later answer always reaches it (`settleTracked`). */
237
- 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;
238
236
  /** What became of the phone message `id` sent to `target`'s conversation:
239
237
  * queued until the agent submits it, then delivered, or blocked when
240
- * another conversation in the pane took it. Unknown when the Hook did not
241
- * 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. */
242
241
  deliveryState(id: string, target: Target): TrackedState;
243
- /** 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
+ }[];
244
247
  private settleTracked;
245
248
  /** The conversation `target` just submitted `prompt`. Nothing Phren typed
246
249
  * matches: a locally typed prompt, always allowed. Otherwise the oldest
@@ -20,7 +20,7 @@ import { phrenStoreRoot, unwrapPastedContent } from "./transcripts.js";
20
20
  import { archiveFinishedFanouts, blockedFanouts, fanoutAsking } from "./fanouts.js";
21
21
  import { ensureGrant, findGrant } from "./grants.js";
22
22
  import { ApprovalPushService } from "./push.js";
23
- import { approvalSummary } from "./approval-summary.js";
23
+ import { approvalSummary, paneProject } from "./approval-summary.js";
24
24
  import { computerDisplayName } from "./pair.js";
25
25
  import { intervalFromEnv } from "./limits.js";
26
26
  import { answerClaudeQuestionDialog, claudeQuestionDialog } from "./claude-question-dialog.js";
@@ -157,21 +157,27 @@ function promptKey(text) {
157
157
  .replace(/\[Image #\d+\]/g, " ").replace(/\s+/g, " ").trim();
158
158
  }
159
159
  const PICTURE_PATH_LINE = /^\s*\/.*\.(?:png|jpe?g|gif|webp)\s*$/i;
160
- const trackKey = (text) => createHash("sha256").update(promptKey(text)).digest("hex");
160
+ const promptHash = (text) => createHash("sha256").update(promptKey(text)).digest("hex");
161
161
  /** This socket is deliberately separate from the phone's HTTP pipe. Only local
162
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
+ }
163
169
  export class AgentHooks {
164
170
  push;
165
171
  modules;
166
172
  changes = new ToolChanges();
167
173
  pending = new Map();
168
- /** 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
169
175
  * actually receives one reports in through UserPromptSubmit. Herdr writes
170
176
  * to a pane, not a conversation; the receiving agent's hook is the only
171
177
  * party that knows which conversation consumed the text, so it is the one
172
178
  * that can refuse it when that is not the conversation the phone meant. */
173
179
  deliveries = new Map();
174
- /** Phone messages by delivery id, until TRACK_MS: see `trackDelivery`. */
180
+ /** Phone messages by delivery id, until TRACK_MS: see `queueDelivery`. */
175
181
  tracked = new Map();
176
182
  /** The permission request a conversation is drawing in its own terminal
177
183
  * because nobody was there to hold it: what the phone shows above its
@@ -321,7 +327,7 @@ export class AgentHooks {
321
327
  // The held request is what stops a later sweep from pushing again; a
322
328
  // failed delivery only drops the binding and leaves the card in place.
323
329
  void this.push.notify({ binding, provider: "opencode", question: false, expiresAt: String(request.expiresAt),
324
- ...(cwd ? { project: path.basename(cwd) } : {}), computer: this.computerName, ...summary })
330
+ ...projectField(cwd), computer: this.computerName, ...summary })
325
331
  .then(delivered => { if (!delivered)
326
332
  this.pushBindings.dropAction(id); })
327
333
  .catch(() => { });
@@ -631,11 +637,14 @@ export class AgentHooks {
631
637
  * text, "blocked" if another conversation in the pane tried to, or "pending"
632
638
  * after `waitMs`: a busy agent queues typed input and submits it only when
633
639
  * its turn ends, so the record outlives the wait (up to ten minutes) and a
634
- * late submission to the wrong conversation is still refused. */
635
- expectDelivery(target, text, waitMs = 1_500, signal) {
636
- const key = promptKey(text);
637
- 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)
638
644
  return Promise.resolve("pending");
645
+ const key = promptHash(text);
646
+ if (id)
647
+ this.track(id, target, "typed");
639
648
  return new Promise(resolve => {
640
649
  let settled = false;
641
650
  const list = this.deliveries.get(key) ?? [];
@@ -658,9 +667,10 @@ export class AgentHooks {
658
667
  if (outcome !== "pending") {
659
668
  clearTimeout(delivery.timer);
660
669
  remove();
670
+ this.settleTracked(delivery, outcome);
661
671
  }
662
672
  };
663
- 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) };
664
674
  // Only cancel after a provider explicitly refused before writing. A
665
675
  // possibly delivered paste keeps its guard against the wrong session.
666
676
  const cancel = () => { clearTimeout(delivery.timer); settle("pending"); remove(); };
@@ -676,12 +686,12 @@ export class AgentHooks {
676
686
  }
677
687
  /** A prompt Phren typed into `target` that its conversation has not submitted yet. */
678
688
  deliveryPending(target, text) {
679
- 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);
680
690
  }
681
691
  /** Wait again for a delivery `expectDelivery` already reported pending,
682
692
  * after the Hook pressed Enter a second time. */
683
693
  awaitLateDelivery(target, text, waitMs = 2_500) {
684
- 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);
685
695
  if (!delivery)
686
696
  return Promise.resolve("pending");
687
697
  return new Promise(resolve => {
@@ -690,34 +700,41 @@ export class AgentHooks {
690
700
  delivery.late = outcome => { clearTimeout(timer); delivery.late = undefined; resolve(outcome); };
691
701
  });
692
702
  }
693
- /** Remember a phone message's outcome under its delivery id. A queued one
694
- * is tracked only while its typed record still waits for the agent's hook,
695
- * so the hook's later answer always reaches it (`settleTracked`). */
696
- trackDelivery(id, target, text, state) {
697
- if (state === "queued" && !this.deliveryPending(target, text))
698
- return;
703
+ track(id, target, state) {
699
704
  const now = Date.now();
700
705
  for (const [key, entry] of this.tracked)
701
706
  if (now - entry.at > TRACK_MS)
702
707
  this.tracked.delete(key);
703
708
  while (this.tracked.size >= 512)
704
709
  this.tracked.delete(this.tracked.keys().next().value);
705
- 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";
706
718
  }
707
719
  /** What became of the phone message `id` sent to `target`'s conversation:
708
720
  * queued until the agent submits it, then delivered, or blocked when
709
- * another conversation in the pane took it. Unknown when the Hook did not
710
- * 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. */
711
724
  deliveryState(id, target) {
712
725
  const entry = this.tracked.get(id);
713
- 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";
727
+ }
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");
714
731
  }
715
- /** The oldest queued message tracked for `delivery`'s conversation with these words. */
716
- settleTracked(delivery, prompt, state) {
717
- const key = trackKey(prompt);
718
- const entry = [...this.tracked.values()].find(item => item.state === "queued" && item.key === key && item.source === delivery.source && item.session === delivery.session);
719
- if (entry)
720
- entry.state = state;
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
+ }
721
738
  }
722
739
  /** The conversation `target` just submitted `prompt`. Nothing Phren typed
723
740
  * matches: a locally typed prompt, always allowed. Otherwise the oldest
@@ -725,14 +742,13 @@ export class AgentHooks {
725
742
  * conversation is told to drop it, so the text is never spoken to the
726
743
  * wrong agent and the phone can safely send it again. */
727
744
  submitted(target, prompt) {
728
- const list = this.deliveries.get(promptKey(prompt));
745
+ const list = this.deliveries.get(promptHash(prompt));
729
746
  // The same words sent to two conversations at once: each one's own
730
747
  // submission settles its own record, not whichever was typed first.
731
748
  const delivery = list?.find(entry => entry.source === target.source && entry.session === target.session) ?? list?.[0];
732
749
  if (!delivery)
733
750
  return {};
734
751
  const own = delivery.source === target.source && delivery.session === target.session;
735
- this.settleTracked(delivery, prompt, own ? "delivered" : "blocked");
736
752
  if (own) {
737
753
  delivery.settle("delivered");
738
754
  return {};
@@ -1399,7 +1415,7 @@ export class AgentHooks {
1399
1415
  const summary = entry.request ? { request: entry.request, requestKind: entry.requestKind ?? "other" }
1400
1416
  : approvalSummary({ tool: entry.tool, message: title });
1401
1417
  void this.push.notify({ binding, provider: target.source, question: entry.tool === "AskUserQuestion", expiresAt: new Date(expiresAt).toISOString(),
1402
- ...(cwd ? { project: path.basename(cwd) } : {}), computer: this.computerName, ...summary })
1418
+ ...projectField(cwd), computer: this.computerName, ...summary })
1403
1419
  .then(delivered => { if (!delivered)
1404
1420
  this.dropDialogPush(key); }).catch(() => this.dropDialogPush(key));
1405
1421
  }
@@ -1616,7 +1632,7 @@ export class AgentHooks {
1616
1632
  const binding = randomUUID();
1617
1633
  this.pushBindings.add(binding, { action, expiresAt });
1618
1634
  void this.push.notify({ binding, provider: "codex", question: false, expiresAt: new Date(expiresAt).toISOString(),
1619
- ...(cwd ? { project: path.basename(cwd) } : {}), computer: this.computerName, ...summary })
1635
+ ...projectField(cwd), computer: this.computerName, ...summary })
1620
1636
  .then(delivered => { if (!delivered)
1621
1637
  this.pushBindings.consume(binding); }).catch(() => { });
1622
1638
  }
@@ -1825,7 +1841,7 @@ export class AgentHooks {
1825
1841
  this.pushBindings.add(binding, { action, expiresAt: pushExpiresAt });
1826
1842
  this.pushedHolds.set(action, pushExpiresAt);
1827
1843
  void this.push.notify({ binding, provider: target.source, question: body.tool === "AskUserQuestion",
1828
- 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 => {
1829
1845
  if (!delivered) {
1830
1846
  this.pushBindings.consume(binding);
1831
1847
  this.pushedHolds.delete(action);
@@ -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
@@ -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)) {
@@ -42,7 +42,7 @@ export async function runDispatch(args) {
42
42
  "parent-server": { type: "string" }, "parent-workspace": { type: "string" }, "parent-tab": { type: "string" }, "parent-pane": { type: "string" },
43
43
  } });
44
44
  if (positionals.length !== 2)
45
- throw new Error("Usage: phren dispatch <computer|anywhere> <project> --label <label> --prompt <brief> [--harness codex|claude|opencode] [--model <model>] [--effort minimal|low|medium|high|xhigh|max] [--account <id>] [--permission-mode supervised|auto-edits|auto|full-access] [explicit parent flags]");
45
+ throw new Error("Usage: phren dispatch <computer|anywhere> <project> --label <label> --prompt <brief> [--harness codex|claude|opencode|copilot] [--model <model>] [--effort minimal|low|medium|high|xhigh|max] [--account <id>] [--permission-mode supervised|auto-edits|auto|full-access] [explicit parent flags]");
46
46
  const parentValues = ["parent-provider", "parent-session", "parent-computer", "parent-server", "parent-workspace", "parent-tab", "parent-pane"];
47
47
  const hasParent = parentValues.some(key => values[key] !== undefined);
48
48
  const parent = hasParent ? {
@@ -85,8 +85,9 @@ export interface WorkerObservation {
85
85
  /** When the turn's Stop arrived, on the worker's clock; names the turn. */
86
86
  endedAt?: string;
87
87
  stopSeq?: number;
88
- /** Background tasks the harness still runs: waited on while `working`,
89
- * left running when `done` after BACKGROUND_WAIT_MS. */
88
+ /** Background tasks the harness still runs: waited on while `working`;
89
+ * when `done`, left running (after BACKGROUND_WAIT_MS, or not awaited), so
90
+ * the pane is not closed on them. */
90
91
  background?: number;
91
92
  /** The owner stopped the turn in the worker's terminal. */
92
93
  interrupted?: true;
@@ -15,11 +15,11 @@ import { hookPeers, peerRequest } from "./peers.js";
15
15
  import { isLocalComputer } from "./dispatch-hosts.js";
16
16
  import { BridgeError, objects, startingTargetSchema, targetSchema } from "./protocol.js";
17
17
  import { ownerQuestion, readFinalTurn } from "./schedule-watch.js";
18
- import { liveWork } from "./session-activity.js";
18
+ import { liveWork, runningTasks } from "./session-activity.js";
19
19
  import { terminalProvider } from "./terminal.js";
20
20
  import { childAgentTree, runningChildAgents } from "./transcripts.js";
21
21
  import { opencodeTurn, readTurn, TURN_REPLY_LIMIT, truncateUtf8, turnPhase } from "./turn-records.js";
22
- import { recentUncommitted, sharedCheckout, unfinishedTurn } from "./worker-unfinished.js";
22
+ import { awaitedInReply, recentUncommitted, sharedCheckout, unfinishedTurn } from "./worker-unfinished.js";
23
23
  export { truncateUtf8 } from "./turn-records.js";
24
24
  /**
25
25
  * The conductor's returns loop. The worker's computer answers what its
@@ -65,7 +65,7 @@ const defaultReaders = {
65
65
  snapshot: server => sharedSnapshot(server, SNAPSHOT_AGE_MS),
66
66
  freshSnapshot: snapshot,
67
67
  identity: (server, pane) => paneIdentity(server, pane),
68
- finalTurn: (source, session) => source === "codex" || source === "claude" || source === "opencode" ? readFinalTurn(source, session) : Promise.resolve(undefined),
68
+ finalTurn: (source, session) => source === "codex" || source === "claude" || source === "opencode" || source === "copilot" ? readFinalTurn(source, session) : Promise.resolve(undefined),
69
69
  turn: paneTurn,
70
70
  children: (source, session) => childAgentTree(source, session).then(runningChildAgents).then(children => children.length),
71
71
  stall: (target, pane, live) => sessionStalls.observe(target, pane, live),
@@ -90,12 +90,20 @@ function replyFields(text, truncated) {
90
90
  const reply = truncateUtf8(text);
91
91
  return { reply: reply.text, ...(reply.truncated || truncated ? { truncated: true } : {}) };
92
92
  }
93
+ /** A finished turn's state with nothing awaited left (`liveWork`): working
94
+ * when its reply says it waits on a task that still runs (`awaitedInReply`),
95
+ * else done, carrying what still runs so its pane is not closed on it. */
96
+ function settled(reply, running) {
97
+ if (running && awaitedInReply(reply))
98
+ return { state: "working", background: running };
99
+ return { state: "done", ...(running ? { background: running } : {}) };
100
+ }
93
101
  /** A worker's state from its own turn events. Done means a Stop arrived after
94
102
  * the last submitted prompt with no live work left (see `liveWork`: awaited
95
- * shells plus running children, never a leftover idle shell); a prompt with no
96
- * Stop is still working, unless the pane is idle and the transcript shows the
97
- * owner interrupted it (no Stop comes then) or a finished turn whose Stop the
98
- * Hook never received. */
103
+ * shells plus running children, never a leftover idle shell, and `settled`); a
104
+ * prompt with no Stop is still working, unless the pane is idle and the
105
+ * transcript shows the owner interrupted it (no Stop comes then) or a
106
+ * finished turn whose Stop the Hook never received. */
99
107
  async function fromTurn(record, session, status, source, readers) {
100
108
  const base = { session, hook: true };
101
109
  if (status === "blocked")
@@ -119,12 +127,18 @@ async function fromTurn(record, session, status, source, readers) {
119
127
  const live = liveWork(record, final, children, now);
120
128
  if (live)
121
129
  return { state: "working", ...base, background: live };
122
- return { state: "done", ...base, completed: true, ...(final.error ? { error: final.error } : {}), ...replyFields(final.lastAssistant) };
130
+ const end = settled(final.lastAssistant, runningTasks(record, final, now));
131
+ if (end.state === "working")
132
+ return { ...end, ...base };
133
+ return { ...end, ...base, completed: true, ...(final.error ? { error: final.error } : {}), ...replyFields(final.lastAssistant) };
123
134
  }
124
135
  const live = liveWork(record, final, children, now);
125
136
  if (live)
126
137
  return { state: "working", ...base, background: live };
127
- return { state: "done", ...base, completed: true, endedAt: phase.at, stopSeq: record.stop?.seq,
138
+ const end = settled(phase.reply ?? final?.lastAssistant, runningTasks(record, final, now));
139
+ if (end.state === "working")
140
+ return { ...end, ...base };
141
+ return { ...end, ...base, completed: true, endedAt: phase.at, stopSeq: record.stop?.seq,
128
142
  ...(final?.completed && final.error ? { error: final.error } : {}),
129
143
  ...(phase.reply ? replyFields(phase.reply, phase.truncated) : replyFields(final?.lastAssistant)) };
130
144
  }
@@ -221,11 +235,13 @@ export async function workerStates(input, readers = defaultReaders) {
221
235
  // A finished turn that left live work is still the worker's turn. With no
222
236
  // Stop record, the transcript's awaited shells and the running children are
223
237
  // all there is: a leftover shell alone does not hold it.
224
- const live = turn?.completed ? liveWork(undefined, turn, children, (readers.now ?? Date.now)()) : undefined;
238
+ const now = (readers.now ?? Date.now)();
239
+ const end = turn?.completed ? settled(turn.lastAssistant, runningTasks(undefined, turn, now)) : undefined;
240
+ const live = turn?.completed ? liveWork(undefined, turn, children, now) ?? (end?.state === "working" ? end.background : undefined) : undefined;
225
241
  if (live) {
226
242
  return { state: "working", session, completed: true, background: live, ...(turn?.error ? { error: turn.error } : {}), ...replyFields(turn?.lastAssistant) };
227
243
  }
228
- const seen = { state, session, completed: turn?.completed === true, ...(turn?.error ? { error: turn.error } : {}),
244
+ const seen = { state, session, completed: turn?.completed === true, ...(end?.background ? { background: end.background } : {}), ...(turn?.error ? { error: turn.error } : {}),
229
245
  ...(turn?.interrupted ? { interrupted: true } : {}), ...replyFields(turn?.lastAssistant) };
230
246
  return { ...seen, ...await unfinished(seen, paneDirectory(pane), readers, s, pane) };
231
247
  }));
@@ -3,12 +3,15 @@ import { type DispatchHost } from "./dispatch-hosts.js";
3
3
  import { type Json, type Provider, type Target } from "./protocol.js";
4
4
  import { type BriefArrival } from "./launch-brief.js";
5
5
  export declare const projectName: z.ZodString;
6
+ /** The harnesses a dispatch, a code note's hand-off or a schedule can start. */
7
+ export declare const DISPATCH_HARNESSES: readonly ["codex", "claude", "opencode", "copilot"];
6
8
  export declare const dispatchSchema: z.ZodObject<{
7
9
  computer: z.ZodUnion<readonly [z.ZodLiteral<"anywhere">, z.ZodString]>;
8
10
  project: z.ZodString;
9
11
  harness: z.ZodEnum<{
10
12
  claude: "claude";
11
13
  codex: "codex";
14
+ copilot: "copilot";
12
15
  opencode: "opencode";
13
16
  }>;
14
17
  model: z.ZodOptional<z.ZodString>;
@@ -97,6 +100,7 @@ declare const receiptSchema: z.ZodObject<{
97
100
  harness: z.ZodEnum<{
98
101
  claude: "claude";
99
102
  codex: "codex";
103
+ copilot: "copilot";
100
104
  opencode: "opencode";
101
105
  }>;
102
106
  model: z.ZodOptional<z.ZodString>;
@@ -23,15 +23,17 @@ import { hasUsable } from "./harnesses.js";
23
23
  import { arrivalSchema } from "./launch-brief.js";
24
24
  const text = (max) => z.string().min(1).max(max).refine(value => !!value.trim() && !/[\x00-\x1f\x7f]/.test(value));
25
25
  export const projectName = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,99}$/);
26
+ /** The harnesses a dispatch, a code note's hand-off or a schedule can start. */
27
+ export const DISPATCH_HARNESSES = ["codex", "claude", "opencode", "copilot"];
26
28
  export const dispatchSchema = z.object({
27
29
  computer: z.union([z.literal("anywhere"), computerName]).describe("Enrolled computer name, or anywhere for the least busy connected computer."),
28
30
  project: projectName.describe("Project slug registered on the receiving computer."),
29
- harness: z.enum(["codex", "claude", "opencode"]).describe("Agent harness on the receiving computer."),
31
+ harness: z.enum(DISPATCH_HARNESSES).describe("Agent harness on the receiving computer."),
30
32
  model: text(200).optional().describe("Explicit model, otherwise the remote harness default."),
31
33
  effort: z.enum(launchEfforts).optional().describe("Reasoning effort for the worker (minimal, low, medium, high, xhigh, max), otherwise the harness default."),
32
34
  account: z.string().refine(isAccountSlug, "Account must be default or a lowercase slug.").optional()
33
35
  .describe("Claude account id to run the worker under (default, or a slug from `phren bridge accounts`). anywhere only picks computers where that account is signed in; a named computer without it fails."),
34
- permissionMode: z.enum(PERMISSION_MODES).optional().describe("Permission mode the worker starts in: supervised, auto-edits, auto or full-access (Claude and Codex only); otherwise the receiving computer's own default."),
36
+ permissionMode: z.enum(PERMISSION_MODES).optional().describe("Permission mode the worker starts in: supervised, auto-edits, auto or full-access (Claude, Codex and Copilot; not OpenCode); otherwise the receiving computer's own default."),
35
37
  releaseActions: z.array(releaseAction).min(1).max(RELEASE_ACTIONS.length).optional()
36
38
  .describe("Release-type actions the brief asks the worker to do (merge, publish, deploy, app-store, github-admin). Ask-first projects refuse them from an agent unless the owner confirmed."),
37
39
  prompt: z.string().min(1).max(32768).refine(value => !/[\x00-\x08\x0b-\x1f\x7f]/.test(value)).describe("Worker brief, at most 32768 characters."),
@@ -421,7 +423,7 @@ export class DispatchService {
421
423
  async dispatch(input, originValue) {
422
424
  const data = dispatchSchema.parse(input);
423
425
  if (data.permissionMode && data.harness === "opencode")
424
- throw new BridgeError(400, "OpenCode takes its permissions from its own config; permissionMode is for Claude and Codex workers.");
426
+ throw new BridgeError(400, "OpenCode takes its permissions from its own config; permissionMode is for Claude, Codex and Copilot workers.");
425
427
  if (this.active)
426
428
  throw new BridgeError(429, "A dispatch is already being placed. Try again after its receipt arrives.");
427
429
  this.active = true;
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Marking a folder the Hook chose as trusted, so a Claude or Codex launched
2
+ * Marking a folder the Hook chose as trusted, so a Claude, Codex or Copilot launched
3
3
  * there starts without its folder-trust screen. Claude's default on that
4
4
  * screen is "No, exit", so a dispatched worker would otherwise sit there
5
5
  * until the owner answers it (the brief is never sent; see dispatch.ts).
@@ -15,11 +15,15 @@
15
15
  * that key for the working folder and each parent up to its git root.
16
16
  * - Codex: `[projects."<dir>"]` `trust_level = "trusted"` in
17
17
  * `$CODEX_HOME/config.toml`, the table Codex itself writes on "Yes".
18
+ * - Copilot: the folder added to `trustedFolders` in
19
+ * `$COPILOT_HOME/settings.json` (else `~/.copilot/settings.json`), the list
20
+ * its "Yes, and remember this folder" answer keeps.
18
21
  *
19
- * Both were checked against Claude Code 2.1.280 and codex-cli 0.155.1.
22
+ * Claude and Codex were checked against Claude Code 2.1.280 and codex-cli
23
+ * 0.155.1, Copilot against Copilot CLI 1.0.89.
20
24
  * `PHREN_PRETRUST=off` turns all of it off.
21
25
  */
22
- export type TrustHarness = "claude" | "codex";
26
+ export type TrustHarness = "claude" | "codex" | "copilot";
23
27
  export type TrustResult = "trusted" | "already" | "skipped";
24
28
  export declare function pretrustEnabled(env?: NodeJS.ProcessEnv): boolean;
25
29
  /** Claude Code's global config file, resolved the way Claude resolves it. */
@@ -48,6 +52,12 @@ export declare function codexTrustedText(text: string, dir: string): string | un
48
52
  * file is kept byte for byte. An unreadable config is left untouched.
49
53
  */
50
54
  export declare function ensureCodexDirTrusted(dir: string, env?: NodeJS.ProcessEnv): Promise<TrustResult>;
55
+ /**
56
+ * Adds `dir` to `trustedFolders` in Copilot's `settings.json`, creating the
57
+ * file when Copilot has none yet. Other settings are kept; a file that is not
58
+ * a JSON object is left alone (the launch then meets the trust screen).
59
+ */
60
+ export declare function ensureCopilotFolderTrusted(dir: string, env?: NodeJS.ProcessEnv): Promise<TrustResult>;
51
61
  /**
52
62
  * Trusts `dir` for `harness` before a launch, when the harness has a trust
53
63
  * screen and pre-trust is on. Never throws: a failure is logged and the