@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.
- package/dist/bridge/account-add.d.ts +7 -0
- package/dist/bridge/account-add.js +39 -0
- package/dist/bridge/claude-accounts.js +1 -1
- package/dist/bridge/client.js +1 -1
- package/dist/bridge/command.js +2 -0
- package/dist/bridge/computers.js +3 -2
- package/dist/bridge/conductor-role.d.ts +162 -2
- package/dist/bridge/conductor-role.js +56 -23
- package/dist/bridge/conductor-succession.d.ts +100 -0
- package/dist/bridge/conductor-succession.js +649 -0
- package/dist/bridge/continuation-launch.d.ts +54 -0
- package/dist/bridge/continuation-launch.js +106 -0
- package/dist/bridge/dispatch-command.js +11 -4
- package/dist/bridge/dispatch-hosts.d.ts +3 -0
- package/dist/bridge/dispatch-hosts.js +6 -1
- package/dist/bridge/dispatch-returns.d.ts +21 -3
- package/dist/bridge/dispatch-returns.js +169 -39
- package/dist/bridge/dispatch.d.ts +11 -0
- package/dist/bridge/dispatch.js +70 -5
- package/dist/bridge/hand-off-queue.d.ts +3 -0
- package/dist/bridge/hand-off-queue.js +8 -0
- package/dist/bridge/hand-off.d.ts +13 -0
- package/dist/bridge/hand-off.js +20 -1
- package/dist/bridge/install.js +0 -6
- package/dist/bridge/launch-brief.d.ts +2 -0
- package/dist/bridge/launch-brief.js +19 -8
- package/dist/bridge/move-computers.d.ts +47 -0
- package/dist/bridge/move-computers.js +118 -0
- package/dist/bridge/peer-handoff.d.ts +5 -0
- package/dist/bridge/peer-handoff.js +52 -0
- package/dist/bridge/request-origin.d.ts +6 -0
- package/dist/bridge/request-origin.js +20 -0
- package/dist/bridge/scoped-gateway.d.ts +2 -1
- package/dist/bridge/scoped-gateway.js +16 -3
- package/dist/bridge/server-launch.d.ts +2 -0
- package/dist/bridge/server-launch.js +2 -0
- package/dist/bridge/server-routes.d.ts +6 -0
- package/dist/bridge/server-routes.js +228 -15
- package/dist/bridge/server.js +39 -12
- package/dist/bridge/session-move.d.ts +28 -1
- package/dist/bridge/session-move.js +266 -25
- package/dist/bridge/terminal-herdr.js +14 -0
- package/dist/bridge/terminal-tmux.js +1 -0
- package/dist/bridge/terminal.d.ts +2 -0
- package/dist/bridge/terminal.js +6 -0
- package/dist/bridge/worker-relocation.d.ts +5 -0
- package/dist/bridge/worker-relocation.js +33 -0
- package/dist/bridge-hook.mjs +16154 -14087
- package/dist/modules/registry.js +8 -8
- package/dist/tools/dispatch.js +2 -1
- package/package.json +1 -1
|
@@ -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 (
|
|
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
|
|
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
|
-
|
|
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 &&
|
|
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) {
|
|
@@ -93,6 +93,20 @@ export const herdrTerminal = {
|
|
|
93
93
|
await rpc(server, "pane.send_keys", { pane_id: pane, keys });
|
|
94
94
|
}
|
|
95
95
|
},
|
|
96
|
+
async shellCommand(server, pane, command) {
|
|
97
|
+
const deadline = Date.now() + 15_000;
|
|
98
|
+
for (;;) {
|
|
99
|
+
const info = object((await rpc(server, "pane.process_info", { pane_id: pane })).process_info);
|
|
100
|
+
if (Number.isSafeInteger(info.shell_pid) && info.foreground_process_group_id === info.shell_pid)
|
|
101
|
+
break;
|
|
102
|
+
if (Date.now() >= deadline)
|
|
103
|
+
throw new BridgeError(409, "The new pane did not become ready at its shell prompt.");
|
|
104
|
+
await new Promise(resolve => setTimeout(resolve, 200));
|
|
105
|
+
}
|
|
106
|
+
// An empty shell is not a named agent: agent.prompt cannot address it.
|
|
107
|
+
await rpc(server, "pane.send_text", { pane_id: pane, text: command });
|
|
108
|
+
await rpc(server, "pane.send_keys", { pane_id: pane, keys: ["Enter"] });
|
|
109
|
+
},
|
|
96
110
|
async prompt(server, pane, text, signal) {
|
|
97
111
|
try {
|
|
98
112
|
if (signal)
|
|
@@ -417,6 +417,7 @@ export const tmuxTerminal = {
|
|
|
417
417
|
for (const call of sendKeysCalls(target, keys))
|
|
418
418
|
await tmux(server, call);
|
|
419
419
|
},
|
|
420
|
+
async shellCommand(server, pane, command) { await tmuxTerminal.prompt(server, pane, command); },
|
|
420
421
|
async prompt(server, pane, text, signal) {
|
|
421
422
|
const target = toTmuxId(pane, "p"), buffer = `phren-${process.pid}-${Date.now().toString(36)}`;
|
|
422
423
|
// The text reaches tmux on stdin and the pane as one bracketed paste
|
|
@@ -98,6 +98,8 @@ export interface TerminalProvider {
|
|
|
98
98
|
/** Types `text` and sends the submit key. Success acknowledges transport,
|
|
99
99
|
* not a submitted turn; the harness must confirm that separately. */
|
|
100
100
|
prompt(server: string, pane: string, text: string, signal?: AbortSignal): Promise<void>;
|
|
101
|
+
/** Run an owner-selected command at an empty pane's shell prompt. */
|
|
102
|
+
shellCommand?(server: string, pane: string, command: string): Promise<void>;
|
|
101
103
|
/** Opens a pane; the caller finds it in the next `listPanes`. */
|
|
102
104
|
create(server: string, placement: PanePlacement): Promise<void>;
|
|
103
105
|
startAgent(server: string, pane: string, agent: AgentStart): Promise<void>;
|
package/dist/bridge/terminal.js
CHANGED
|
@@ -49,6 +49,12 @@ export const routedTerminal = {
|
|
|
49
49
|
readScreen: (server, pane, read) => route(server).readScreen(server, pane, read),
|
|
50
50
|
sendKeys: (server, pane, keys) => route(server).sendKeys(server, pane, keys),
|
|
51
51
|
prompt: (server, pane, text, signal) => route(server).prompt(server, pane, text, signal),
|
|
52
|
+
shellCommand: async (server, pane, command) => {
|
|
53
|
+
const provider = route(server);
|
|
54
|
+
if (!provider.shellCommand)
|
|
55
|
+
throw new BridgeError(503, "This terminal cannot open an interactive account login.");
|
|
56
|
+
await provider.shellCommand(server, pane, command);
|
|
57
|
+
},
|
|
52
58
|
create: (server, placement) => route(server).create(server, placement),
|
|
53
59
|
startAgent: (server, pane, agent) => route(server).startAgent(server, pane, agent),
|
|
54
60
|
paneEnv: (server, place) => route(server).paneEnv?.(server, place),
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { type Json, type Target } from "./protocol.js";
|
|
2
|
+
/** Carry the original receipt id so its dispatcher can prove compatibility
|
|
3
|
+
* even before its next poll observes the new session. Aliases have no authority. */
|
|
4
|
+
export declare function preflightWorkerRelocation(dispatch: string, target: Target): Promise<string>;
|
|
5
|
+
export declare function relocationSupport(id: string, session: string): Promise<Json>;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { continuationPlacement } from "./continuation-launch.js";
|
|
2
|
+
import { hookRequest } from "./client.js";
|
|
3
|
+
import { dispatchStatus } from "./dispatch.js";
|
|
4
|
+
import { optionalHookPeers, peerRequest } from "./peers.js";
|
|
5
|
+
import { BridgeError, object } from "./protocol.js";
|
|
6
|
+
/** Carry the original receipt id so its dispatcher can prove compatibility
|
|
7
|
+
* even before its next poll observes the new session. Aliases have no authority. */
|
|
8
|
+
export async function preflightWorkerRelocation(dispatch, target) {
|
|
9
|
+
const original = (await continuationPlacement(dispatch))?.workerDispatch ?? dispatch;
|
|
10
|
+
const query = `/v1/dispatch/relocation?id=${encodeURIComponent(original)}&session=${encodeURIComponent(target.session)}`;
|
|
11
|
+
const { peers } = await optionalHookPeers();
|
|
12
|
+
const probes = [
|
|
13
|
+
async () => ({ health: await hookRequest("/v1/health", undefined, undefined, 5_000), known: await hookRequest(query, undefined, undefined, 5_000) }),
|
|
14
|
+
...peers.map(peer => async () => ({ health: await peerRequest(peer, "/v1/health", undefined, 5_000), known: await peerRequest(peer, query, undefined, 5_000) })),
|
|
15
|
+
];
|
|
16
|
+
const answers = await Promise.all(probes.map(probe => probe().catch(() => undefined)));
|
|
17
|
+
const ownsReceipt = (answer) => answer.known.known === true || answer.known.knownDispatch === true;
|
|
18
|
+
const dispatchers = answers.filter(answer => answer && ownsReceipt(answer) && object(answer.health.capabilities).workerRelocation === 1);
|
|
19
|
+
const incompatibleDispatcher = answers.some(answer => answer && ownsReceipt(answer) && object(answer.health.capabilities).workerRelocation !== 1);
|
|
20
|
+
if (dispatchers.length !== 1 || incompatibleDispatcher)
|
|
21
|
+
throw new BridgeError(409, "Update the dispatching computer's Phren Hook first");
|
|
22
|
+
return original;
|
|
23
|
+
}
|
|
24
|
+
export async function relocationSupport(id, session) {
|
|
25
|
+
const receipts = await dispatchStatus();
|
|
26
|
+
const matched = receipts.filter(receipt => receipt.id === id || receipt.moves?.some(move => move.id === id));
|
|
27
|
+
const known = matched.some(receipt => receipt.target && "session" in receipt.target && receipt.target.session === session);
|
|
28
|
+
// A source move is durable before a worker's receiving Hook may use its id.
|
|
29
|
+
// This also repairs moves launched before workerDispatch was serialized.
|
|
30
|
+
const moved = matched.length ? undefined : await (await import("./session-move.js")).readMove(id).catch(() => undefined);
|
|
31
|
+
const knownDispatch = matched.length > 0 || !!moved?.dispatch && receipts.some(receipt => receipt.id === moved.dispatch) && moved.target && "session" in moved.target && moved.target.session === session;
|
|
32
|
+
return { known, knownDispatch: !!knownDispatch, workerRelocation: 1 };
|
|
33
|
+
}
|