@phren/cli 0.3.53 → 0.3.55

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 (55) 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/git.js +82 -8
  21. package/dist/bridge/hand-off-queue.d.ts +3 -0
  22. package/dist/bridge/hand-off-queue.js +8 -0
  23. package/dist/bridge/hand-off.d.ts +13 -0
  24. package/dist/bridge/hand-off.js +20 -1
  25. package/dist/bridge/install.js +0 -6
  26. package/dist/bridge/launch-brief.d.ts +2 -0
  27. package/dist/bridge/launch-brief.js +19 -8
  28. package/dist/bridge/move-computers.d.ts +47 -0
  29. package/dist/bridge/move-computers.js +118 -0
  30. package/dist/bridge/peer-handoff.d.ts +5 -0
  31. package/dist/bridge/peer-handoff.js +52 -0
  32. package/dist/bridge/projects.js +13 -8
  33. package/dist/bridge/request-origin.d.ts +6 -0
  34. package/dist/bridge/request-origin.js +20 -0
  35. package/dist/bridge/scoped-gateway.d.ts +2 -1
  36. package/dist/bridge/scoped-gateway.js +16 -3
  37. package/dist/bridge/server-launch.d.ts +2 -0
  38. package/dist/bridge/server-launch.js +2 -0
  39. package/dist/bridge/server-routes.d.ts +6 -0
  40. package/dist/bridge/server-routes.js +228 -15
  41. package/dist/bridge/server.js +46 -24
  42. package/dist/bridge/session-move.d.ts +28 -1
  43. package/dist/bridge/session-move.js +266 -25
  44. package/dist/bridge/socket-budget.d.ts +29 -0
  45. package/dist/bridge/socket-budget.js +62 -0
  46. package/dist/bridge/terminal-herdr.js +14 -0
  47. package/dist/bridge/terminal-tmux.js +1 -0
  48. package/dist/bridge/terminal.d.ts +2 -0
  49. package/dist/bridge/terminal.js +6 -0
  50. package/dist/bridge/worker-relocation.d.ts +5 -0
  51. package/dist/bridge/worker-relocation.js +33 -0
  52. package/dist/bridge-hook.mjs +16480 -14296
  53. package/dist/modules/registry.js +8 -8
  54. package/dist/tools/dispatch.js +2 -1
  55. package/package.json +1 -1
@@ -1,3 +1,4 @@
1
+ import type { ConductorSuccessionService } from "./conductor-succession.js";
1
2
  import { z } from "zod";
2
3
  import { moveToSchema } from "./dispatch.js";
3
4
  import { type HarnessInventory } from "./harnesses.js";
@@ -21,6 +22,7 @@ export declare const moveRequestSchema: z.ZodObject<{
21
22
  session: z.ZodUnion<readonly [z.ZodString, z.ZodString]>;
22
23
  }, z.core.$strip>;
23
24
  to: z.ZodObject<{
25
+ computer: z.ZodOptional<z.ZodString>;
24
26
  harness: z.ZodEnum<{
25
27
  claude: "claude";
26
28
  codex: "codex";
@@ -54,6 +56,7 @@ declare const moveRecordSchema: z.ZodObject<{
54
56
  launching: "launching";
55
57
  linking: "linking";
56
58
  moved: "moved";
59
+ uncertain: "uncertain";
57
60
  }>;
58
61
  createdAt: z.ZodString;
59
62
  updatedAt: z.ZodString;
@@ -76,6 +79,7 @@ declare const moveRecordSchema: z.ZodObject<{
76
79
  label: z.ZodOptional<z.ZodString>;
77
80
  }, z.core.$strict>;
78
81
  to: z.ZodObject<{
82
+ computer: z.ZodOptional<z.ZodString>;
79
83
  harness: z.ZodEnum<{
80
84
  claude: "claude";
81
85
  codex: "codex";
@@ -93,12 +97,17 @@ declare const moveRecordSchema: z.ZodObject<{
93
97
  xhigh: "xhigh";
94
98
  }>>;
95
99
  }, z.core.$strict>;
100
+ computerFingerprint: z.ZodOptional<z.ZodString>;
101
+ computerId: z.ZodOptional<z.ZodString>;
102
+ accountChoice: z.ZodOptional<z.ZodString>;
103
+ project: z.ZodOptional<z.ZodString>;
96
104
  mode: z.ZodOptional<z.ZodEnum<{
97
105
  "new-chat": "new-chat";
98
106
  replace: "replace";
99
107
  }>>;
100
108
  modeForced: z.ZodOptional<z.ZodLiteral<"conductor">>;
101
109
  handedOffTo: z.ZodOptional<z.ZodObject<{
110
+ computer: z.ZodOptional<z.ZodString>;
102
111
  target: z.ZodUnion<readonly [z.ZodObject<{
103
112
  server: z.ZodString;
104
113
  workspace: z.ZodString;
@@ -147,6 +156,7 @@ declare const moveRecordSchema: z.ZodObject<{
147
156
  }, z.core.$strict>>;
148
157
  cwd: z.ZodString;
149
158
  dispatch: z.ZodOptional<z.ZodString>;
159
+ workerDispatch: z.ZodOptional<z.ZodString>;
150
160
  handoff: z.ZodOptional<z.ZodObject<{
151
161
  path: z.ZodString;
152
162
  source: z.ZodEnum<{
@@ -163,6 +173,7 @@ declare const moveRecordSchema: z.ZodObject<{
163
173
  }>>;
164
174
  placement: z.ZodOptional<z.ZodEnum<{
165
175
  "adjacent-pane": "adjacent-pane";
176
+ peer: "peer";
166
177
  "same-pane": "same-pane";
167
178
  }>>;
168
179
  target: z.ZodOptional<z.ZodUnion<readonly [z.ZodObject<{
@@ -210,6 +221,10 @@ declare const moveRecordSchema: z.ZodObject<{
210
221
  notice: z.ZodOptional<z.ZodString>;
211
222
  movedAt: z.ZodOptional<z.ZodString>;
212
223
  error: z.ZodOptional<z.ZodString>;
224
+ recovery: z.ZodOptional<z.ZodObject<{
225
+ attempts: z.ZodNumber;
226
+ nextAt: z.ZodString;
227
+ }, z.core.$strict>>;
213
228
  }, z.core.$strict>;
214
229
  export type MoveRecord = z.infer<typeof moveRecordSchema>;
215
230
  /** What a dispatching Hook records on its receipt when its worker moved. */
@@ -217,6 +232,8 @@ export interface MovedWorker {
217
232
  id: string;
218
233
  at: string;
219
234
  handoff?: string;
235
+ computerFingerprint?: string;
236
+ computerId?: string;
220
237
  from: {
221
238
  harness: Provider;
222
239
  account?: string;
@@ -279,7 +296,7 @@ export declare function readGitState(directory: string): Promise<GitState | unde
279
296
  /** The commands of every process below `pids` (the agent's own children), not the agent itself. */
280
297
  export declare function processesBelow(pids: readonly number[]): Promise<string[]>;
281
298
  /** What Phren itself saw at the move, appended to every hand-off. */
282
- export declare function observedState(git: GitState | undefined, processes: readonly string[]): string;
299
+ export declare function observedState(git: GitState | undefined, processes: readonly string[], processCommands?: boolean): string;
283
300
  /** A hand-off built without the agent: the conversation's tail, the original brief and the git state. */
284
301
  export declare function fallbackHandoff(input: {
285
302
  reason: string;
@@ -294,6 +311,7 @@ export declare function handoffDocument(record: MoveRecord, body: string, observ
294
311
  /** The new agent's first prompt: the whole hand-off when it fits the brief, else where to read it. */
295
312
  export declare function continuePrompt(document: string, file: string): string;
296
313
  export interface MoverDeps {
314
+ succession?: ConductorSuccessionService;
297
315
  snapshot: (server: string) => Promise<Json>;
298
316
  /** The conversation the pane runs now. */
299
317
  identity: (server: string, pane: Json) => Promise<string | undefined>;
@@ -337,6 +355,8 @@ export interface MoverDeps {
337
355
  * request that started it (the Hook answers in seconds); its record says where it is. */
338
356
  export declare class SessionMover {
339
357
  private readonly deps;
358
+ private readonly cancelled;
359
+ private readonly admissions;
340
360
  private readonly running;
341
361
  constructor(deps: MoverDeps);
342
362
  private get now();
@@ -346,10 +366,17 @@ export declare class SessionMover {
346
366
  start(input: unknown, caller?: {
347
367
  owner?: boolean;
348
368
  }): Promise<MoveRecord>;
369
+ private admit;
349
370
  /** For tests: the move under way in a pane, until it settles. */
350
371
  settled(server: string, pane: string): Promise<void> | undefined;
351
372
  private update;
352
373
  private run;
374
+ abort(id: string): Promise<MoveRecord>;
375
+ private assertNotAborted;
376
+ private continueOnPeer;
377
+ /** Startup and tick recovery reuse the receiving Hook's durable move id.
378
+ * No fresh id, brief or pane is created after an uncertain launch. */
379
+ reconcile(): Promise<void>;
353
380
  /** An ordinary move never acquires permission to stop a conductor merely
354
381
  * because the owner promoted its source while the hand-off was running. */
355
382
  private checkPromotion;
@@ -1,3 +1,5 @@
1
+ import { saveContinuationIntent } from "./continuation-launch.js";
2
+ import { redactPeerHandoff } from "./peer-handoff.js";
1
3
  // Moving a live session to another agent: the agent in the pane writes a
2
4
  // hand-off, exits the way it normally does, and the target harness starts in
3
5
  // the same pane by default, or a new chat that keeps the old agent running.
@@ -15,9 +17,12 @@
15
17
  // `<bridge>/moves/<id>.json`; a dispatching Hook asking about the old pane
16
18
  // (dispatch-returns.ts `workerStates`) follows the record to the new agent,
17
19
  // so the dispatch and its receipt carry on as one worker.
20
+ import { redactSecretsForLog } from "../content/secrets.js";
21
+ import { redactApproval } from "./approval-summary.js";
22
+ import { stableComputerName } from "./computer-names.js";
18
23
  import { execFile } from "node:child_process";
19
24
  import { randomUUID } from "node:crypto";
20
- import { lstat, mkdir, open, readFile, readdir, rm } from "node:fs/promises";
25
+ import { lstat, mkdir, open, readFile, readdir, realpath, rm } from "node:fs/promises";
21
26
  import path from "node:path";
22
27
  import { promisify } from "node:util";
23
28
  import { z } from "zod";
@@ -25,11 +30,11 @@ import { logger } from "../logger.js";
25
30
  import { quoted, withOriginalBrief } from "./account-failover.js";
26
31
  import { recordedConductor, runsAgent, transferConductor } from "./conductor-role.js";
27
32
  import { DEFAULT_ACCOUNT } from "./claude-accounts.js";
28
- import { DISPATCH_HARNESSES, moveToSchema, repointDispatchOrigins } from "./dispatch.js";
33
+ import { DISPATCH_HARNESSES, DispatchService, dispatchProjectDirectory, projectName, moveToSchema, repointDispatchOrigins } from "./dispatch.js";
29
34
  import { hasUsable } from "./harnesses.js";
30
35
  import { findPane } from "./herdr.js";
31
- import { briefArrival, briefId, briefRoot, writeLaunchBrief } from "./launch-brief.js";
32
- import { atomic, BridgeError, bridgeRoot, startingTargetSchema, targetSchema } from "./protocol.js";
36
+ import { briefArrival, briefId, briefRoot, assertUnusedLaunchId, writeLaunchBrief } from "./launch-brief.js";
37
+ import { atomic, BridgeError, bridgeRoot, object, startingTargetSchema, targetSchema } from "./protocol.js";
33
38
  import { publicAssistant } from "./schedule-watch.js";
34
39
  const run = promisify(execFile);
35
40
  export { moveToSchema };
@@ -42,7 +47,7 @@ export const moveRequestSchema = z.object({
42
47
  /** How long the agent gets to write its hand-off before Phren builds one. */
43
48
  handoffTimeoutMs: z.number().int().min(5_000).max(900_000).optional(),
44
49
  }).strict();
45
- const MOVE_STATES = ["handing-off", "exiting", "launching", "linking", "moved", "failed"];
50
+ const MOVE_STATES = ["handing-off", "exiting", "launching", "linking", "uncertain", "moved", "failed"];
46
51
  const timestamp = z.string().datetime();
47
52
  const moveRecordSchema = z.object({
48
53
  id: z.string().uuid(),
@@ -50,23 +55,29 @@ const moveRecordSchema = z.object({
50
55
  createdAt: timestamp, updatedAt: timestamp,
51
56
  from: z.object({ target: targetSchema, account: z.string().max(64).optional(), label: z.string().max(200).optional() }).strict(),
52
57
  to: moveToSchema,
58
+ computerFingerprint: z.string().regex(/^[a-f0-9]{64}$/).optional(),
59
+ computerId: z.string().uuid().optional(),
60
+ accountChoice: z.string().max(400).optional(),
61
+ project: projectName.optional(),
53
62
  mode: z.enum(["replace", "new-chat"]).optional(),
54
63
  modeForced: z.literal("conductor").optional(),
55
- handedOffTo: z.object({ target: z.union([targetSchema, startingTargetSchema]) }).strict().optional(),
64
+ handedOffTo: z.object({ computer: z.string().optional(), target: z.union([targetSchema, startingTargetSchema]) }).strict().optional(),
56
65
  handedOffFrom: z.object({ target: targetSchema, title: z.string().max(200) }).strict().optional(),
57
66
  cwd: z.string().max(4096),
58
67
  /** The dispatch the moved worker was launched for, as its turn record names it. */
59
68
  dispatch: briefId.optional(),
69
+ workerDispatch: briefId.optional(),
60
70
  handoff: z.object({ path: z.string().max(4096), source: z.enum(["agent", "fallback"]), reason: z.string().max(300).optional(), chars: z.number().int().nonnegative() }).strict().optional(),
61
71
  /** How the old agent ended: its own exit command, an interrupt, or a kill after it hung. */
62
72
  exit: z.enum(["clean", "interrupted", "killed"]).optional(),
63
- placement: z.enum(["same-pane", "adjacent-pane"]).optional(),
73
+ placement: z.enum(["same-pane", "adjacent-pane", "peer"]).optional(),
64
74
  target: z.union([targetSchema, startingTargetSchema]).optional(),
65
75
  paneTarget: targetSchema.omit({ session: true }).optional(),
66
76
  linkPending: z.boolean().optional(),
67
77
  notice: z.string().max(500).optional(),
68
78
  movedAt: timestamp.optional(),
69
79
  error: z.string().max(500).optional(),
80
+ recovery: z.object({ attempts: z.number().int().positive(), nextAt: timestamp }).strict().optional(),
70
81
  }).strict();
71
82
  /** The slash command each harness ends its interactive session with. */
72
83
  const EXIT_COMMANDS = { claude: "/exit", codex: "/quit", copilot: "/exit", opencode: "/exit", phren: "/exit" };
@@ -132,7 +143,7 @@ export function moveSessionFields(records, target, title) {
132
143
  && other.tab === target.tab && other.pane === target.pane && other.source === target.source
133
144
  && "session" in other && other.session === target.session;
134
145
  const outgoing = records.find(record => record.state === "moved" && record.mode === "new-chat" && matches(record.from.target));
135
- const incoming = records.find(record => record.state === "moved" && record.mode === "new-chat" && record.target && matches(record.target));
146
+ const incoming = records.find(record => record.state === "moved" && record.mode === "new-chat" && !record.to.computer && record.target && matches(record.target));
136
147
  const suffix = outgoing ? ` (handed off to ${outgoing.to.harness})` : "";
137
148
  return { ...(outgoing?.handedOffTo ? { handedOffTo: outgoing.handedOffTo,
138
149
  title: `${(title ?? outgoing.from.label ?? outgoing.from.target.source).replace(/ \(handed off to [^)]+\)$/, "")}${suffix}` } : {}),
@@ -143,6 +154,8 @@ export function movedWorker(record) {
143
154
  if (record.state !== "moved" || !record.target)
144
155
  return undefined;
145
156
  return { id: record.id, at: record.movedAt ?? record.updatedAt, ...(record.handoff ? { handoff: record.handoff.path } : {}),
157
+ ...(record.computerFingerprint ? { computerFingerprint: record.computerFingerprint } : {}),
158
+ ...(record.computerId ? { computerId: record.computerId } : {}),
146
159
  from: { harness: record.from.target.source, ...(record.from.account ? { account: record.from.account } : {}) }, to: record.to, target: record.target };
147
160
  }
148
161
  /** A harness as people name it, with its account and model: "Claude (work, opus)". */
@@ -303,7 +316,7 @@ export async function processesBelow(pids) {
303
316
  return found;
304
317
  }
305
318
  /** What Phren itself saw at the move, appended to every hand-off. */
306
- export function observedState(git, processes) {
319
+ export function observedState(git, processes, processCommands = true) {
307
320
  const lines = ["## Checked by Phren at the move", ""];
308
321
  if (!git)
309
322
  lines.push("- Not a git checkout, or git could not be read.");
@@ -316,7 +329,9 @@ export function observedState(git, processes) {
316
329
  lines.push(`- Uncommitted changes (${git.changes.length}). The move committed, stashed and reset nothing: they are the previous agent's work in progress, so keep them.`, "", "```", ...git.changes, "```");
317
330
  }
318
331
  lines.push("");
319
- if (processes.length)
332
+ if (!processCommands)
333
+ lines.push(`- The previous agent had ${processes.length} child processes running; process command lines are withheld on cross-computer moves.`);
334
+ else if (processes.length)
320
335
  lines.push(`- Processes the previous agent had running (${processes.length}):`, "", "```", ...processes, "```");
321
336
  else
322
337
  lines.push("- The previous agent had no child processes running.");
@@ -377,6 +392,8 @@ const DEFAULT_HANDOFF_MS = 240_000;
377
392
  * request that started it (the Hook answers in seconds); its record says where it is. */
378
393
  export class SessionMover {
379
394
  deps;
395
+ cancelled = new Set();
396
+ admissions = new Set();
380
397
  running = new Map();
381
398
  constructor(deps) {
382
399
  this.deps = deps;
@@ -387,10 +404,29 @@ export class SessionMover {
387
404
  /** Checks the move can happen, records it and starts it. Refuses before anything is typed. */
388
405
  async start(input, caller = {}) {
389
406
  const data = moveRequestSchema.parse(input);
407
+ if (data.to.computer && !caller.owner)
408
+ throw new BridgeError(403, "Only the owner can continue a chat on another computer.");
409
+ const key = `${data.target.server}\0${data.target.pane}`;
410
+ if (this.admissions.has(key))
411
+ throw new BridgeError(409, "This session is already being moved.");
412
+ this.admissions.add(key);
413
+ let release;
414
+ try {
415
+ return await this.admit(data, caller, () => { release = this.deps.succession?.reserveCaller(data.target); });
416
+ }
417
+ finally {
418
+ release?.();
419
+ this.admissions.delete(key);
420
+ }
421
+ }
422
+ async admit(input, caller, reserve) {
423
+ const data = moveRequestSchema.parse(input);
424
+ if (data.to.computer && !caller.owner)
425
+ throw new BridgeError(403, "Only the owner can continue a chat on another computer.");
390
426
  if (data.id) {
391
427
  const earlier = await readMove(data.id);
392
428
  if (earlier) {
393
- if (earlier.modeForced === "conductor" && !caller.owner)
429
+ if ((earlier.modeForced === "conductor" || earlier.to.computer) && !caller.owner)
394
430
  throw new BridgeError(403, "Only the owner can move the conductor.");
395
431
  const from = earlier.from.target;
396
432
  if (from.server !== data.target.server || from.pane !== data.target.pane || from.session !== data.target.session)
@@ -398,7 +434,11 @@ export class SessionMover {
398
434
  return earlier;
399
435
  }
400
436
  }
401
- const { target, to } = data;
437
+ const { target } = data;
438
+ const peer = data.to.computer ? await (await import("./move-computers.js")).movePeer(data.to.computer, stableComputerName()) : undefined;
439
+ const to = { ...data.to };
440
+ if (!peer)
441
+ delete to.computer;
402
442
  const active = (await listMoves(this.now)).find(record => record.from.target.server === target.server && record.from.target.pane === target.pane
403
443
  && record.state !== "moved" && record.state !== "failed");
404
444
  if (active || [...this.running.keys()].some(key => key === `${target.server}\0${target.pane}`))
@@ -415,18 +455,21 @@ export class SessionMover {
415
455
  const holdsRole = await this.deps.isConductor?.(target.server, pane) ?? false;
416
456
  if (holdsRole && !caller.owner)
417
457
  throw new BridgeError(403, "Only the owner can move the conductor.");
458
+ reserve();
418
459
  const conductor = holdsRole ? await recordedConductor() : undefined;
419
460
  if (holdsRole && (!conductor || conductor.server !== target.server || conductor.pane !== target.pane)) {
420
461
  throw new BridgeError(409, "The conductor changed during the move; nothing was transferred.");
421
462
  }
463
+ if (conductor && peer && !this.deps.succession)
464
+ throw new BridgeError(409, "Update this Hook to move the conductor to another computer.");
422
465
  if (conductor && to.harness === "copilot")
423
466
  throw new BridgeError(400, "Copilot cannot run as a conductor.");
424
467
  const account = target.source === "claude" ? this.deps.paneAccount?.(target.server, pane) ?? DEFAULT_ACCOUNT : undefined;
425
468
  const sameHarness = to.harness === target.source && (to.harness !== "claude" || (to.account ?? account) === account);
426
- if (sameHarness && !to.model && !to.effort)
469
+ if (!peer && sameHarness && !to.model && !to.effort)
427
470
  throw new BridgeError(400, "The session already runs there. Choose another harness, account, model or effort.");
428
471
  // Only harnesses signed in and usable here; an inventory that cannot be read lets the move go on, as a launch does.
429
- const inventory = await this.deps.inventory().catch(() => undefined);
472
+ const inventory = peer ? undefined : await this.deps.inventory().catch(() => undefined);
430
473
  if (inventory) {
431
474
  const availability = hasUsable(inventory, to.harness, to.harness === "claude" ? to.account : undefined);
432
475
  if (!availability.ok) {
@@ -437,15 +480,52 @@ export class SessionMover {
437
480
  const cwd = String(pane.foreground_cwd || pane.cwd || "");
438
481
  if (!path.isAbsolute(cwd))
439
482
  throw new BridgeError(409, "The pane's folder is unknown, so the new agent could not start there.");
483
+ let project;
484
+ let accountChoice;
485
+ let computerId;
486
+ if (peer) {
487
+ const { getProjectDirs } = await import("../phren-paths.js");
488
+ const { phrenStoreRoot } = await import("./transcripts.js");
489
+ const { checkMovePeer } = await import("./move-computers.js");
490
+ // Match the registered checkout, including sessions in its subfolders.
491
+ const sourceDirectory = await realpath(cwd).catch(() => cwd);
492
+ let longest = 0;
493
+ for (const directoryName of getProjectDirs(phrenStoreRoot())) {
494
+ const name = path.basename(directoryName);
495
+ const directory = await dispatchProjectDirectory(name).catch(() => undefined);
496
+ if (directory && directory.length > longest && (sourceDirectory === directory || sourceDirectory.startsWith(directory + path.sep))) {
497
+ project = name;
498
+ longest = directory.length;
499
+ }
500
+ }
501
+ if (!project && conductor)
502
+ project = "phren-conductor";
503
+ if (!project)
504
+ throw new BridgeError(409, "The source folder is not a registered project checkout.");
505
+ projectName.parse(project);
506
+ const selected = await checkMovePeer(peer, project, to, !!conductor);
507
+ computerId = selected.computerId;
508
+ if (selected.account) {
509
+ to.account = selected.account;
510
+ accountChoice = selected.accountChoice;
511
+ }
512
+ }
440
513
  const dispatch = await this.deps.paneDispatch?.(target.server, pane).catch(() => undefined);
514
+ const workerDispatch = peer && dispatch ? await (await import("./worker-relocation.js")).preflightWorkerRelocation(dispatch, target) : undefined;
441
515
  const label = [pane.label, pane.title, pane.terminal_title_stripped, pane.agent_name].find(value => typeof value === "string" && value.trim() && !/^\d+$/.test(value));
442
516
  const at = new Date(this.now).toISOString();
443
517
  const record = { id: data.id ?? randomUUID(), state: "handing-off", createdAt: at, updatedAt: at,
444
- mode: conductor ? "new-chat" : data.mode, ...(conductor ? { modeForced: "conductor" } : {}), from: { target, ...(account ? { account } : {}), ...(label ? { label: label.slice(0, 200) } : {}) }, to, cwd,
445
- ...(dispatch && briefId.safeParse(dispatch).success ? { dispatch } : {}) };
518
+ ...(project ? { project } : {}), mode: conductor || peer ? "new-chat" : data.mode, ...(conductor ? { modeForced: "conductor" } : {}), from: { target, ...(account ? { account } : {}), ...(label ? { label: label.slice(0, 200) } : {}) }, to, cwd, ...(computerId ? { computerId } : {}), ...(peer?.fingerprint ? { computerFingerprint: peer.fingerprint } : {}), ...(accountChoice ? { accountChoice } : {}),
519
+ ...(dispatch && briefId.safeParse(dispatch).success ? { dispatch } : {}), ...(workerDispatch ? { workerDispatch } : {}) };
520
+ await assertUnusedLaunchId(record.id);
521
+ if (conductor && peer) {
522
+ if (!computerId)
523
+ throw new BridgeError(409, "The destination did not report its verified Hook identity.");
524
+ await this.deps.succession.begin(record.id, conductor, target, peer, computerId, record);
525
+ }
446
526
  await saveMove(record);
447
527
  const key = `${target.server}\0${target.pane}`;
448
- const work = this.run(record, data.handoffTimeoutMs ?? DEFAULT_HANDOFF_MS, conductor).finally(() => this.running.delete(key));
528
+ const work = this.run(record, data.handoffTimeoutMs ?? DEFAULT_HANDOFF_MS, conductor, peer, project).finally(() => this.running.delete(key));
449
529
  this.running.set(key, work);
450
530
  return record;
451
531
  }
@@ -455,7 +535,7 @@ export class SessionMover {
455
535
  Object.assign(record, change, { updatedAt: new Date(this.now).toISOString() });
456
536
  await saveMove(record);
457
537
  }
458
- async run(record, handoffMs, conductor) {
538
+ async run(record, handoffMs, conductor, peer, project) {
459
539
  const from = record.from.target;
460
540
  let roleTransferred = false;
461
541
  try {
@@ -469,7 +549,8 @@ export class SessionMover {
469
549
  const body = "text" in written ? written.text : record.mode === "new-chat"
470
550
  ? `## Goal and current state\n\n${fallback}\n\n## Next steps\n\nContinue the owner's goal above after checking the checkout and the latest agent reply.\n\n## Key files\n\nOpen or changed files are named in the conversation above and the checked Git state below; open editor tabs are not available to the Hook.`
471
551
  : fallback;
472
- const document = handoffDocument(record, body, observedState(git, processes), new Date(this.now).toISOString(), !!conductor);
552
+ const document = handoffDocument(record, body, observedState(git, processes, !peer), new Date(this.now).toISOString(), !!conductor);
553
+ await this.assertNotAborted(record);
473
554
  const file = handoffPath(record.id);
474
555
  const prompt = briefText(continuePrompt(document, file));
475
556
  // The folder is the new agent's brief folder; the hand-off is written into it, whole.
@@ -483,9 +564,24 @@ export class SessionMover {
483
564
  await this.update(record, { state: "launching", exit });
484
565
  await this.deps.afterExit?.(from.server, from.pane).catch(() => undefined);
485
566
  }
486
- const launched = await this.relaunch(record, prompt);
567
+ let launched;
568
+ if (peer) {
569
+ peer = await (await import("./move-computers.js")).currentMovePeer(peer);
570
+ const target = await this.continueOnPeer(record, peer, project, document);
571
+ launched = { target, to: record.to, placement: "peer" };
572
+ }
573
+ else
574
+ launched = await this.relaunch(record, prompt);
487
575
  await this.checkPromotion(record);
488
- if (conductor) {
576
+ if (conductor && peer) {
577
+ if (!launched.target || !("session" in launched.target))
578
+ throw new BridgeError(409, "The prepared successor conversation was not confirmed.");
579
+ await this.deps.succession.prepared(record.id, launched.target);
580
+ await this.deps.succession.commit(record.id);
581
+ roleTransferred = true;
582
+ await this.deps.succession.finish(record.id);
583
+ }
584
+ else if (conductor) {
489
585
  try {
490
586
  if (launched.linkPending || !launched.target || !("session" in launched.target))
491
587
  throw new Error("The new conductor conversation is not linked; the hand-over was not confirmed.");
@@ -524,7 +620,7 @@ export class SessionMover {
524
620
  }
525
621
  await this.update(record, { state: "moved", movedAt: new Date(this.now).toISOString(), ...launched,
526
622
  ...(record.mode === "new-chat" ? {
527
- ...(launched.target ? { handedOffTo: { target: launched.target } } : {}),
623
+ ...(launched.target ? { handedOffTo: { ...(peer ? { computer: peer.name } : {}), target: launched.target } } : {}),
528
624
  handedOffFrom: { target: from, title: record.from.label ?? from.source },
529
625
  } : {}) });
530
626
  logger.info("move", `Moved ${from.source} in pane ${from.pane} to ${harnessName(record.to)} (${launched.placement}); hand-off ${record.handoff?.source}.`);
@@ -534,7 +630,7 @@ export class SessionMover {
534
630
  if (roleTransferred) {
535
631
  // update() has already populated the complete moved record. The role
536
632
  // and worker routes committed; a later status save cannot undo them.
537
- record.state = "moved";
633
+ record.state = peer ? "uncertain" : "moved";
538
634
  record.notice = `Conductor moved with worker routing, but saving move status failed: ${message}`.slice(0, 500);
539
635
  delete record.error;
540
636
  landedMoves.set(recordFile(record.id), record);
@@ -544,16 +640,161 @@ export class SessionMover {
544
640
  logger.warn("move", record.notice);
545
641
  return;
546
642
  }
547
- if (conductor && record.paneTarget) {
643
+ if (conductor && peer) {
644
+ await this.deps.succession.abort(record.id).catch(() => undefined);
645
+ const status = await this.deps.succession.status(record.id).catch(() => undefined);
646
+ if (status?.phase === "committed") {
647
+ await this.update(record, { state: "uncertain", error: "The ownership commit is being reconciled; the previous generation remains fenced." }).catch(() => undefined);
648
+ return;
649
+ }
650
+ }
651
+ if (conductor && record.paneTarget && !peer) {
548
652
  record.notice = await this.conductorNotice(record, "The conductor hand-over failed; you are not the conductor. The previous conductor keeps coordinating.", "failed")
549
653
  ?? "The new chat was told the conductor hand-over failed; it is not the conductor.";
550
654
  }
551
655
  const stopped = record.exit !== undefined;
552
656
  const hint = stopped && record.handoff ? ` The old agent has exited; start ${HARNESS_NAMES[record.to.harness]} in the pane with the hand-off at ${record.handoff.path}.` : "";
553
- await this.update(record, { state: "failed", error: `${message}${hint}`.slice(0, 500) }).catch(() => undefined);
657
+ await this.update(record, { state: record.state === "uncertain" ? "uncertain" : "failed", error: `${message}${hint}`.slice(0, 500) }).catch(() => undefined);
554
658
  logger.warn("move", `Moving pane ${from.pane} to ${record.to.harness} failed: ${message}`);
555
659
  }
556
660
  }
661
+ async abort(id) {
662
+ const record = await readMove(id);
663
+ if (!record)
664
+ throw new BridgeError(404, "No move with that id is recorded.");
665
+ if (record.state === "moved")
666
+ throw new BridgeError(409, "This move is already committed; it cannot be aborted.");
667
+ if (record.modeForced === "conductor" && record.to.computer) {
668
+ await this.deps.succession.abort(id);
669
+ if ((await this.deps.succession.status(id)).phase === "committed")
670
+ throw new BridgeError(409, "This ownership generation is committed; reconcile it instead of rolling back.");
671
+ }
672
+ else if (record.state !== "handing-off" && record.state !== "failed")
673
+ throw new BridgeError(409, "This launch may already exist; reconcile it before aborting.");
674
+ this.cancelled.add(id);
675
+ await this.update(record, { state: "failed", error: "The owner aborted this uncommitted move; the original chat keeps its role." });
676
+ return record;
677
+ }
678
+ async assertNotAborted(record) {
679
+ if (this.cancelled.has(record.id) || (await readMove(record.id))?.state === "failed" || record.modeForced === "conductor" && record.to.computer && (await this.deps.succession.status(record.id)).phase === "aborted")
680
+ throw new BridgeError(409, "This uncommitted move was aborted; no conductor role was transferred.");
681
+ }
682
+ async continueOnPeer(record, peer, project, document) {
683
+ // Full inline text only: the peer cannot read this Hook's brief path.
684
+ // Preserve commit ids and the complete hand-off, redacting credentials
685
+ // in place instead of applying the lossy approval/log summarizer to it.
686
+ const safeDocument = document.replaceAll(record.cwd, "<source checkout>");
687
+ const remotePrompt = redactPeerHandoff(briefText(`Continue the owner's work from this hand-off. This is a different checkout: local uncommitted files and running processes were not copied. Check its branch and files before proceeding.\n\n${safeDocument}`));
688
+ if (remotePrompt.length > PROMPT_LIMIT)
689
+ throw new BridgeError(409, "The hand-off is too long to send in full to another computer; the old chat remains open.");
690
+ const checked = await (await import("./move-computers.js")).checkMovePeer(peer, project, record.to, record.modeForced === "conductor");
691
+ if (record.computerId && checked.computerId !== record.computerId)
692
+ throw new BridgeError(409, "The destination Hook identity changed during the move; nothing was launched.");
693
+ await this.checkPromotion(record);
694
+ await this.assertNotAborted(record);
695
+ await this.update(record, { state: "uncertain", placement: "peer" });
696
+ const label = redactSecretsForLog(redactPeerHandoff(redactApproval(briefText(record.from.label ?? "Continued chat"))));
697
+ const { computer: _destination, ...destination } = record.to;
698
+ await saveContinuationIntent({ computerId: record.computerId, project, to: destination, label, brief: { id: record.id, text: remotePrompt }, worker: !!record.dispatch, ...(record.workerDispatch ? { workerDispatch: record.workerDispatch } : {}) });
699
+ if (record.modeForced === "conductor") {
700
+ const { computer: _computer, ...to } = record.to;
701
+ await this.deps.succession.saveLaunch(record.id, { computerId: record.computerId, project, to, label, brief: { id: record.id, text: remotePrompt }, worker: !!record.dispatch, ...(record.workerDispatch ? { workerDispatch: record.workerDispatch } : {}) });
702
+ }
703
+ const target = await new DispatchService().continueChat(peer, project, record.to, { id: record.id, text: remotePrompt }, label, async (target) => {
704
+ const parsed = targetSchema.safeParse(target);
705
+ const pane = targetSchema.omit({ session: true }).safeParse(object(target).paneTarget);
706
+ if (pane.success)
707
+ await this.update(record, { state: "uncertain", paneTarget: pane.data, placement: "peer" });
708
+ if (parsed.success) {
709
+ await this.update(record, { state: "uncertain", target: parsed.data, placement: "peer" });
710
+ if (record.modeForced === "conductor")
711
+ await this.deps.succession.prepared(record.id, parsed.data);
712
+ }
713
+ }, record.computerId, !!record.dispatch, record.workerDispatch);
714
+ return target;
715
+ }
716
+ /** Startup and tick recovery reuse the receiving Hook's durable move id.
717
+ * No fresh id, brief or pane is created after an uncertain launch. */
718
+ async reconcile() {
719
+ const transaction = (await (await import("./conductor-role.js")).readRoleState())?.succession;
720
+ if (transaction?.side === "origin" && ["preparing", "prepared"].includes(transaction.phase) && transaction.resume && !await readMove(transaction.id))
721
+ await saveMove(moveRecordSchema.parse(transaction.resume));
722
+ for (const record of await listMoves(this.now)) {
723
+ if (["moved", "failed"].includes(record.state) || !record.to.computer || !record.project)
724
+ continue;
725
+ if (record.recovery && Date.parse(record.recovery.nextAt) > this.now)
726
+ continue;
727
+ const key = `${record.from.target.server}\0${record.from.target.pane}`;
728
+ if (this.running.has(key) || this.admissions.has(key))
729
+ continue;
730
+ const work = (async () => {
731
+ try {
732
+ const { movePeer, currentMovePeer } = await import("./move-computers.js");
733
+ const enrolled = await movePeer(record.to.computer);
734
+ if (!enrolled || enrolled.fingerprint !== record.computerFingerprint)
735
+ throw new BridgeError(409, "The destination enrollment changed; reconciliation is paused.");
736
+ const peer = await currentMovePeer(enrolled);
737
+ if (record.modeForced === "conductor" && transaction?.id === record.id && transaction.phase === "aborted") {
738
+ await this.update(record, { state: "failed", error: transaction.revoked ? "The owner stopped the delegated conductor; no previous chat regained the role." : "The hand-over was aborted; the previous conductor keeps the role." });
739
+ return;
740
+ }
741
+ if (this.now - Date.parse(record.createdAt) >= 10 * 60_000) {
742
+ const placement = await peer.request(`/v1/sessions/move/launch?id=${record.id}`, undefined, 5_000);
743
+ if (placement.state === "not-placed") {
744
+ if (record.modeForced === "conductor") {
745
+ await this.deps.succession.abort(record.id);
746
+ if ((await this.deps.succession.status(record.id)).phase === "committed")
747
+ throw new BridgeError(409, "The ownership is committed; reconciliation cannot abort it.");
748
+ }
749
+ await this.update(record, { state: "failed", error: "The destination confirmed no pane exists after ten minutes. The move was aborted; the original chat keeps its role." });
750
+ return;
751
+ }
752
+ }
753
+ if (record.modeForced === "conductor")
754
+ await this.deps.succession.ensurePrepared(record.id);
755
+ const document = await readFile(handoffPath(record.id), "utf8").catch(() => undefined);
756
+ if (!document) {
757
+ await this.run(record, DEFAULT_HANDOFF_MS, record.modeForced === "conductor" ? transaction?.previous : undefined, peer, record.project);
758
+ if (record.state === "uncertain")
759
+ throw new BridgeError(503, record.error ?? "The launch is still uncertain.");
760
+ return;
761
+ }
762
+ const target = await this.continueOnPeer(record, peer, record.project, document);
763
+ if (record.modeForced === "conductor") {
764
+ const status = await this.deps.succession.status(record.id);
765
+ if (status.phase !== "committed") {
766
+ await this.deps.succession.prepared(record.id, target);
767
+ await this.deps.succession.commit(record.id);
768
+ }
769
+ await this.deps.succession.finish(record.id);
770
+ }
771
+ await this.update(record, { state: "moved", movedAt: new Date(this.now).toISOString(), target, placement: "peer", error: undefined,
772
+ handedOffTo: { computer: peer.name, target }, handedOffFrom: { target: record.from.target, title: record.from.label ?? record.from.target.source } });
773
+ }
774
+ catch (error) {
775
+ const attempts = (record.recovery?.attempts ?? 0) + 1;
776
+ const deadline = Date.parse(record.createdAt) + 10 * 60_000;
777
+ const refused = error instanceof BridgeError && error.status >= 400 && error.status < 500;
778
+ let message = String(error instanceof Error ? error.message : error);
779
+ if (refused || this.now >= deadline) {
780
+ if (record.modeForced === "conductor") {
781
+ // abort() reads the durable commit point and cannot roll back a
782
+ // committed generation, including a lost commit acknowledgement.
783
+ await this.deps.succession.abort(record.id).catch(() => undefined);
784
+ const state = await this.deps.succession.status(record.id).catch(() => undefined);
785
+ message += state?.phase === "committed" ? " Ownership is committed; the old chat remains fenced. Reconcile conductor status on the original Hook." : state?.phase === "aborted" ? " The uncommitted move was aborted; the original conductor keeps the role." : " Ownership is uncertain; verify the original Hook's generation before changing roles.";
786
+ }
787
+ await this.update(record, { state: "failed", error: message.slice(0, 500) }).catch(() => undefined);
788
+ }
789
+ else {
790
+ const delay = Math.min(600_000, 5_000 * 2 ** Math.min(attempts - 1, 20));
791
+ await this.update(record, { state: "uncertain", error: message.slice(0, 500), recovery: { attempts, nextAt: new Date(Math.min(this.now + delay, deadline)).toISOString() } }).catch(() => undefined);
792
+ }
793
+ }
794
+ })().finally(() => this.running.delete(key));
795
+ this.running.set(key, work);
796
+ }
797
+ }
557
798
  /** An ordinary move never acquires permission to stop a conductor merely
558
799
  * because the owner promoted its source while the hand-off was running. */
559
800
  async checkPromotion(record) {
@@ -0,0 +1,29 @@
1
+ import type { IncomingMessage } from "node:http";
2
+ /** Sockets one identity may hold per client kind, and in all. */
3
+ export declare const SOCKETS_PER_KIND = 16;
4
+ export declare const SOCKETS_PER_IDENTITY = 32;
5
+ /** Every identity together; the backstop if identities themselves multiply. */
6
+ export declare const SOCKETS_TOTAL = 128;
7
+ /**
8
+ * Who a WebSocket belongs to, from what the Hook itself trusts rather than a
9
+ * client hint: a peer key's gateway rebuilds its request with `x-phren-origin:
10
+ * peer` and the peer's fingerprint, so that is its own identity; everything
11
+ * else arrives on the owner's local socket or the owner's SSH pipe and is the
12
+ * owner. `x-phren-client` only picks a sub-pool inside the identity.
13
+ */
14
+ export declare function socketIdentity(request: Pick<IncomingMessage, "headers">): string;
15
+ export declare const socketKind: (request: Pick<IncomingMessage, "headers">) => string;
16
+ /** Admits sockets oldest-first under the per-kind, per-identity and total caps. */
17
+ export declare class SocketBudget<S> {
18
+ private readonly limits;
19
+ private readonly entries;
20
+ constructor(limits?: {
21
+ kind: number;
22
+ identity: number;
23
+ total: number;
24
+ });
25
+ /** Register a socket; returns the sockets to close to stay inside the caps. */
26
+ add(socket: S, identity: string, kind: string): S[];
27
+ remove(socket: S): void;
28
+ count(identity?: string): number;
29
+ }