@phren/cli 0.3.53 → 0.3.54

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 (51) hide show
  1. package/dist/bridge/account-add.d.ts +7 -0
  2. package/dist/bridge/account-add.js +39 -0
  3. package/dist/bridge/claude-accounts.js +1 -1
  4. package/dist/bridge/client.js +1 -1
  5. package/dist/bridge/command.js +2 -0
  6. package/dist/bridge/computers.js +3 -2
  7. package/dist/bridge/conductor-role.d.ts +162 -2
  8. package/dist/bridge/conductor-role.js +56 -23
  9. package/dist/bridge/conductor-succession.d.ts +100 -0
  10. package/dist/bridge/conductor-succession.js +649 -0
  11. package/dist/bridge/continuation-launch.d.ts +54 -0
  12. package/dist/bridge/continuation-launch.js +106 -0
  13. package/dist/bridge/dispatch-command.js +11 -4
  14. package/dist/bridge/dispatch-hosts.d.ts +3 -0
  15. package/dist/bridge/dispatch-hosts.js +6 -1
  16. package/dist/bridge/dispatch-returns.d.ts +21 -3
  17. package/dist/bridge/dispatch-returns.js +169 -39
  18. package/dist/bridge/dispatch.d.ts +11 -0
  19. package/dist/bridge/dispatch.js +70 -5
  20. package/dist/bridge/hand-off-queue.d.ts +3 -0
  21. package/dist/bridge/hand-off-queue.js +8 -0
  22. package/dist/bridge/hand-off.d.ts +13 -0
  23. package/dist/bridge/hand-off.js +20 -1
  24. package/dist/bridge/install.js +0 -6
  25. package/dist/bridge/launch-brief.d.ts +2 -0
  26. package/dist/bridge/launch-brief.js +19 -8
  27. package/dist/bridge/move-computers.d.ts +47 -0
  28. package/dist/bridge/move-computers.js +118 -0
  29. package/dist/bridge/peer-handoff.d.ts +5 -0
  30. package/dist/bridge/peer-handoff.js +52 -0
  31. package/dist/bridge/request-origin.d.ts +6 -0
  32. package/dist/bridge/request-origin.js +20 -0
  33. package/dist/bridge/scoped-gateway.d.ts +2 -1
  34. package/dist/bridge/scoped-gateway.js +16 -3
  35. package/dist/bridge/server-launch.d.ts +2 -0
  36. package/dist/bridge/server-launch.js +2 -0
  37. package/dist/bridge/server-routes.d.ts +6 -0
  38. package/dist/bridge/server-routes.js +228 -15
  39. package/dist/bridge/server.js +39 -12
  40. package/dist/bridge/session-move.d.ts +28 -1
  41. package/dist/bridge/session-move.js +266 -25
  42. package/dist/bridge/terminal-herdr.js +14 -0
  43. package/dist/bridge/terminal-tmux.js +1 -0
  44. package/dist/bridge/terminal.d.ts +2 -0
  45. package/dist/bridge/terminal.js +6 -0
  46. package/dist/bridge/worker-relocation.d.ts +5 -0
  47. package/dist/bridge/worker-relocation.js +33 -0
  48. package/dist/bridge-hook.mjs +16154 -14087
  49. package/dist/modules/registry.js +8 -8
  50. package/dist/tools/dispatch.js +2 -1
  51. package/package.json +1 -1
@@ -0,0 +1,54 @@
1
+ import { z } from "zod";
2
+ import { type Json } from "./protocol.js";
3
+ import type { PeerIdentity } from "./request-origin.js";
4
+ export declare const continuationLaunchSchema: z.ZodObject<{
5
+ workerDispatch: z.ZodOptional<z.ZodString>;
6
+ worker: z.ZodDefault<z.ZodBoolean>;
7
+ computerId: z.ZodString;
8
+ project: z.ZodString;
9
+ to: z.ZodObject<{
10
+ computer: z.ZodOptional<z.ZodString>;
11
+ harness: z.ZodEnum<{
12
+ claude: "claude";
13
+ codex: "codex";
14
+ copilot: "copilot";
15
+ opencode: "opencode";
16
+ }>;
17
+ account: z.ZodOptional<z.ZodString>;
18
+ model: z.ZodOptional<z.ZodString>;
19
+ effort: z.ZodOptional<z.ZodEnum<{
20
+ high: "high";
21
+ low: "low";
22
+ max: "max";
23
+ medium: "medium";
24
+ minimal: "minimal";
25
+ xhigh: "xhigh";
26
+ }>>;
27
+ }, z.core.$strict>;
28
+ label: z.ZodString;
29
+ brief: z.ZodObject<{
30
+ id: z.ZodString;
31
+ text: z.ZodString;
32
+ }, z.core.$strict>;
33
+ }, z.core.$strict>;
34
+ type Placement = {
35
+ hash: string;
36
+ worker?: boolean;
37
+ workerDispatch?: string;
38
+ state: "uncertain" | "placed" | "not-placed";
39
+ createdAt?: number;
40
+ server?: string;
41
+ caller?: PeerIdentity;
42
+ paneTarget?: Json;
43
+ result?: Json;
44
+ };
45
+ /** A durable intent precedes creation. An interrupted intent is reconciled by
46
+ * its brief arrival, never by creating another pane. */
47
+ export declare function continuationPlacement(id: string, includeCreating?: boolean): Promise<Placement | undefined>;
48
+ export declare function launchContinuation(input: unknown, launch: (data: z.infer<typeof continuationLaunchSchema>, placed: (paneTarget: Json) => Promise<void>) => Promise<Json>, authorization?: {
49
+ caller?: PeerIdentity;
50
+ server: string;
51
+ }): Promise<Json>;
52
+ export declare function saveContinuationIntent(input: Json): Promise<void>;
53
+ export declare function continuationIntent(id: string): Promise<Json>;
54
+ export {};
@@ -0,0 +1,106 @@
1
+ import { createHash } from "node:crypto";
2
+ import { readFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { z } from "zod";
5
+ import { atomicInPrivateDir, BridgeError, bridgeRoot } from "./protocol.js";
6
+ import { terminalProvider } from "./terminal.js";
7
+ import { briefArrival, briefId, assertUnusedLaunchId } from "./launch-brief.js";
8
+ import { moveToSchema, projectName } from "./dispatch.js";
9
+ export const continuationLaunchSchema = z.object({
10
+ workerDispatch: briefId.optional(), worker: z.boolean().default(false), computerId: z.string().uuid(), project: projectName, to: moveToSchema.refine(to => to.computer === undefined, "A receiving launch is local only."), label: z.string().max(200),
11
+ brief: z.object({ id: z.string().uuid(), text: z.string().min(1).max(32768) }).strict(),
12
+ }).strict();
13
+ const queues = new Map();
14
+ const creating = new Map();
15
+ const fileFor = (id) => path.join(bridgeRoot(), "move-launches", `${z.string().uuid().parse(id)}.json`);
16
+ /** A durable intent precedes creation. An interrupted intent is reconciled by
17
+ * its brief arrival, never by creating another pane. */
18
+ export async function continuationPlacement(id, includeCreating = true) {
19
+ let saved;
20
+ try {
21
+ saved = JSON.parse(await readFile(fileFor(id), "utf8"));
22
+ }
23
+ catch (error) {
24
+ if (error.code === "ENOENT")
25
+ return includeCreating ? creating.get(fileFor(id)) : undefined;
26
+ throw error;
27
+ }
28
+ if (!saved.result) {
29
+ const arrived = (await briefArrival(id))?.accepted?.target;
30
+ if (arrived) {
31
+ saved = { ...saved, state: "placed", result: { target: arrived, briefLaunched: true } };
32
+ await atomicInPrivateDir(fileFor(id), JSON.stringify(saved));
33
+ }
34
+ }
35
+ if (!saved.result && !queues.has(fileFor(id)) && saved.createdAt && Date.now() - saved.createdAt >= 10 * 60_000 && saved.server) {
36
+ // A unique creation label covers a crash between create() and onPlaced().
37
+ // Failure to inspect the terminal keeps the placement uncertain.
38
+ const panes = await terminalProvider().listPanes(saved.server);
39
+ if (!panes.some(pane => pane.label === `move-${id}` || saved.paneTarget && pane.pane === saved.paneTarget.pane)) {
40
+ saved = { ...saved, state: "not-placed" };
41
+ await atomicInPrivateDir(fileFor(id), JSON.stringify(saved));
42
+ }
43
+ }
44
+ return saved;
45
+ }
46
+ export async function launchContinuation(input, launch, authorization) {
47
+ const data = continuationLaunchSchema.parse(input);
48
+ const file = fileFor(data.brief.id);
49
+ const hash = createHash("sha256").update(JSON.stringify(data)).digest("hex");
50
+ const pending = queues.get(file);
51
+ if (pending) {
52
+ await pending.catch(() => undefined);
53
+ return launchContinuation(data, launch, authorization);
54
+ }
55
+ const metadata = { hash, worker: data.worker, ...(data.workerDispatch ? { workerDispatch: data.workerDispatch } : {}), createdAt: Date.now(), ...authorization };
56
+ creating.set(file, { ...metadata, state: "uncertain" });
57
+ const work = (async () => {
58
+ const saved = await continuationPlacement(data.brief.id, false);
59
+ if (saved) {
60
+ if (JSON.stringify(saved.caller) !== JSON.stringify(authorization?.caller))
61
+ throw new BridgeError(403, "This peer is not the launch's recorded counterpart.");
62
+ if (saved.hash !== hash)
63
+ throw new BridgeError(409, "This move id already names a different launch.");
64
+ if (saved.result)
65
+ return saved.result;
66
+ throw new BridgeError(409, "This move's launch is uncertain; inspect its existing pane or wait for its arrival. It will not be launched twice.");
67
+ }
68
+ await assertUnusedLaunchId(data.brief.id);
69
+ await atomicInPrivateDir(file, JSON.stringify({ ...metadata, state: "uncertain" }));
70
+ let paneTarget;
71
+ const result = await launch(data, async (pane) => {
72
+ paneTarget = pane;
73
+ await atomicInPrivateDir(file, JSON.stringify({ ...metadata, state: "uncertain", paneTarget }));
74
+ });
75
+ await atomicInPrivateDir(file, JSON.stringify({ ...metadata, state: "placed", paneTarget, result }));
76
+ return result;
77
+ })();
78
+ queues.set(file, work);
79
+ try {
80
+ return await work;
81
+ }
82
+ finally {
83
+ queues.delete(file);
84
+ creating.delete(file);
85
+ }
86
+ }
87
+ /** An owner-admitted source move publishes one canonical intent privately.
88
+ * The receiving Hook pulls it back over its own verified reverse enrollment. */
89
+ const intentFile = (id) => path.join(bridgeRoot(), "move-intents", `${z.string().uuid().parse(id)}.json`);
90
+ export async function saveContinuationIntent(input) {
91
+ const id = z.string().uuid().parse(input.brief.id);
92
+ const previous = await readFile(intentFile(id), "utf8").catch(error => { if (error.code !== "ENOENT")
93
+ throw error; return undefined; });
94
+ const encoded = JSON.stringify(input);
95
+ if (previous && previous !== encoded)
96
+ throw new BridgeError(409, "This move id already has a different launch intent.");
97
+ await atomicInPrivateDir(intentFile(id), encoded);
98
+ }
99
+ export async function continuationIntent(id) {
100
+ try {
101
+ return JSON.parse(await readFile(intentFile(id), "utf8"));
102
+ }
103
+ catch {
104
+ throw new BridgeError(404, "No owner-admitted continuation intent is recorded.");
105
+ }
106
+ }
@@ -30,7 +30,8 @@ export async function runDispatch(args) {
30
30
  return 0;
31
31
  }
32
32
  if (args.length === 1 && args[0] === "returns") {
33
- console.log(JSON.stringify(await hookRequest("/v1/dispatch/returns", {}), null, 2));
33
+ const origin = await terminalPaneFromEnv();
34
+ console.log(JSON.stringify(await hookRequest("/v1/dispatch/returns", { ...(origin ? { origin } : {}) }), null, 2));
34
35
  return 0;
35
36
  }
36
37
  if (args[0] === "usage" && args.slice(1).every(arg => arg === "--json")) {
@@ -194,8 +195,11 @@ export async function runConductor(args) {
194
195
  }
195
196
  if (namespace !== "grants")
196
197
  throw new Error(CONDUCTOR_USAGE);
198
+ const grantOrigin = await terminalPaneFromEnv();
199
+ const grantCall = async (action, data) => grantOrigin ? hookRequest("/v1/conductor/call", { action, data, origin: grantOrigin }) : undefined;
197
200
  if (action === "list") {
198
- console.log(JSON.stringify(await listNamedGrants(), null, 2));
201
+ const forwarded = await grantCall("grants-list", {});
202
+ console.log(JSON.stringify(forwarded?.grants ?? await listNamedGrants(), null, 2));
199
203
  return 0;
200
204
  }
201
205
  if (action === "add") {
@@ -211,7 +215,8 @@ export async function runConductor(args) {
211
215
  ...(values.until ? { until: values.until } : {}),
212
216
  ...(values["max-permission-mode"] ? { maxPermissionMode: values["max-permission-mode"] } : {}),
213
217
  });
214
- console.log(JSON.stringify(await addGrant(grant), null, 2));
218
+ const forwarded = await grantCall("grants-add", grant);
219
+ console.log(JSON.stringify(forwarded?.grant ?? await addGrant(grant), null, 2));
215
220
  return 0;
216
221
  }
217
222
  if (action === "remove") {
@@ -223,7 +228,9 @@ export async function runConductor(args) {
223
228
  throw new Error("Usage: phren conductor grants remove <index>|--scope <scope>");
224
229
  if (index !== undefined && !Number.isInteger(index))
225
230
  throw new Error("Grant index must be an integer.");
226
- console.log(JSON.stringify(await removeGrant(index !== undefined ? { index } : { scope: values.scope }), null, 2));
231
+ const input = index !== undefined ? { index } : { scope: values.scope };
232
+ const forwarded = await grantCall("grants-remove", input);
233
+ console.log(JSON.stringify(forwarded?.grant ?? await removeGrant(input), null, 2));
227
234
  return 0;
228
235
  }
229
236
  throw new Error(CONDUCTOR_USAGE);
@@ -11,6 +11,7 @@ export interface DispatchHost {
11
11
  name: string;
12
12
  server: string;
13
13
  local: boolean;
14
+ fingerprint?: string;
14
15
  /** Every name this computer answers to (local hosts only). */
15
16
  names?: readonly string[];
16
17
  request(route: string, data?: Json, timeout?: number): Promise<Json>;
@@ -18,6 +19,8 @@ export interface DispatchHost {
18
19
  /** This computer's own names: its hostname, the hostname's first label and
19
20
  * its Bonjour name, plus "local". */
20
21
  export declare function isLocalComputer(name: string, names?: readonly string[]): boolean;
22
+ /** Pinned host and SSH account identity; aliases and key comments are local. */
23
+ export declare function peerFingerprint(peer: Pick<HookPeer, "hostKey" | "username">): string;
21
24
  export declare function peerHost(peer: HookPeer, request?: typeof peerRequest): DispatchHost;
22
25
  /** This computer. `server` is the Herdr server its Hook reports first. */
23
26
  export declare function localHost(server?: string, names?: readonly string[], request?: typeof hookRequest): DispatchHost;
@@ -1,3 +1,4 @@
1
+ import { createHash } from "node:crypto";
1
2
  import { hookRequest } from "./client.js";
2
3
  import { localNames } from "./computer-names.js";
3
4
  import { peerRequest } from "./peers.js";
@@ -15,8 +16,12 @@ export function isLocalComputer(name, names = localNames()) {
15
16
  return value === wanted || value.split(".")[0] === first;
16
17
  });
17
18
  }
19
+ /** Pinned host and SSH account identity; aliases and key comments are local. */
20
+ export function peerFingerprint(peer) {
21
+ return createHash("sha256").update(JSON.stringify([peer.hostKey.trim().split(/\s+/).slice(0, 2).join(" "), peer.username])).digest("hex");
22
+ }
18
23
  export function peerHost(peer, request = peerRequest) {
19
- return { name: peer.name, server: peer.server, local: false, request: (route, data, timeout) => request(peer, route, data, timeout) };
24
+ return { name: peer.name, server: peer.server, local: false, fingerprint: peerFingerprint(peer), request: (route, data, timeout) => request(peer, route, data, timeout) };
20
25
  }
21
26
  /** This computer. `server` is the Herdr server its Hook reports first. */
22
27
  export function localHost(server = "default", names = localNames(), request = hookRequest) {
@@ -195,14 +195,26 @@ export declare function workerTurnKey(seen: {
195
195
  reply?: string;
196
196
  }, error?: string): string | undefined;
197
197
  /** Apply one observation to a receipt. Returns true when the receipt changed. */
198
- export declare function observe(receipt: Receipt, value: unknown, now: number): boolean;
198
+ export declare function observe(receipt: Receipt, value: unknown, now: number, peers?: readonly HookPeer[], self?: {
199
+ id: string;
200
+ name: string;
201
+ verifiedHomeMove?: string;
202
+ }): boolean;
199
203
  /** One line for the dispatching agent: who returned, how, and where to read it. */
200
204
  export declare function noticeLine(receipts: readonly Receipt[]): string;
201
205
  /** What `dispatch_returns` lists for one unread return. */
202
206
  export declare function returnRow(receipt: Receipt): Json;
203
207
  export interface DispatchReturnsOptions {
208
+ /** This Hook's stable identity, for a worker moving back home. */
209
+ localComputer?: {
210
+ id: string;
211
+ name: string;
212
+ };
204
213
  peers?: () => Promise<HookPeer[]>;
205
214
  request?: typeof peerRequest;
215
+ forward?: (origin: OriginPane, text: string, deliveryId: string) => Promise<{
216
+ delivered: boolean;
217
+ } | undefined>;
206
218
  /** Worker states on this computer, for dispatches placed here without SSH. */
207
219
  localWorkers?: (input: Json) => Promise<{
208
220
  workers: unknown[];
@@ -224,7 +236,7 @@ export interface DispatchReturnsOptions {
224
236
  localAnswer?: (target: Target, actionId: string, decision: ApprovalDecision) => Promise<unknown>;
225
237
  /** A worker's new forwarded request was recorded. Returns true when this Hook pushed it to its phone. */
226
238
  onApproval?: (receipt: Receipt, approval: NonNullable<Receipt["approval"]>) => boolean | void;
227
- close?: (receipt: Receipt) => Promise<Json>;
239
+ close?: (receipt: Receipt, verifiedPeer?: HookPeer) => Promise<Json>;
228
240
  /** Continues Claude workers stopped by their usage limit on another account, after each poll (account-failover.ts). */
229
241
  failover?: {
230
242
  run: () => Promise<void>;
@@ -236,6 +248,8 @@ export interface DispatchReturnsOptions {
236
248
  export declare function noticeDeliveryId(receipts: readonly Receipt[]): string;
237
249
  /** Dispatching side: follows open dispatches and delivers their returns. */
238
250
  export declare class DispatchReturns {
251
+ private readonly forward?;
252
+ private readonly localComputer?;
239
253
  private readonly peers;
240
254
  private readonly request;
241
255
  private readonly localWorkers;
@@ -257,6 +271,8 @@ export declare class DispatchReturns {
257
271
  private noticesDue;
258
272
  private running?;
259
273
  constructor(options?: DispatchReturnsOptions);
274
+ private isSelf;
275
+ private verifiedMovedPeer;
260
276
  /** Send a decision for a worker's request to the Hook that runs it. */
261
277
  private sendAnswer;
262
278
  /** Answer the permission request a dispatched worker is waiting on. It is
@@ -287,6 +303,8 @@ export declare class DispatchReturns {
287
303
  forwardPrs(): Promise<void>;
288
304
  cleanup(): Promise<void>;
289
305
  private closeRemote;
306
+ /** A remote successor acknowledges only the exact return version it received. */
307
+ acknowledge(rows: Json[]): Promise<void>;
290
308
  /** Every unread return, oldest first, marked read as it is handed over. */
291
- take(): Promise<Json[]>;
309
+ take(consume?: boolean): Promise<Json[]>;
292
310
  }