@phren/cli 0.3.50 → 0.3.51

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.
@@ -3,7 +3,7 @@ import { chmod, lstat, mkdir, mkdtemp, readFile, rename, rm, writeFile } from "n
3
3
  import { homedir } from "node:os";
4
4
  import path from "node:path";
5
5
  import { promisify } from "node:util";
6
- import { forcedCommand } from "./install.js";
6
+ import { forcedCommand, peerForcedCommand } from "./install.js";
7
7
  import { BridgeError, bridgeRoot, computerName } from "./protocol.js";
8
8
  const exec = promisify(execFile);
9
9
  export { computerName };
@@ -20,7 +20,7 @@ export function publicComputerKey(value) {
20
20
  return `ssh-ed25519 ${match[1]}`;
21
21
  }
22
22
  export function computerKeyLine(name, publicKey) {
23
- return `restrict,pty,${forcedCommand} ${publicComputerKey(publicKey)} phren-computer:${computerName.parse(name)}`;
23
+ return `restrict,${peerForcedCommand} ${publicComputerKey(publicKey)} phren-computer:${computerName.parse(name)}`;
24
24
  }
25
25
  async function regularFile(file) {
26
26
  const info = await lstat(file).catch((error) => {
@@ -70,9 +70,10 @@ export async function enrollComputer(name, root = bridgeRoot()) {
70
70
  /** Accept a public key, rebuilding the restrictions rather than trusting supplied options. */
71
71
  export async function acceptComputer(name, input, sshDirectory = path.join(homedir(), ".ssh")) {
72
72
  computerName.parse(name);
73
- const prefix = `restrict,pty,${forcedCommand} `;
73
+ const prefixes = [`restrict,${peerForcedCommand} `, `restrict,pty,${forcedCommand} `];
74
74
  const raw = input.trim();
75
- const publicKey = publicComputerKey(raw.startsWith(prefix) ? raw.slice(prefix.length) : raw);
75
+ const prefix = prefixes.find(value => raw.startsWith(value));
76
+ const publicKey = publicComputerKey(prefix ? raw.slice(prefix.length) : raw);
76
77
  const line = computerKeyLine(name, publicKey);
77
78
  const encoded = publicKey.split(" ")[1];
78
79
  await appendAuthorizedKey(line, existing => existing.endsWith(` phren-computer:${name}`) || existing.split(/\s+/).includes(encoded), "This name or key is already enrolled differently. Revoke the old line explicitly first.", sshDirectory);
@@ -83,6 +83,10 @@ export declare function conductorPane(server: string, s: Json): Promise<Json | u
83
83
  export declare function recordedConductor(): Promise<ConductorRecord | undefined>;
84
84
  /** Makes `pane` on `server` this computer's conductor, replacing any record. */
85
85
  export declare function recordConductor(server: string, pane: Json, by: ConductorRecord["by"], session?: string): Promise<ConductorRecord>;
86
+ /** Move only the captured role. The optional hand-over holds the receipt
87
+ * writer's queue while preparing routing and committing this role; it must
88
+ * roll routing back if commit fails. No role writer can interleave here. */
89
+ export declare function transferConductor(expected: ConductorRecord, server: string, pane: Json, session?: string, handOver?: (commit: () => Promise<void>) => Promise<void>): Promise<ConductorRecord>;
86
90
  /** The session now running in the conductor's pane: a restart or new login reattaches here. */
87
91
  export declare function noteConductorSession(server: string, pane: string, session: string): Promise<void>;
88
92
  /** Ends the role. With `pane`, only when that pane holds it. Returns what was stopped. */
@@ -1,8 +1,9 @@
1
1
  import { lstatSync, readFileSync } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { z } from "zod";
4
+ import { conductorOriginChanged } from "./dispatch-origins.js";
4
5
  import { isConductorName, paneAgentName } from "./herdr.js";
5
- import { atomicInPrivateDir, bridgeRoot, id, objects, provider, serverName } from "./protocol.js";
6
+ import { atomicInPrivateDir, BridgeError, bridgeRoot, id, objects, provider, serverName } from "./protocol.js";
6
7
  /**
7
8
  * Which pane is this computer's conductor, as the Hook keeps it
8
9
  * (docs/conductor-sets.md). The role follows the pane: server, pane id and
@@ -57,6 +58,7 @@ async function writeRoleState(state) {
57
58
  const file = roleFile();
58
59
  await atomicInPrivateDir(file, JSON.stringify(state, null, 2) + "\n");
59
60
  cached = { file, state };
61
+ conductorOriginChanged(state.conductor);
60
62
  }
61
63
  /** Every read-modify-write of the state runs one at a time: an overview poll
62
64
  * noting a moved pane must not interleave with a make or stop and bring back
@@ -148,6 +150,23 @@ export function recordConductor(server, pane, by, session) {
148
150
  return record;
149
151
  });
150
152
  }
153
+ /** Move only the captured role. The optional hand-over holds the receipt
154
+ * writer's queue while preparing routing and committing this role; it must
155
+ * roll routing back if commit fails. No role writer can interleave here. */
156
+ export function transferConductor(expected, server, pane, session, handOver = commit => commit()) {
157
+ return serialized(async () => {
158
+ const state = await readRoleState();
159
+ const current = state?.conductor;
160
+ // Include the generation (since), terminal and session, so a stop/make
161
+ // or another move cannot be overwritten even if it used the same pane.
162
+ if (!current || !recordSchema.keyof().options.every(field => current[field] === expected[field])) {
163
+ throw new BridgeError(409, "The conductor changed during the move; nothing was transferred.");
164
+ }
165
+ const record = recordFor(server, pane, "owner", session);
166
+ await handOver(() => writeRoleState({ ...state, version: 1, conductor: record }));
167
+ return record;
168
+ });
169
+ }
151
170
  /** The session now running in the conductor's pane: a restart or new login reattaches here. */
152
171
  export function noteConductorSession(server, pane, session) {
153
172
  return serialized(async () => {
@@ -0,0 +1,32 @@
1
+ import { type Provider } from "./protocol.js";
2
+ type PaneIdentity = {
3
+ server: string;
4
+ pane: string;
5
+ terminal?: string;
6
+ };
7
+ type Origin = PaneIdentity & {
8
+ workspace: string;
9
+ tab: string;
10
+ terminal: string;
11
+ agent: Provider;
12
+ };
13
+ export interface DispatchOriginWindow {
14
+ rewrite(origin: Origin | undefined): Origin | undefined;
15
+ finish(): void;
16
+ }
17
+ /** Register before a dispatch's first await; only these live operations can
18
+ * inherit a hand-over alias. A later dispatch starts with no aliases. */
19
+ export declare function trackDispatchOrigin(): DispatchOriginWindow;
20
+ /** Prepare while holding the receipt lock, then seal only after role commit.
21
+ * Keep prior chains in this snapshot because the role write invalidates them.
22
+ * Operations started during the commit are included; later ones never are. */
23
+ export declare function prepareDispatchOriginHandover(from: PaneIdentity, to: Origin): () => void;
24
+ /** Called after every successful role write, without acquiring another lock.
25
+ * A stop or reassignment must not let an earlier move redirect late workers
26
+ * away from the newly chosen conductor. No aliases survive a Hook restart. */
27
+ export declare function conductorOriginChanged(conductor: (PaneIdentity & {
28
+ source?: Provider;
29
+ workspace?: string;
30
+ tab?: string;
31
+ }) | null | undefined): void;
32
+ export {};
@@ -0,0 +1,44 @@
1
+ import { bridgeRoot } from "./protocol.js";
2
+ const pending = new Set();
3
+ const samePane = (left, right) => left.server === right.server && left.pane === right.pane && (left.terminal === undefined || left.terminal === right.terminal);
4
+ /** Register before a dispatch's first await; only these live operations can
5
+ * inherit a hand-over alias. A later dispatch starts with no aliases. */
6
+ export function trackDispatchOrigin() {
7
+ const entry = { root: bridgeRoot(), aliases: [] };
8
+ pending.add(entry);
9
+ return {
10
+ rewrite: origin => origin && (entry.aliases.find(alias => samePane(alias.from, origin))?.to ?? origin),
11
+ finish: () => { pending.delete(entry); entry.aliases = []; },
12
+ };
13
+ }
14
+ /** Prepare while holding the receipt lock, then seal only after role commit.
15
+ * Keep prior chains in this snapshot because the role write invalidates them.
16
+ * Operations started during the commit are included; later ones never are. */
17
+ export function prepareDispatchOriginHandover(from, to) {
18
+ const root = bridgeRoot();
19
+ const before = new Map([...pending].filter(entry => entry.root === root).map(entry => [entry, entry.aliases]));
20
+ return () => {
21
+ for (const entry of pending) {
22
+ if (entry.root !== root)
23
+ continue;
24
+ entry.aliases = (before.get(entry) ?? entry.aliases)
25
+ .filter(alias => !samePane(alias.from, to) && !samePane(alias.from, from))
26
+ .map(alias => samePane(alias.to, from) ? { ...alias, to } : alias);
27
+ entry.aliases.push({ from, to });
28
+ }
29
+ };
30
+ }
31
+ /** Called after every successful role write, without acquiring another lock.
32
+ * A stop or reassignment must not let an earlier move redirect late workers
33
+ * away from the newly chosen conductor. No aliases survive a Hook restart. */
34
+ export function conductorOriginChanged(conductor) {
35
+ const root = bridgeRoot();
36
+ for (const entry of pending) {
37
+ if (entry.root !== root)
38
+ continue;
39
+ entry.aliases = entry.aliases.filter(alias => conductor && samePane(alias.to, conductor)
40
+ && (conductor.source === undefined || alias.to.agent === conductor.source)
41
+ && (conductor.workspace === undefined || alias.to.workspace === conductor.workspace)
42
+ && (conductor.tab === undefined || alias.to.tab === conductor.tab));
43
+ }
44
+ }
@@ -231,7 +231,8 @@ export interface DispatchReturnsOptions {
231
231
  };
232
232
  now?: () => number;
233
233
  }
234
- /** One notice's delivery id, named by what it reports: the same returns keep the same id on a retry. */
234
+ /** The same returns to the same origin keep their id on retry. A role
235
+ * hand-over gets a fresh delivery instead of reusing the old chat's receipt. */
235
236
  export declare function noticeDeliveryId(receipts: readonly Receipt[]): string;
236
237
  /** Dispatching side: follows open dispatches and delivers their returns. */
237
238
  export declare class DispatchReturns {
@@ -522,9 +522,10 @@ export function returnRow(receipt) {
522
522
  ...(receipt.moves ? { moves: receipt.moves } : {}), ...(receipt.target ? { target: receipt.target } : {}) };
523
523
  }
524
524
  const originKey = (origin) => JSON.stringify([origin.server, origin.workspace, origin.tab, origin.pane, origin.terminal]);
525
- /** One notice's delivery id, named by what it reports: the same returns keep the same id on a retry. */
525
+ /** The same returns to the same origin keep their id on retry. A role
526
+ * hand-over gets a fresh delivery instead of reusing the old chat's receipt. */
526
527
  export function noticeDeliveryId(receipts) {
527
- return `notice-${createHash("sha256").update(receipts.map(receipt => `${receipt.id}@${receipt.returned.at}`).sort().join(",")).digest("hex").slice(0, 32)}`;
528
+ return `notice-${createHash("sha256").update(receipts.map(receipt => `${receipt.id}@${receipt.returned.at}@${receipt.origin ? originKey(receipt.origin) : ""}`).sort().join(",")).digest("hex").slice(0, 32)}`;
528
529
  }
529
530
  /** Dispatching side: follows open dispatches and delivers their returns. */
530
531
  export class DispatchReturns {
@@ -762,6 +763,12 @@ export class DispatchReturns {
762
763
  const at = new Date(this.now()).toISOString();
763
764
  for (const receipt of receipts) {
764
765
  await updateReceipt(receipt.id, current => {
766
+ // An in-flight notice to the old chat must not acknowledge a return
767
+ // whose origin changed while delivery was pending.
768
+ if (!current.origin || originKey(current.origin) !== key) {
769
+ busy = true;
770
+ return false;
771
+ }
765
772
  if (!current.returned || current.returned.read || current.returned.at !== receipt.returned.at)
766
773
  return false;
767
774
  current.returned.notifiedAt = at;
@@ -1,4 +1,5 @@
1
1
  import { z } from "zod";
2
+ import { type ConductorRecord } from "./conductor-role.js";
2
3
  import { type DispatchHost } from "./dispatch-hosts.js";
3
4
  import { type Json, type Provider, type Target } from "./protocol.js";
4
5
  import { type HarnessInventory } from "./harnesses.js";
@@ -421,6 +422,10 @@ export declare function dispatchProjectDirectory(project: unknown, home?: string
421
422
  * receipt still being placed (launching or sending) is never touched.
422
423
  */
423
424
  export declare function updateReceipt(receiptID: string, change: (receipt: Receipt) => boolean): Promise<Receipt | undefined>;
425
+ /** Hand over all open worker routes using the receipt writer's own lock and
426
+ * update path. Commit the role last; any failure restores the old origins.
427
+ * Placing receipts are refused because placement can still overwrite them. */
428
+ export declare function repointDispatchOrigins(from: Pick<ConductorRecord, "server" | "pane" | "terminal">, to: NonNullable<Receipt["origin"]>, commit: () => Promise<void>): Promise<void>;
424
429
  /** One bounded line for a log or a receipt: a Bridge message, an errno code, or the error's first line. */
425
430
  export declare function failureReason(error: unknown): string;
426
431
  export declare function dispatchStatus(): Promise<Receipt[]>;
@@ -13,6 +13,7 @@ import { findGrant, grantLabel, permissionModeAllowed, DEFAULT_MAX_PERMISSION_MO
13
13
  import { checkAgentDispatch, projectAuthority, readAuthority, RELEASE_ACTIONS, releaseAction } from "./authority.js";
14
14
  import { hookPeers } from "./peers.js";
15
15
  import { callerQuery, localCaller, oneWayHint } from "./conductor-group.js";
16
+ import { prepareDispatchOriginHandover, trackDispatchOrigin } from "./dispatch-origins.js";
16
17
  import { recordedConductor } from "./conductor-role.js";
17
18
  import { linkedComputer } from "./computer-identity.js";
18
19
  import { isLocalComputer, localHost, peerHost } from "./dispatch-hosts.js";
@@ -133,7 +134,20 @@ export async function dispatchProjectDirectory(project, home = homeDir()) {
133
134
  }
134
135
  throw new BridgeError(404, `Project ${name} is not on this computer: the store names no folder for ${getMachineName()} that exists here, and there is no ~/Projects/${name} checkout.`);
135
136
  }
136
- async function save(receipt) {
137
+ function save(receipt, originWindow) {
138
+ return serializeReceiptUpdate(async () => {
139
+ // Only this already-running dispatch can inherit a hand-over alias.
140
+ // Resolve it under the receipt lock, after any role change invalidation.
141
+ const origin = originWindow.rewrite(receipt.origin);
142
+ if (origin !== receipt.origin && !receipt.closedAt) {
143
+ receipt.origin = origin;
144
+ if (receipt.returned && !receipt.returned.read)
145
+ delete receipt.returned.notifiedAt;
146
+ }
147
+ await saveReceipt(receipt);
148
+ });
149
+ }
150
+ async function saveReceipt(receipt) {
137
151
  const root = path.join(bridgeRoot(), "dispatches");
138
152
  await mkdir(root, { recursive: true, mode: 0o700 });
139
153
  await atomic(path.join(root, `${receipt.id}.json`), receipt);
@@ -147,23 +161,99 @@ let receiptUpdates = Promise.resolve();
147
161
  * receipt still being placed (launching or sending) is never touched.
148
162
  */
149
163
  export function updateReceipt(receiptID, change) {
150
- const run = receiptUpdates.then(async () => {
151
- const file = path.join(bridgeRoot(), "dispatches", `${z.string().uuid().parse(receiptID)}.json`);
152
- const info = await lstat(file).catch(() => undefined);
153
- if (!info?.isFile() || info.isSymbolicLink() || info.size > MAX_RECEIPT_BYTES)
154
- return undefined;
155
- const receipt = receiptSchema.parse(JSON.parse(await readFile(file, "utf8")));
156
- if (["launching", "sending"].includes(receipt.state))
157
- return undefined;
158
- if (!change(receipt))
159
- return receipt;
160
- receipt.updatedAt = new Date().toISOString();
161
- await atomic(file, receiptSchema.parse(receipt));
162
- return receipt;
163
- });
164
+ return serializeReceiptUpdate(() => changeReceipt(receiptID, change));
165
+ }
166
+ function serializeReceiptUpdate(change) {
167
+ const run = receiptUpdates.then(change);
164
168
  receiptUpdates = run.catch(() => undefined);
165
169
  return run;
166
170
  }
171
+ async function readReceipt(receiptID) {
172
+ const file = path.join(bridgeRoot(), "dispatches", `${z.string().uuid().parse(receiptID)}.json`);
173
+ const info = await lstat(file).catch(error => {
174
+ if (error.code !== "ENOENT")
175
+ throw error;
176
+ return undefined;
177
+ });
178
+ if (!info?.isFile() || info.isSymbolicLink() || info.size > MAX_RECEIPT_BYTES)
179
+ return undefined;
180
+ return receiptSchema.parse(JSON.parse(await readFile(file, "utf8")));
181
+ }
182
+ /** Caller holds receiptUpdates; ordinary polling never edits a placing receipt. */
183
+ async function changeReceipt(receiptID, change) {
184
+ const receipt = await readReceipt(receiptID);
185
+ if (!receipt || ["launching", "sending"].includes(receipt.state))
186
+ return undefined;
187
+ if (!change(receipt))
188
+ return receipt;
189
+ receipt.updatedAt = new Date().toISOString();
190
+ await saveReceipt(receiptSchema.parse(receipt));
191
+ return receipt;
192
+ }
193
+ /** Hand over all open worker routes using the receipt writer's own lock and
194
+ * update path. Commit the role last; any failure restores the old origins.
195
+ * Placing receipts are refused because placement can still overwrite them. */
196
+ export function repointDispatchOrigins(from, to, commit) {
197
+ return serializeReceiptUpdate(async () => {
198
+ const seal = prepareDispatchOriginHandover(from, to);
199
+ const names = await readdir(path.join(bridgeRoot(), "dispatches")).catch(error => {
200
+ if (error.code !== "ENOENT")
201
+ throw error;
202
+ return [];
203
+ });
204
+ const matches = (origin) => origin?.server === from.server && origin.pane === from.pane
205
+ && (from.terminal === undefined || origin.terminal === from.terminal);
206
+ const selected = [];
207
+ for (const name of names.filter(name => /^[a-f0-9-]{36}\.json$/.test(name))) {
208
+ const receipt = await readReceipt(name.slice(0, -5));
209
+ if (!receipt || receipt.closedAt || !matches(receipt.origin))
210
+ continue;
211
+ if (["launching", "sending"].includes(receipt.state))
212
+ throw new BridgeError(409, "A conductor dispatch is still being placed; retry the move after it settles.");
213
+ selected.push(receipt);
214
+ }
215
+ const changed = [];
216
+ try {
217
+ for (const before of selected) {
218
+ await changeReceipt(before.id, receipt => {
219
+ if (receipt.closedAt || !matches(receipt.origin))
220
+ return false;
221
+ receipt.origin = to;
222
+ // Unread returns already announced to the old chat need a new notice.
223
+ if (receipt.returned && !receipt.returned.read)
224
+ delete receipt.returned.notifiedAt;
225
+ return true;
226
+ });
227
+ changed.push(before);
228
+ }
229
+ await commit();
230
+ seal();
231
+ }
232
+ catch (error) {
233
+ const failures = [];
234
+ for (const before of changed.reverse()) {
235
+ try {
236
+ await changeReceipt(before.id, receipt => {
237
+ receipt.origin = before.origin;
238
+ if (receipt.returned && receipt.returned.at === before.returned?.at) {
239
+ if (before.returned.notifiedAt)
240
+ receipt.returned.notifiedAt = before.returned.notifiedAt;
241
+ else
242
+ delete receipt.returned.notifiedAt;
243
+ }
244
+ return true;
245
+ });
246
+ }
247
+ catch (rollback) {
248
+ failures.push(`${before.id}: ${failureReason(rollback)}`);
249
+ }
250
+ }
251
+ if (failures.length)
252
+ throw new Error(`${failureReason(error)} Receipt routing rollback failed: ${failures.join("; ")}`);
253
+ throw error;
254
+ }
255
+ });
256
+ }
167
257
  /** No ledger yet is normal; any other read failure is logged before it reads as empty. */
168
258
  async function receiptNames(root) {
169
259
  try {
@@ -183,7 +273,11 @@ export function failureReason(error) {
183
273
  const message = error instanceof Error ? error.message.split("\n")[0] : String(error);
184
274
  return `${typeof code === "string" && !(error instanceof BridgeError) ? `${code}: ` : ""}${message}`.replace(/[\x00-\x1f\x7f]/g, " ").slice(0, 200);
185
275
  }
186
- export async function dispatchStatus() {
276
+ export function dispatchStatus() {
277
+ return serializeReceiptUpdate(readDispatchStatus);
278
+ }
279
+ /** Caller holds receiptUpdates, including for the entire routing snapshot. */
280
+ async function readDispatchStatus() {
187
281
  const root = path.join(bridgeRoot(), "dispatches");
188
282
  const names = (await receiptNames(root)).filter(name => /^[a-f0-9-]{36}\.json$/.test(name)).slice(0, 1024);
189
283
  const receipts = [];
@@ -476,6 +570,7 @@ export class DispatchService {
476
570
  if (this.active)
477
571
  throw new BridgeError(429, "A dispatch is already being placed. Try again after its receipt arrives.");
478
572
  this.active = true;
573
+ const originWindow = trackDispatchOrigin();
479
574
  let holding = true, placed;
480
575
  const release = () => { if (holding) {
481
576
  holding = false;
@@ -582,7 +677,7 @@ export class DispatchService {
582
677
  ...(grant ? { granted: grantLabel(grant) } : {}), ...(authority?.listed ? { authority: authority.line.slice(0, 600) } : {}),
583
678
  ...(checked?.confirmation ? { authorityConfirmed: checked.confirmation.confirmedAt } : {}),
584
679
  ...(skipped.length ? { skipped } : {}), ...(origin ? { origin } : {}), ...(continues ? { continues } : {}) };
585
- await save(receipt);
680
+ await save(receipt, originWindow);
586
681
  try {
587
682
  // The brief goes with the launch: a Hook that can start the harness
588
683
  // with it says so, and any other types it below.
@@ -602,11 +697,11 @@ export class DispatchService {
602
697
  const ignored = data.permissionMode && launched.permissionMode !== data.permissionMode ? IGNORED_MODE : undefined;
603
698
  if (launched.briefLaunched === true) {
604
699
  receipt.brief = "launch";
605
- await this.confirmLaunched(peer, receipt, launched);
700
+ await this.confirmLaunched(peer, receipt, launched, originWindow);
606
701
  if (ignored)
607
702
  receipt.error = [receipt.error, ignored].filter(Boolean).join(" ").slice(0, 500);
608
703
  receipt.updatedAt = new Date().toISOString();
609
- await save(receipt);
704
+ await save(receipt, originWindow);
610
705
  return { ok: receipt.state === "accepted", ...receipt };
611
706
  }
612
707
  receipt.brief = "typed";
@@ -622,7 +717,7 @@ export class DispatchService {
622
717
  receipt.target = target;
623
718
  receipt.state = "sending";
624
719
  receipt.updatedAt = new Date().toISOString();
625
- await save(receipt);
720
+ await save(receipt, originWindow);
626
721
  if (!("starting" in target)) {
627
722
  const result = await sendBrief(peer, target, prompt, `dispatch-${receipt.id}`);
628
723
  receipt.state = result.ok === true && result.deliveryUncertain !== true ? "accepted" : "uncertain";
@@ -647,10 +742,11 @@ export class DispatchService {
647
742
  }
648
743
  }
649
744
  receipt.updatedAt = new Date().toISOString();
650
- await save(receipt);
745
+ await save(receipt, originWindow);
651
746
  return { ok: receipt.state === "accepted", ...receipt };
652
747
  }
653
748
  finally {
749
+ originWindow.finish();
654
750
  release();
655
751
  if (placed) {
656
752
  const left = this.inFlight(placed) - 1;
@@ -724,13 +820,13 @@ export class DispatchService {
724
820
  * itself, so that is not a failure. Neither confirmed nor held reads
725
821
  * uncertain, and the returns loop keeps asking.
726
822
  */
727
- async confirmLaunched(peer, receipt, launched) {
823
+ async confirmLaunched(peer, receipt, launched, originWindow) {
728
824
  const known = remoteTarget.safeParse(launched.target);
729
825
  if (known.success && known.data.source === receipt.harness && known.data.server === peer.server)
730
826
  receipt.target = known.data;
731
827
  receipt.state = "sending";
732
828
  receipt.updatedAt = new Date().toISOString();
733
- await save(receipt);
829
+ await save(receipt, originWindow);
734
830
  const held = (status) => ["blocked", "waiting"].includes(String(status));
735
831
  const arrival = held(launched.agentStatus) ? await arrivalOf(peer, receipt.id).catch(() => undefined) ?? {}
736
832
  : await awaitArrival(peer, receipt.id, this.settleIntervalMs);
@@ -89,6 +89,7 @@ export declare const moveSessionSchema: z.ZodObject<{
89
89
  export declare function moveSession(input: unknown, options?: {
90
90
  waitMs?: number;
91
91
  pollMs?: number;
92
+ agent?: boolean;
92
93
  }): Promise<{
93
94
  ok: boolean;
94
95
  move: Json;
@@ -161,7 +161,7 @@ export async function moveSession(input, options = {}) {
161
161
  if (peer && target.server !== peer.server)
162
162
  throw new BridgeError(400, "The target belongs to a different Herdr server on that computer.");
163
163
  const to = { harness: data.harness, ...(data.account ? { account: data.account } : {}), ...(data.model ? { model: data.model } : {}), ...(data.effort ? { effort: data.effort } : {}) };
164
- move = object((await request("/v1/sessions/move", { target, to: moveToSchema.parse(to), ...(data.id ? { id: data.id } : {}) })).move);
164
+ move = object((await request("/v1/sessions/move", { target, to: moveToSchema.parse(to), ...(options.agent ? { origin: "agent" } : {}), ...(data.id ? { id: data.id } : {}) })).move);
165
165
  if (data.wait !== false && typeof move.id === "string") {
166
166
  const until = Date.now() + (options.waitMs ?? MOVE_WAIT_MS);
167
167
  while (!settled(move) && Date.now() < until) {
@@ -1,6 +1,7 @@
1
1
  import { type ModuleSnapshot } from "../modules/runtime.js";
2
2
  import type { GatewayScope } from "./scoped-gateway.js";
3
3
  import { type CodexServerEntry } from "./codex-servers.js";
4
+ export declare const peerForcedCommand = "command=\"sh ~/.local/share/phren/bridge/dispatch-scoped peer\"";
4
5
  export declare const forcedCommand = "command=\"sh ~/.local/share/phren/bridge/dispatch\"";
5
6
  /** A scoped key's forced command. A separate script, so a key added before
6
7
  * the Hook can serve its scope fails closed instead of reaching `dispatch`. */
@@ -22,6 +22,7 @@ import { serversInService } from "./codex-servers.js";
22
22
  const exec = promisify(execFile);
23
23
  const label = "com.phren.hook";
24
24
  const unit = "phren-hook.service";
25
+ export const peerForcedCommand = 'command="sh ~/.local/share/phren/bridge/dispatch-scoped peer"';
25
26
  export const forcedCommand = 'command="sh ~/.local/share/phren/bridge/dispatch"';
26
27
  /** A scoped key's forced command. A separate script, so a key added before
27
28
  * the Hook can serve its scope fails closed instead of reaching `dispatch`. */
@@ -52,6 +53,12 @@ export function upgradeKeys(text) {
52
53
  let changed = 0;
53
54
  const result = text.split(/(?<=\n)/).map(line => {
54
55
  const parsed = keyOptions(line);
56
+ if (parsed && parsed.options[0] === "restrict" && /^\s+ssh-ed25519 [A-Za-z0-9+/=]+ phren-computer:[A-Za-z0-9_.-]+\s*$/.test(parsed.rest)
57
+ && parsed.options.includes(forcedCommand)) {
58
+ changed++;
59
+ return parsed.options.filter(option => option !== "pty" && option.toLowerCase() !== "port-forwarding" && !option.toLowerCase().startsWith("permitopen="))
60
+ .map(option => option === forcedCommand ? peerForcedCommand : option).join(",") + parsed.rest;
61
+ }
55
62
  if (!parsed || parsed.options[0] !== "restrict" || !/^\s+ssh-ed25519 [A-Za-z0-9+/=]+ phren-(?:iphone|android)\s*$/.test(parsed.rest))
56
63
  return line;
57
64
  const old = /^command="(?:\/usr\/bin\/false|python3 ~\/\.local\/share\/phren\/chat-progress\.py|sh ~\/\.local\/share\/phren\/bridge\/dispatch)"$/;
@@ -0,0 +1,6 @@
1
+ import type { IncomingMessage } from "node:http";
2
+ import type { Json } from "./protocol.js";
3
+ /** Owner phone/desktop gateways and the owner's local CLI carry no agent or
4
+ * peer origin. Peer keys are forced through the peer scope, which rebuilds
5
+ * the request with its own origin header; MCP calls carry an agent origin. */
6
+ export declare function ownerRequest(request: Pick<IncomingMessage, "headers">, data: Json): boolean;
@@ -0,0 +1,6 @@
1
+ /** Owner phone/desktop gateways and the owner's local CLI carry no agent or
2
+ * peer origin. Peer keys are forced through the peer scope, which rebuilds
3
+ * the request with its own origin header; MCP calls carry an agent origin. */
4
+ export function ownerRequest(request, data) {
5
+ return request.headers?.["x-phren-origin"] === undefined && data.origin === undefined;
6
+ }
@@ -16,6 +16,9 @@ export type Admission = {
16
16
  };
17
17
  /** Decide one request: its head (through the blank line) and the bytes after it. */
18
18
  export declare function admitScopedRequest(scope: GatewayScope, rawHead: string, rest?: Buffer): Admission;
19
+ /** A computer key's forced scope rebuilds the HTTP envelope. Client headers
20
+ * cannot impersonate the owner gateway, and peer keys cannot open terminals. */
21
+ export declare function admitPeerRequest(rawHead: string, rest?: Buffer): Admission;
19
22
  export interface ScopedIO {
20
23
  input: Readable;
21
24
  output: Writable;
@@ -123,6 +123,8 @@ export function admitScopedRequest(scope, rawHead, rest = Buffer.alloc(0)) {
123
123
  if ("ok" in head)
124
124
  return head;
125
125
  const rule = findRule(scope, head);
126
+ if (!rule && head.path === "/v1/sessions/move")
127
+ return refuse(403, "Only the owner can move the conductor.");
126
128
  if (!rule)
127
129
  return refuse(403, `This key only permits ${DESCRIBE[scope]}.`);
128
130
  let target = head.path;
@@ -163,6 +165,22 @@ export function admitScopedRequest(scope, rawHead, rest = Buffer.alloc(0)) {
163
165
  const body = JSON.stringify(checked.data);
164
166
  return { ok: true, request: `${rule.method} ${target} HTTP/1.1\r\nHost: phren.local\r\nContent-Type: application/json\r\nContent-Length: ${Buffer.byteLength(body)}\r\nConnection: close\r\n\r\n${body}` };
165
167
  }
168
+ /** A computer key's forced scope rebuilds the HTTP envelope. Client headers
169
+ * cannot impersonate the owner gateway, and peer keys cannot open terminals. */
170
+ export function admitPeerRequest(rawHead, rest = Buffer.alloc(0)) {
171
+ const head = parseHead(rawHead);
172
+ if ("ok" in head)
173
+ return head;
174
+ if (!["GET", "POST", "DELETE"].includes(head.method) || !head.path.startsWith("/v1/"))
175
+ return refuse(403, "This key only permits Hook API requests.");
176
+ if (head.contentLength > 8 * 1024 * 1024 || rest.length !== head.contentLength)
177
+ return refuse(400, "Send one bounded request matching Content-Length.");
178
+ if (rest.length && !head.json)
179
+ return refuse(415, "Send Content-Type: application/json.");
180
+ const body = rest.toString("utf8");
181
+ const target = head.path + (head.query === null ? "" : `?${head.query}`);
182
+ return { ok: true, request: `${head.method} ${target} HTTP/1.1\r\nHost: phren.local\r\nX-Phren-Origin: peer\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: ${Buffer.byteLength(body)}\r\n\r\n${body}` };
183
+ }
166
184
  const REASONS = { 400: "Bad Request", 403: "Forbidden", 408: "Request Timeout", 413: "Content Too Large", 415: "Unsupported Media Type", 503: "Service Unavailable" };
167
185
  function httpResponse(status, error) {
168
186
  const body = JSON.stringify({ error, code: status === 503 ? "hook-unavailable" : "scope-refused" });
@@ -172,7 +190,7 @@ function httpResponse(status, error) {
172
190
  * a body within its cap, exactly that many bytes. Stops at a limit, the
173
191
  * timeout or EOF; bytes beyond the request make it refused. */
174
192
  function readRequest(scope, input) {
175
- const bodyCap = Math.max(0, ...RULES[scope].map(rule => rule.body?.max ?? 0));
193
+ const bodyCap = scope === "peer" ? 8 * 1024 * 1024 : Math.max(0, ...RULES[scope].map(rule => rule.body?.max ?? 0));
176
194
  return new Promise(resolve => {
177
195
  let buffer = Buffer.alloc(0), headEnd = -1, wanted = 0;
178
196
  const finish = (value) => {
@@ -214,12 +232,12 @@ function readRequest(scope, input) {
214
232
  * reads a normal response.
215
233
  */
216
234
  export async function scopedDispatch(scope, command, io) {
217
- if (!isGatewayScope(scope))
235
+ if (scope !== "peer" && !isGatewayScope(scope))
218
236
  throw new BridgeError(403, "Unknown key scope.");
219
237
  if (command !== SCOPED_COMMAND)
220
- throw new BridgeError(403, `This SSH key only permits \`${SCOPED_COMMAND}\` with ${DESCRIBE[scope]}.`);
238
+ throw new BridgeError(403, `This SSH key only permits \`${SCOPED_COMMAND}\` with ${scope === "peer" ? "Hook API requests" : DESCRIBE[scope]}.`);
221
239
  const read = await readRequest(scope, io.input);
222
- const admission = "head" in read ? admitScopedRequest(scope, read.head, read.rest) : refuse(read.status, read.error);
240
+ const admission = "head" in read ? (scope === "peer" ? admitPeerRequest(read.head, read.rest) : admitScopedRequest(scope, read.head, read.rest)) : refuse(read.status, read.error);
223
241
  if (!admission.ok) {
224
242
  await new Promise(done => io.output.write(httpResponse(admission.status, admission.error), () => done()));
225
243
  return;
@@ -135,6 +135,7 @@ export declare const capabilities: {
135
135
  launchPermissionMode: boolean;
136
136
  sessionMove: boolean;
137
137
  moveNewChat: boolean;
138
+ moveConductor: boolean;
138
139
  projectMemory: boolean;
139
140
  fileWrite: boolean;
140
141
  fileSearch: boolean;