@phren/cli 0.3.52 → 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 +63 -2
  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 +269 -26
  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 +16386 -14258
  49. package/dist/modules/registry.js +8 -8
  50. package/dist/tools/dispatch.js +2 -1
  51. package/package.json +1 -1
@@ -1,4 +1,11 @@
1
- import { ownerRequest } from "./request-origin.js";
1
+ import { terminalProvider } from "./terminal.js";
2
+ import { peerFingerprint } from "./dispatch-hosts.js";
3
+ import { redactPeerHandoff } from "./peer-handoff.js";
4
+ import { relocationSupport } from "./worker-relocation.js";
5
+ import { continuationIntent, continuationLaunchSchema, continuationPlacement, launchContinuation } from "./continuation-launch.js";
6
+ import { addClaudeAccount } from "./account-add.js";
7
+ import { localMoveAvailability, moveComputers } from "./move-computers.js";
8
+ import { ownerRequest, requestPeer } from "./request-origin.js";
2
9
  import { listMoves, moveSessionFields, readMove } from "./session-move.js";
3
10
  import { getTaskRoute, getTaskDirectoryRoute, updateTaskRoute, createTaskRoute, saveTaskRoute, launchTaskRoute } from "./task-routes.js";
4
11
  import { ownerInboxView } from "./owner-inbox-view.js";
@@ -19,10 +26,10 @@ import { hookWorkers } from "./dispatch-returns.js";
19
26
  import { remoteChildren } from "./dispatch-tree.js";
20
27
  import { briefArrival, briefId, readLaunchBrief } from "./launch-brief.js";
21
28
  import { listApprovalRules, changeApprovalRule } from "./approval-rules.js";
22
- import { addGrant, listNamedGrants, removeGrant } from "./grants.js";
29
+ import { addGrant, listGrants, listNamedGrants, removeGrant } from "./grants.js";
23
30
  import { clearProjectAuthority, confirmAuthority, listConfirmations, projectAuthority, readAuthority, setProjectAuthority } from "./authority.js";
24
31
  import { readComputers } from "./computer-identity.js";
25
- import { optionalHookPeers, peerRequest } from "./peers.js";
32
+ import { hookPeers, optionalHookPeers, peerRequest } from "./peers.js";
26
33
  import { candidateRepos, enrollProject } from "./enroll.js";
27
34
  import { browseFiles } from "./files.js";
28
35
  import { MAX_FILE_RANGE, rangeInteger, readFileRange } from "./file-range.js";
@@ -82,7 +89,7 @@ async function childActivity(source, session) {
82
89
  export const capabilities = { transcript: true, progress: true, images: true, prompt: true, stop: true,
83
90
  terminal: "ssh-pty", shell: "ssh-pty", paneTerminal: "ssh-pty", paneLayout: true, deskPresence: true, herdr: true, sessionRename: true, diff: true, webServers: true, webPreview: "ssh-exec", activity: true,
84
91
  approvals: true, questions: false, accountUsage: true, providers: ["codex", "claude", "copilot", "opencode"],
85
- files: true, repositoryFiles: true, fileResolution: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, setLink: true, ownerInbox: true, workerReports: true, queuedHandOff: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, codeFiles: true, overviewStream: true, speech: true, speechTimestamps: true, speechTimestampStream: true, speechLive: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, deliveryFrames: true, paneDeliveries: true, resources: true, sudo: true, sudoOutcome: true, previewDeltas: true, quickChat: true, agentFolder: true, launchPermissionMode: true, sessionMove: true, moveNewChat: true, moveConductor: true, projectMemory: true, fileWrite: true, fileSearch: true, gitReview: true, memoryStoreBatch: true, gitHosts: true, projectHostToken: true };
92
+ files: true, repositoryFiles: true, fileResolution: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, setLink: true, ownerInbox: true, workerReports: true, queuedHandOff: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, codeFiles: true, overviewStream: true, speech: true, speechTimestamps: true, speechTimestampStream: true, speechLive: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, deliveryFrames: true, paneDeliveries: true, resources: true, sudo: true, sudoOutcome: true, previewDeltas: true, quickChat: true, agentFolder: true, launchPermissionMode: true, sessionMove: true, moveNewChat: true, moveConductor: true, moveToComputer: true, moveConductorToComputer: true, claudeAccountAdd: true, workerRelocation: 1, projectMemory: true, fileWrite: true, fileSearch: true, gitReview: true, memoryStoreBatch: true, gitHosts: true, projectHostToken: true };
86
93
  export function capabilitiesForModules(snapshot) {
87
94
  const allowed = new Set(snapshot.modules.flatMap(module => module.capabilities));
88
95
  const result = Object.fromEntries(Object.entries(capabilities).filter(([name]) => allowed.has(name)));
@@ -315,6 +322,19 @@ async function fromPeers(route) {
315
322
  }));
316
323
  return { peers: answers, ...(peerError ? { peerError } : {}) };
317
324
  }
325
+ async function moveDestination(move, caller) {
326
+ if (!caller || !move.to.computer || caller.fingerprint !== move.computerFingerprint || caller.name && caller.name !== move.to.computer || caller.id && caller.id !== move.computerId)
327
+ throw new BridgeError(403, "This peer is not the move's source or destination.");
328
+ const peer = (await hookPeers()).find(peer => peerFingerprint(peer) === move.computerFingerprint && (!caller.name || caller.name === peer.name));
329
+ if (!peer || object((await peerRequest(peer, "/v1/health", undefined, 5_000)).computer).id !== move.computerId)
330
+ throw new BridgeError(403, "The move destination's enrollment changed.");
331
+ }
332
+ async function peerContinuationIntent(caller, id) {
333
+ const candidates = (await hookPeers()).filter(peer => peerFingerprint(peer) === caller.fingerprint && (!caller.name || caller.name === peer.name));
334
+ if (candidates.length !== 1)
335
+ throw new BridgeError(403, "The launch origin is not uniquely verified.");
336
+ return peerRequest(candidates[0], `/v1/sessions/move/intent?id=${z.string().uuid().parse(id)}`, undefined, 5_000);
337
+ }
318
338
  export function createRouteHandler(ctx) {
319
339
  const { version, modules, info, computerID, scheduleStore, scheduler, dispatches, agentHooks, journal, modelCatalog, accountUsage, resources, launches, locatedDirectories, fanoutMessages, canary } = ctx;
320
340
  const { conversationReader, childConversationReader, emptyPage } = ctx.streams;
@@ -330,6 +350,12 @@ export function createRouteHandler(ctx) {
330
350
  throw new BridgeError(400, "Invalid request origin.");
331
351
  requireRoute(modules, request.method ?? "", url.pathname);
332
352
  let result;
353
+ if (url.pathname.startsWith("/v1/conductor/move/")) {
354
+ if (!ctx.succession)
355
+ throw new BridgeError(503, "Conductor succession is unavailable.");
356
+ if (request.method === "GET")
357
+ await ctx.succession.authorize(z.string().uuid().parse(url.searchParams.get("id")), requestPeer(request));
358
+ }
333
359
  const memoryRoute = PROJECT_MEMORY_ROUTE.exec(url.pathname);
334
360
  if (memoryRoute) {
335
361
  const [, project, route] = memoryRoute;
@@ -408,10 +434,94 @@ export function createRouteHandler(ctx) {
408
434
  result = { dispatches: await dispatchStatus() };
409
435
  break;
410
436
  // A session move (session-move.ts) by its id, or this computer's recent moves.
437
+ case "/v1/conductor/move/launch": {
438
+ if (!ctx.succession)
439
+ throw new BridgeError(503, "Conductor succession is unavailable.");
440
+ result = await ctx.succession.launchIntent(z.string().uuid().parse(url.searchParams.get("id")));
441
+ break;
442
+ }
443
+ case "/v1/conductor/move/status": {
444
+ if (!ctx.succession)
445
+ throw new BridgeError(503, "Conductor succession is unavailable.");
446
+ result = await ctx.succession.status(z.string().uuid().parse(url.searchParams.get("id")));
447
+ break;
448
+ }
449
+ case "/v1/conductor/move/operation": {
450
+ if (!ctx.succession)
451
+ throw new BridgeError(503, "Conductor succession is unavailable.");
452
+ result = await ctx.succession.outgoing(z.string().uuid().parse(url.searchParams.get("id")), z.string().uuid().parse(url.searchParams.get("operationId")));
453
+ break;
454
+ }
455
+ case "/v1/conductor/move/notification": {
456
+ if (!ctx.succession)
457
+ throw new BridgeError(503, "Conductor succession is unavailable.");
458
+ result = await ctx.succession.notification(z.string().uuid().parse(url.searchParams.get("id")), z.string().parse(url.searchParams.get("deliveryId")));
459
+ break;
460
+ }
461
+ case "/v1/dispatch/relocation": {
462
+ result = await relocationSupport(z.string().parse(url.searchParams.get("id")), z.string().parse(url.searchParams.get("session")));
463
+ break;
464
+ }
465
+ case "/v1/sessions/move/intent": {
466
+ const id = z.string().uuid().parse(url.searchParams.get("id"));
467
+ const caller = requestPeer(request), move = await readMove(id);
468
+ if (!move || move.state === "failed")
469
+ throw new BridgeError(403, "This continuation intent is no longer authorized.");
470
+ await moveDestination(move, caller);
471
+ result = await continuationIntent(id);
472
+ break;
473
+ }
474
+ case "/v1/sessions/move/launch": {
475
+ const placement = await continuationPlacement(z.string().uuid().parse(url.searchParams.get("id")));
476
+ const caller = requestPeer(request);
477
+ if (!placement && caller) {
478
+ const id = z.string().uuid().parse(url.searchParams.get("id"));
479
+ const intent = continuationLaunchSchema.parse(await peerContinuationIntent(caller, id));
480
+ if (intent.computerId !== info.computer.id || intent.brief.id !== id)
481
+ throw new BridgeError(403, "This continuation is not intended for this Hook.");
482
+ result = { state: "not-placed" };
483
+ break;
484
+ }
485
+ if (!ownerRequest(request, {}) && (!caller || !placement?.caller || caller.name !== placement.caller.name || caller.id !== placement.caller.id || caller.fingerprint !== placement.caller.fingerprint))
486
+ throw new BridgeError(403, "This peer is not the launch's recorded counterpart.");
487
+ result = placement ?? { state: "missing" };
488
+ break;
489
+ }
490
+ case "/v1/sessions/move/computers": {
491
+ if (!ownerRequest(request, {}))
492
+ throw new BridgeError(403, "Only the owner can list continuation computers.");
493
+ const session = url.searchParams.get("session");
494
+ let currentAccount;
495
+ if (session) {
496
+ const server = selectedServer(url);
497
+ const rows = objects((await readWorkspaces(server, await snapshot(server), false)).groups).flatMap(group => objects(group.children));
498
+ const current = rows.find(row => object(row.target).session === session && row.agent === "claude");
499
+ if (current)
500
+ currentAccount = String(object(current.account).id ?? "default");
501
+ }
502
+ result = await moveComputers(url.searchParams.get("project"), info.computer.name, async () => ({ ...await localMoveAvailability(url.searchParams.get("project"), () => accountUsage.read(new Set(["claude"]), true), url.searchParams.get("conductor") === "1"), computerId: info.computer.id }), currentAccount, url.searchParams.get("conductor") === "1");
503
+ break;
504
+ }
505
+ // Local facts only: peers may probe these without starting a move or fanning out.
506
+ case "/v1/sessions/move/availability": {
507
+ if (!ownerRequest(request, {}) && request.headers?.["x-phren-origin"] !== "peer")
508
+ throw new BridgeError(403, "Only the owner or a verified peer can read continuation availability.");
509
+ const availability = await localMoveAvailability(url.searchParams.get("project"), () => accountUsage.read(new Set(["claude"]), true), url.searchParams.get("conductor") === "1");
510
+ if (!ownerRequest(request, {}))
511
+ for (const harness of availability.harnesses)
512
+ for (const account of harness.accounts ?? []) {
513
+ delete account.email;
514
+ delete account.plan;
515
+ }
516
+ result = { ...availability, computerId: info.computer.id };
517
+ break;
518
+ }
411
519
  case "/v1/sessions/move": {
412
520
  const move = await readMove(z.string().uuid().parse(url.searchParams.get("id")));
413
521
  if (!move)
414
522
  throw new BridgeError(404, "No move with that id on this computer.");
523
+ if (request.headers?.["x-phren-origin"] === "peer")
524
+ await moveDestination(move, requestPeer(request));
415
525
  result = { move };
416
526
  break;
417
527
  }
@@ -744,7 +854,66 @@ export function createRouteHandler(ctx) {
744
854
  }
745
855
  else if (request.method === "POST") {
746
856
  const data = await body(request);
747
- if (url.pathname === "/v1/tasks/launch") {
857
+ if (url.pathname.startsWith("/v1/conductor/move/"))
858
+ await ctx.succession.authorize(z.string().uuid().parse(data.id), requestPeer(request), url.pathname.endsWith("/prepare") ? z.string().uuid().parse(data.originId) : undefined);
859
+ const executeConductor = async (action, payload, origin, remote = false) => {
860
+ if (action === "dispatch")
861
+ return dispatches.dispatch(payload, { server: origin.server, workspace: origin.workspace, tab: origin.tab, pane: origin.pane });
862
+ if (action === "hand_off")
863
+ return handOff(payload, { bypassConductor: true });
864
+ if (action === "returns")
865
+ return { returns: await ctx.returns.take(!remote) };
866
+ if (action === "approve") {
867
+ const parsed = z.object({ id: z.string().uuid(), decision: z.enum(approvalDecisions), actionId: z.string().min(1).max(200) }).strict().parse(payload);
868
+ await ctx.returns.answerApproval(parsed.id, parsed.decision, parsed.actionId, origin);
869
+ return { ok: true };
870
+ }
871
+ if (action === "grants-list")
872
+ return { grants: await listGrants() };
873
+ if (action === "grants-add")
874
+ return { grant: await addGrant(payload) };
875
+ return { grant: await removeGrant(payload) };
876
+ };
877
+ const conductorCall = (action, payload, origin, run) => {
878
+ if (request.headers?.["x-phren-origin"] === "peer") {
879
+ if (action === "hand_off")
880
+ return run();
881
+ throw new BridgeError(403, "Peer conductor operations require the authenticated generation-scoped routes.");
882
+ }
883
+ return ctx.succession ? ctx.succession.call(action, payload, origin, run) : run();
884
+ };
885
+ if (url.pathname === "/v1/conductor/move/prepare") {
886
+ if (!ctx.succession)
887
+ throw new BridgeError(503, "Conductor succession is unavailable.");
888
+ result = await ctx.succession.prepare(data);
889
+ }
890
+ else if (url.pathname === "/v1/conductor/move/commit") {
891
+ if (!ctx.succession)
892
+ throw new BridgeError(503, "Conductor succession is unavailable.");
893
+ result = await ctx.succession.activate(data);
894
+ }
895
+ else if (url.pathname === "/v1/conductor/move/operate") {
896
+ if (!ctx.succession)
897
+ throw new BridgeError(503, "Conductor succession is unavailable.");
898
+ result = await ctx.succession.operate(data, executeConductor);
899
+ }
900
+ else if (url.pathname === "/v1/conductor/move/ack") {
901
+ if (!ctx.succession)
902
+ throw new BridgeError(503, "Conductor succession is unavailable.");
903
+ result = await ctx.succession.acknowledge(data, rows => ctx.returns.acknowledge(rows));
904
+ }
905
+ else if (url.pathname === "/v1/conductor/move/notice") {
906
+ if (!ctx.succession)
907
+ throw new BridgeError(503, "Conductor succession is unavailable.");
908
+ result = await ctx.succession.notice(data);
909
+ }
910
+ else if (url.pathname === "/v1/conductor/call") {
911
+ if (request.headers?.["x-phren-origin"] === "peer")
912
+ throw new BridgeError(403, "Only local agents use the conductor call route.");
913
+ const parsed = z.object({ action: z.enum(["dispatch", "hand_off", "returns", "approve", "grants-list", "grants-add", "grants-remove"]), data: z.record(z.string(), z.unknown()), origin: targetSchema.omit({ source: true, session: true }) }).strict().parse(data);
914
+ result = await conductorCall(parsed.action, parsed.data, parsed.origin, () => executeConductor(parsed.action, parsed.data, parsed.origin));
915
+ }
916
+ else if (url.pathname === "/v1/tasks/launch") {
748
917
  result = await launches.run(async () => launchTaskRoute(modules.store, selectedServer(url), data));
749
918
  }
750
919
  else if (url.pathname === "/v1/tasks/save") {
@@ -773,7 +942,7 @@ export function createRouteHandler(ctx) {
773
942
  else if (url.pathname === "/v1/code/note") {
774
943
  result = await saveCodeNote(await resolveCodeStore(scheduleStore, typeof data.store === "string" ? data.store : undefined, true), data, dispatches ? async (note, prompt) => {
775
944
  if (note.target && "session" in note.target)
776
- return handOff({ session: note.target.session, project: note.project, text: prompt });
945
+ return handOff({ session: note.target.session, project: note.project, text: prompt }, { bypassConductor: true });
777
946
  return dispatches.dispatch({ computer: "anywhere", project: note.project,
778
947
  harness: note.target && "harness" in note.target ? note.target.harness : "codex", prompt, label: `Code note: ${note.symbol}`.slice(0, 200) });
779
948
  } : undefined);
@@ -785,6 +954,44 @@ export function createRouteHandler(ctx) {
785
954
  const { origin: _origin, ...input } = data;
786
955
  result = { ok: true, move: await ctx.mover.start(input, { owner: ownerRequest(request, data) }) };
787
956
  }
957
+ else if (url.pathname === "/v1/sessions/move/abort") {
958
+ if (!ownerRequest(request, data))
959
+ throw new BridgeError(403, "Only the owner can abort a move.");
960
+ if (!ctx.mover)
961
+ throw new BridgeError(503, "Session moves are unavailable.");
962
+ result = { ok: true, move: await ctx.mover.abort(z.object({ id: z.string().uuid() }).strict().parse(data).id) };
963
+ }
964
+ else if (url.pathname === "/v1/sessions/move/launch") {
965
+ const caller = requestPeer(request);
966
+ if (!caller && !ownerRequest(request, data))
967
+ throw new BridgeError(403, "Only an authenticated owner or enrolled peer can launch a continuation.");
968
+ if (caller) {
969
+ const launch = continuationLaunchSchema.parse(data);
970
+ const canonical = await peerContinuationIntent(caller, launch.brief.id);
971
+ if (JSON.stringify(canonical) !== JSON.stringify(data))
972
+ throw new BridgeError(403, "This is not the origin Hook's owner-admitted continuation launch.");
973
+ }
974
+ const preparedRole = (await (await import("./conductor-role.js")).readRoleState())?.succession;
975
+ if (preparedRole && preparedRole.id === object(data.brief).id)
976
+ await ctx.succession.authorize(preparedRole.id, caller);
977
+ if (data.computerId !== info.computer.id)
978
+ throw new BridgeError(409, "The destination Hook identity changed; no chat was launched.");
979
+ const verified = ctx.succession ? await ctx.succession.verifiedLaunch(data) : data;
980
+ result = await launchContinuation(verified, (input, onPlaced) => launches.run(async () => {
981
+ const role = await (await import("./conductor-role.js")).readRoleState();
982
+ const prepared = role?.succession?.side === "successor" && role.succession.id === input.brief.id && role.succession.phase !== "aborted";
983
+ const cwd = prepared ? defaultPhrenPath() : await dispatchProjectDirectory(input.project);
984
+ return launchSession(selectedServer(url), { cwd, kind: input.to.harness, account: input.to.account, model: input.to.model, effort: input.to.effort, label: `move-${input.brief.id}`, brief: input.brief }, { trustFolder: true, onPlaced: async (target) => {
985
+ await onPlaced(target);
986
+ await terminalProvider().renamePane(selectedServer(url), z.string().parse(target.pane), input.label).catch(() => undefined);
987
+ } });
988
+ }), { caller, server: selectedServer(url) });
989
+ }
990
+ else if (url.pathname === "/v1/accounts/claude/add") {
991
+ if (!ownerRequest(request, data))
992
+ throw new BridgeError(403, "Only the owner can add a Claude account.");
993
+ result = await launches.run(() => addClaudeAccount(data, selectedServer(url)));
994
+ }
788
995
  else if (url.pathname === "/v1/sessions/rename") {
789
996
  result = await renameSession(selectedServer(url), data);
790
997
  }
@@ -833,7 +1040,9 @@ export function createRouteHandler(ctx) {
833
1040
  result = await closeOwnPane(data);
834
1041
  }
835
1042
  else if (url.pathname === "/v1/hand-off") {
836
- result = await ctx.handOffs.enqueue(data);
1043
+ const forwarded = request.headers?.["x-phren-origin"] === "peer" && typeof data.deliveryId === "string" && /^handoff-notice-[a-f0-9]{40}$/.test(data.deliveryId)
1044
+ ? await ctx.succession?.forward(data.target, z.string().max(32768).parse(data.text), data.deliveryId) : undefined;
1045
+ result = forwarded ? { ok: forwarded.delivered, delivered: forwarded.delivered, deliveryId: data.deliveryId } : await conductorCall("hand_off", data, data.origin, () => ctx.handOffs.enqueue(data));
837
1046
  }
838
1047
  else if (url.pathname === "/v1/hand-off/status") {
839
1048
  const body = z.object({ deliveryId: z.string().min(8).max(64), target: targetSchema }).strict().parse(data);
@@ -842,24 +1051,25 @@ export function createRouteHandler(ctx) {
842
1051
  else if (url.pathname === "/v1/dispatch") {
843
1052
  // `origin` is the caller's own pane, added by the MCP tool or CLI from Herdr's variables.
844
1053
  const { origin, ...brief } = data;
845
- result = await dispatches.dispatch(brief, origin);
1054
+ result = await conductorCall("dispatch", brief, origin, () => dispatches.dispatch(brief, origin));
846
1055
  }
847
1056
  else if (url.pathname === "/v1/dispatch/workers") {
848
1057
  result = await hookWorkers(agentHooks)(data);
849
1058
  }
850
1059
  else if (url.pathname === "/v1/dispatch/returns") {
851
- result = { returns: await ctx.returns.take() };
1060
+ result = await conductorCall("returns", {}, data.origin, async () => ({ returns: await ctx.returns.take() }));
852
1061
  }
853
1062
  else if (url.pathname === "/v1/dispatch/approve") {
854
1063
  const body = z.object({ id: z.string().uuid(), decision: z.enum(approvalDecisions), actionId: z.string().min(1).max(200), origin: originPaneSchema.optional() }).strict().parse(data);
855
- await ctx.returns.answerApproval(body.id, body.decision, body.actionId, body.origin);
856
- result = { ok: true };
1064
+ const { origin, ...answer } = body;
1065
+ result = await conductorCall("approve", answer, origin, async () => { await ctx.returns.answerApproval(body.id, body.decision, body.actionId, origin); return { ok: true }; });
857
1066
  }
858
1067
  else if (url.pathname === "/v1/approval-rules") {
859
1068
  result = await changeApprovalRule(data, "POST");
860
1069
  }
861
1070
  else if (url.pathname === "/v1/conductor/grants") {
862
- result = { ok: true, grant: await addGrant(data) };
1071
+ const { origin, ...grant } = data;
1072
+ result = await conductorCall("grants-add", grant, origin, async () => ({ ok: true, grant: await addGrant(grant) }));
863
1073
  }
864
1074
  else if (url.pathname === "/v1/authority" || url.pathname === "/v1/authority/confirm") {
865
1075
  // The owner writes the policy from the phone; an agent's call names its pane.
@@ -877,7 +1087,7 @@ export function createRouteHandler(ctx) {
877
1087
  else if (url.pathname === "/v1/conductor/stop") {
878
1088
  if (!ownerRequest(request, data))
879
1089
  throw new BridgeError(403, "Only the owner can change the conductor.");
880
- result = await launches.run(async () => stopConductor(data));
1090
+ result = await launches.run(async () => await ctx.succession?.stopOrigin(data.paneId) ?? stopConductor(data));
881
1091
  }
882
1092
  else if (url.pathname === "/v1/sets/name") {
883
1093
  result = await nameSet(data);
@@ -978,6 +1188,8 @@ export function createRouteHandler(ctx) {
978
1188
  if (url.pathname !== "/v1/conductor/grants" && url.pathname !== "/v1/authority" && url.pathname !== "/v1/approval-rules")
979
1189
  throw new BridgeError(404, "Unknown Phren Hook route.");
980
1190
  const data = await body(request);
1191
+ if (url.pathname === "/v1/conductor/grants" && request.headers?.["x-phren-origin"] === "peer")
1192
+ throw new BridgeError(403, "Peer conductor operations require the authenticated generation-scoped routes.");
981
1193
  if (url.pathname === "/v1/approval-rules") {
982
1194
  result = await changeApprovalRule(data, "DELETE");
983
1195
  }
@@ -1000,8 +1212,9 @@ export function createRouteHandler(ctx) {
1000
1212
  catch (error) {
1001
1213
  response.statusCode = error instanceof BridgeError ? error.status : error instanceof z.ZodError || error instanceof SyntaxError ? 400 : 503;
1002
1214
  response.setHeader("Content-Type", "application/json");
1003
- response.end(JSON.stringify({ error: error instanceof BridgeError ? error.message : "Phren Hook could not complete this request. Run phren bridge doctor on the computer.",
1004
- ...(error instanceof BridgeError ? error.details : {}) }));
1215
+ const failure = { error: error instanceof BridgeError ? error.message : "Phren Hook could not complete this request. Run phren bridge doctor on the computer.",
1216
+ ...(error instanceof BridgeError ? error.details : {}) };
1217
+ response.end(JSON.stringify(request.headers?.["x-phren-origin"] === "peer" ? { ...failure, error: redactPeerHandoff(failure.error) } : failure));
1005
1218
  }
1006
1219
  };
1007
1220
  }
@@ -1,3 +1,5 @@
1
+ import { continuationPlacement } from "./continuation-launch.js";
2
+ import { ConductorSuccessionService, preflightConductorWorkers } from "./conductor-succession.js";
1
3
  import { StorePulls } from "./store-pull.js";
2
4
  import { GitboyWebhooks } from "./gitboy-webhooks.js";
3
5
  import { setChoiceReaders } from "./account-choice.js";
@@ -59,7 +61,7 @@ import { harnessInventoryWithin, launchCheckOff } from "./harnesses.js";
59
61
  import { paneAccount, paneAccountKey } from "./pane-accounts.js";
60
62
  import { readTurn } from "./turn-records.js";
61
63
  import { readLaunchBrief } from "./launch-brief.js";
62
- import { conductorPane } from "./conductor-role.js";
64
+ import { conductorPane, readRoleState } from "./conductor-role.js";
63
65
  import { terminalKind, terminalProvider } from "./terminal.js";
64
66
  import { targetTranscriptPath } from "./transcripts.js";
65
67
  import { codexAppServerEnabled, codexServers } from "./codex-servers.js";
@@ -91,6 +93,9 @@ export async function serve(version, options = {}) {
91
93
  const dispatches = modules.has("conductor")
92
94
  ? new DispatchService({ computerID, validateParentTarget: target => validateTarget(target, false, true),
93
95
  originAgent: async (origin) => {
96
+ const state = (await readRoleState())?.succession;
97
+ if (state?.side === "origin" && state.phase === "committed" && state.from.server === origin.server && state.from.pane === origin.pane && state.previous.terminal && state.previous.source)
98
+ return { agent: state.previous.source, terminal: state.previous.terminal };
94
99
  const pane = findPane(await snapshot(origin.server), origin);
95
100
  const agent = provider.safeParse(pane?.agent);
96
101
  return agent.success && typeof pane?.terminal_id === "string" ? { agent: agent.data, terminal: pane.terminal_id } : undefined;
@@ -100,18 +105,23 @@ export async function serve(version, options = {}) {
100
105
  const journal = new ActivityJournal();
101
106
  const agentHooks = new AgentHooks(undefined, modules, path.join(bridgeRoot(), "deliveries.json"));
102
107
  // Follows what dispatched workers do and tells the dispatching agent.
108
+ let succession;
103
109
  const returns = dispatches ? new DispatchReturns({
110
+ localComputer: { id: computerID, name: hostname() },
111
+ forward: (origin, text, deliveryId) => succession?.forward(origin, text, deliveryId) ?? Promise.resolve(undefined),
104
112
  // Continue on another signed-in account when a Claude worker stops at its usage limit: opt-in, `phren config account-failover on`.
105
- failover: new AccountFailover({ rooms: () => dispatches.claudeRooms(), dispatch: (input, origin, continues) => dispatches.dispatch(input, origin, continues) }),
113
+ failover: new AccountFailover({ rooms: () => dispatches.claudeRooms(), dispatch: (input, origin, continues) => succession ? succession.automatic("dispatch", { ...input, continues }, origin, () => dispatches.dispatch(input, origin, continues)) : dispatches.dispatch(input, origin, continues) }),
106
114
  localWorkers: hookWorkers(agentHooks),
107
- close: async (receipt) => {
108
- const data = { target: receipt.target, dispatch: receipt.id, turn: receipt.closePending.turn };
109
- if (isLocalComputer(receipt.computer))
115
+ close: async (receipt, verifiedPeer) => {
116
+ const data = { target: receipt.target, dispatch: receipt.moves?.slice().reverse().find(move => move.to.computer)?.id ?? receipt.id, turn: receipt.closePending.turn };
117
+ if (receipt.computerId === computerID)
110
118
  return closeFinishedWorker(data, handOffs);
111
- const peer = (await hookPeers()).find(peer => peer.name === receipt.computer);
112
- if (!peer)
113
- throw new BridgeError(503, "The worker's computer is offline.");
114
- return peerRequest(peer, "/v1/dispatch/close", data);
119
+ const peer = verifiedPeer ?? (await hookPeers().catch(() => [])).find(peer => peer.name === receipt.computer);
120
+ if (peer)
121
+ return peerRequest(peer, "/v1/dispatch/close", data);
122
+ if (!receipt.moves?.some(move => move.to.computer) && isLocalComputer(receipt.computer))
123
+ return closeFinishedWorker(data, handOffs);
124
+ throw new BridgeError(503, "The worker's verified computer is offline.");
115
125
  },
116
126
  localAnswer: (target, actionId, decision) => agentHooks.answer(target, actionId, decision),
117
127
  // A worker's request the worker's own Hook did not push reaches this Hook's phone.
@@ -135,18 +145,24 @@ export async function serve(version, options = {}) {
135
145
  const sideQuestions = new SideQuestions();
136
146
  const sendPrompt = async (target, text, deliveryId, typing) => await paneRouteOnce({ agentHooks, modelSwitcher, settingsSwitcher, permissionModeSwitcher, codexQuestions, sideQuestions }, new URL("http://phren.local/v1/prompt"), { target, text, deliveryId, hookQueued: true }, {}, typing);
137
147
  const handOffs = dispatches ? new HandOffQueue({
148
+ forward: (target, text, deliveryId) => succession?.forward(target, text, deliveryId) ?? Promise.resolve(undefined),
138
149
  validate: target => validateTarget(target, false, true),
139
150
  current: async (target) => {
140
151
  const pane = findPane(await snapshot(target.server), target);
141
152
  const session = pane ? await paneIdentity(target.server, pane, true) : undefined;
142
153
  return pane && session ? { session, terminal: pane.terminal_id } : undefined;
143
154
  },
144
- notify: (target, text, deliveryId, computer) => handOff({ computer, target, text, deliveryId }, { notifySender: false }),
155
+ notify: (target, text, deliveryId, computer) => handOff({ computer, target, text, deliveryId }, { notifySender: false, bypassConductor: true }),
145
156
  send: sendPrompt,
146
157
  }) : undefined;
147
158
  // Moving a session to another agent (session-move.ts): its hand-off request
148
159
  // takes the hand_off path, and the new agent starts through the launch path.
160
+ succession = dispatches ? new ConductorSuccessionService({ root, computer: { id: computerID, name: hostname() }, snapshot, validate: target => validateTarget(target, false, true),
161
+ isSuccessor: async (origin, id) => (await readTurn(origin.server, origin.pane))?.dispatch === id,
162
+ deliver: (target, text, deliveryId) => handOffs.enqueue({ target, text, deliveryId }),
163
+ checkWorkers: from => preflightConductorWorkers(from, computerID), }) : undefined;
149
164
  const mover = new SessionMover({
165
+ succession,
150
166
  snapshot: server => snapshot(server),
151
167
  identity: (server, pane) => paneIdentity(server, pane, true),
152
168
  terminal: terminalProvider(),
@@ -156,7 +172,16 @@ export async function serve(version, options = {}) {
156
172
  inventory: () => launchCheckOff() ? Promise.resolve(undefined) : harnessInventoryWithin(2_500),
157
173
  transcript: async (target) => transcriptTail(await targetTranscriptPath(target)),
158
174
  paneAccount: (server, pane) => paneAccount(paneAccountKey(server, pane.pane_id), typeof pane.terminal_id === "string" ? pane.terminal_id : undefined)?.id,
159
- paneDispatch: async (server, pane) => (await readTurn(server, String(pane.pane_id)))?.dispatch,
175
+ paneDispatch: async (server, pane) => {
176
+ const dispatch = (await readTurn(server, String(pane.pane_id)))?.dispatch;
177
+ if (!dispatch)
178
+ return undefined;
179
+ const continuation = await continuationPlacement(dispatch);
180
+ if (continuation)
181
+ return continuation.worker ? dispatch : undefined;
182
+ const localMove = await (await import("./session-move.js")).readMove(dispatch);
183
+ return localMove && !localMove.dispatch ? undefined : dispatch;
184
+ },
160
185
  brief: readLaunchBrief,
161
186
  isConductor: async (server, pane) => (await conductorPane(server, await snapshot(server)))?.pane_id === pane.pane_id,
162
187
  envAtStart: server => terminalKind(server) === "tmux",
@@ -238,7 +263,7 @@ export async function serve(version, options = {}) {
238
263
  // 256 KiB: gitboy's /memory/files asks about up to 500 paths in one query string.
239
264
  const http = createServer({ maxHeaderSize: 256 * 1024 }, createRouteHandler({ version, modules, info, computerID, scheduleStore, scheduler, dispatches, agentHooks,
240
265
  journal, tabActivity, contextUsage, modelCatalog, modelSwitcher, settingsSwitcher, permissionModeSwitcher, sideQuestions, accountUsage, resources, codexQuestions, launches, locatedDirectories,
241
- fanoutMessages, canary, streams, returns, handOffs, inbox, mover, storePulls, gitboyWebhooks }));
266
+ fanoutMessages, canary, streams, returns, handOffs, inbox, mover, succession, storePulls, gitboyWebhooks }));
242
267
  http.requestTimeout = 20_000;
243
268
  http.headersTimeout = 10_000;
244
269
  http.maxHeadersCount = 32;
@@ -351,6 +376,8 @@ export async function serve(version, options = {}) {
351
376
  // Dispatch returns ride this tick and its shared snapshots. The returns
352
377
  // loop throttles its own peer polls and never holds up activity.
353
378
  void handOffs?.tick().catch(() => { });
379
+ void mover.reconcile().catch(() => { });
380
+ void succession?.reconcile().catch(() => { });
354
381
  void returns?.tick();
355
382
  void inbox?.tick().catch(() => { });
356
383
  })().finally(() => { recording = false; }).catch(() => { });
@@ -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;