@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.
- 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/git.js +82 -8
- 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/projects.js +13 -8
- 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 +46 -24
- package/dist/bridge/session-move.d.ts +28 -1
- package/dist/bridge/session-move.js +266 -25
- package/dist/bridge/socket-budget.d.ts +29 -0
- package/dist/bridge/socket-budget.js +62 -0
- 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 +16480 -14296
- package/dist/modules/registry.js +8 -8
- package/dist/tools/dispatch.js +2 -1
- package/package.json +1 -1
|
@@ -1,4 +1,11 @@
|
|
|
1
|
-
import {
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
}
|
package/dist/bridge/server.js
CHANGED
|
@@ -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,13 +61,14 @@ 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";
|
|
66
68
|
import { CodexAuthKeeper, codexAuthRefreshEnabled } from "./codex-auth-refresh.js";
|
|
67
69
|
import { localNames } from "./computer-names.js";
|
|
68
70
|
import { startStoreSyncLoop } from "../sync/store-sync.js";
|
|
71
|
+
import { SocketBudget, socketIdentity, socketKind } from "./socket-budget.js";
|
|
69
72
|
export { capabilities, capabilitiesForModules, requireRoute } from "./server-routes.js";
|
|
70
73
|
export { streamCloseReason } from "./server-stream.js";
|
|
71
74
|
export { herdrAgentName, launchSession } from "./server-launch.js";
|
|
@@ -91,6 +94,9 @@ export async function serve(version, options = {}) {
|
|
|
91
94
|
const dispatches = modules.has("conductor")
|
|
92
95
|
? new DispatchService({ computerID, validateParentTarget: target => validateTarget(target, false, true),
|
|
93
96
|
originAgent: async (origin) => {
|
|
97
|
+
const state = (await readRoleState())?.succession;
|
|
98
|
+
if (state?.side === "origin" && state.phase === "committed" && state.from.server === origin.server && state.from.pane === origin.pane && state.previous.terminal && state.previous.source)
|
|
99
|
+
return { agent: state.previous.source, terminal: state.previous.terminal };
|
|
94
100
|
const pane = findPane(await snapshot(origin.server), origin);
|
|
95
101
|
const agent = provider.safeParse(pane?.agent);
|
|
96
102
|
return agent.success && typeof pane?.terminal_id === "string" ? { agent: agent.data, terminal: pane.terminal_id } : undefined;
|
|
@@ -100,18 +106,23 @@ export async function serve(version, options = {}) {
|
|
|
100
106
|
const journal = new ActivityJournal();
|
|
101
107
|
const agentHooks = new AgentHooks(undefined, modules, path.join(bridgeRoot(), "deliveries.json"));
|
|
102
108
|
// Follows what dispatched workers do and tells the dispatching agent.
|
|
109
|
+
let succession;
|
|
103
110
|
const returns = dispatches ? new DispatchReturns({
|
|
111
|
+
localComputer: { id: computerID, name: hostname() },
|
|
112
|
+
forward: (origin, text, deliveryId) => succession?.forward(origin, text, deliveryId) ?? Promise.resolve(undefined),
|
|
104
113
|
// 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) }),
|
|
114
|
+
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
115
|
localWorkers: hookWorkers(agentHooks),
|
|
107
|
-
close: async (receipt) => {
|
|
108
|
-
const data = { target: receipt.target, dispatch: receipt.id, turn: receipt.closePending.turn };
|
|
109
|
-
if (
|
|
116
|
+
close: async (receipt, verifiedPeer) => {
|
|
117
|
+
const data = { target: receipt.target, dispatch: receipt.moves?.slice().reverse().find(move => move.to.computer)?.id ?? receipt.id, turn: receipt.closePending.turn };
|
|
118
|
+
if (receipt.computerId === computerID)
|
|
110
119
|
return closeFinishedWorker(data, handOffs);
|
|
111
|
-
const peer = (await hookPeers()).find(peer => peer.name === receipt.computer);
|
|
112
|
-
if (
|
|
113
|
-
|
|
114
|
-
|
|
120
|
+
const peer = verifiedPeer ?? (await hookPeers().catch(() => [])).find(peer => peer.name === receipt.computer);
|
|
121
|
+
if (peer)
|
|
122
|
+
return peerRequest(peer, "/v1/dispatch/close", data);
|
|
123
|
+
if (!receipt.moves?.some(move => move.to.computer) && isLocalComputer(receipt.computer))
|
|
124
|
+
return closeFinishedWorker(data, handOffs);
|
|
125
|
+
throw new BridgeError(503, "The worker's verified computer is offline.");
|
|
115
126
|
},
|
|
116
127
|
localAnswer: (target, actionId, decision) => agentHooks.answer(target, actionId, decision),
|
|
117
128
|
// A worker's request the worker's own Hook did not push reaches this Hook's phone.
|
|
@@ -135,18 +146,24 @@ export async function serve(version, options = {}) {
|
|
|
135
146
|
const sideQuestions = new SideQuestions();
|
|
136
147
|
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
148
|
const handOffs = dispatches ? new HandOffQueue({
|
|
149
|
+
forward: (target, text, deliveryId) => succession?.forward(target, text, deliveryId) ?? Promise.resolve(undefined),
|
|
138
150
|
validate: target => validateTarget(target, false, true),
|
|
139
151
|
current: async (target) => {
|
|
140
152
|
const pane = findPane(await snapshot(target.server), target);
|
|
141
153
|
const session = pane ? await paneIdentity(target.server, pane, true) : undefined;
|
|
142
154
|
return pane && session ? { session, terminal: pane.terminal_id } : undefined;
|
|
143
155
|
},
|
|
144
|
-
notify: (target, text, deliveryId, computer) => handOff({ computer, target, text, deliveryId }, { notifySender: false }),
|
|
156
|
+
notify: (target, text, deliveryId, computer) => handOff({ computer, target, text, deliveryId }, { notifySender: false, bypassConductor: true }),
|
|
145
157
|
send: sendPrompt,
|
|
146
158
|
}) : undefined;
|
|
147
159
|
// Moving a session to another agent (session-move.ts): its hand-off request
|
|
148
160
|
// takes the hand_off path, and the new agent starts through the launch path.
|
|
161
|
+
succession = dispatches ? new ConductorSuccessionService({ root, computer: { id: computerID, name: hostname() }, snapshot, validate: target => validateTarget(target, false, true),
|
|
162
|
+
isSuccessor: async (origin, id) => (await readTurn(origin.server, origin.pane))?.dispatch === id,
|
|
163
|
+
deliver: (target, text, deliveryId) => handOffs.enqueue({ target, text, deliveryId }),
|
|
164
|
+
checkWorkers: from => preflightConductorWorkers(from, computerID), }) : undefined;
|
|
149
165
|
const mover = new SessionMover({
|
|
166
|
+
succession,
|
|
150
167
|
snapshot: server => snapshot(server),
|
|
151
168
|
identity: (server, pane) => paneIdentity(server, pane, true),
|
|
152
169
|
terminal: terminalProvider(),
|
|
@@ -156,7 +173,16 @@ export async function serve(version, options = {}) {
|
|
|
156
173
|
inventory: () => launchCheckOff() ? Promise.resolve(undefined) : harnessInventoryWithin(2_500),
|
|
157
174
|
transcript: async (target) => transcriptTail(await targetTranscriptPath(target)),
|
|
158
175
|
paneAccount: (server, pane) => paneAccount(paneAccountKey(server, pane.pane_id), typeof pane.terminal_id === "string" ? pane.terminal_id : undefined)?.id,
|
|
159
|
-
paneDispatch: async (server, pane) =>
|
|
176
|
+
paneDispatch: async (server, pane) => {
|
|
177
|
+
const dispatch = (await readTurn(server, String(pane.pane_id)))?.dispatch;
|
|
178
|
+
if (!dispatch)
|
|
179
|
+
return undefined;
|
|
180
|
+
const continuation = await continuationPlacement(dispatch);
|
|
181
|
+
if (continuation)
|
|
182
|
+
return continuation.worker ? dispatch : undefined;
|
|
183
|
+
const localMove = await (await import("./session-move.js")).readMove(dispatch);
|
|
184
|
+
return localMove && !localMove.dispatch ? undefined : dispatch;
|
|
185
|
+
},
|
|
160
186
|
brief: readLaunchBrief,
|
|
161
187
|
isConductor: async (server, pane) => (await conductorPane(server, await snapshot(server)))?.pane_id === pane.pane_id,
|
|
162
188
|
envAtStart: server => terminalKind(server) === "tmux",
|
|
@@ -238,12 +264,12 @@ export async function serve(version, options = {}) {
|
|
|
238
264
|
// 256 KiB: gitboy's /memory/files asks about up to 500 paths in one query string.
|
|
239
265
|
const http = createServer({ maxHeaderSize: 256 * 1024 }, createRouteHandler({ version, modules, info, computerID, scheduleStore, scheduler, dispatches, agentHooks,
|
|
240
266
|
journal, tabActivity, contextUsage, modelCatalog, modelSwitcher, settingsSwitcher, permissionModeSwitcher, sideQuestions, accountUsage, resources, codexQuestions, launches, locatedDirectories,
|
|
241
|
-
fanoutMessages, canary, streams, returns, handOffs, inbox, mover, storePulls, gitboyWebhooks }));
|
|
267
|
+
fanoutMessages, canary, streams, returns, handOffs, inbox, mover, succession, storePulls, gitboyWebhooks }));
|
|
242
268
|
http.requestTimeout = 20_000;
|
|
243
269
|
http.headersTimeout = 10_000;
|
|
244
270
|
http.maxHeadersCount = 32;
|
|
245
271
|
const ws = new WebSocketServer({ noServer: true, maxPayload: 65_536, perMessageDeflate: false });
|
|
246
|
-
const socketPools = new
|
|
272
|
+
const socketPools = new SocketBudget();
|
|
247
273
|
http.on("upgrade", (request, socket, head) => {
|
|
248
274
|
try {
|
|
249
275
|
const url = new URL(request.url || "/", "http://phren.local");
|
|
@@ -254,20 +280,14 @@ export async function serve(version, options = {}) {
|
|
|
254
280
|
requireRoute(modules, "WS", url.pathname);
|
|
255
281
|
// Parsed before the upgrade: an invalid server name is refused as the other routes refuse it.
|
|
256
282
|
const overviewServer = url.pathname === "/v1/overview" ? selectedServer(url) : undefined;
|
|
257
|
-
//
|
|
258
|
-
//
|
|
259
|
-
|
|
260
|
-
const pool = request.headers["x-phren-client"] === "desktop" ? "desktop" : "default";
|
|
283
|
+
// Sockets are budgeted per authenticated identity (socket-budget.ts); the
|
|
284
|
+
// x-phren-client header only picks a sub-pool inside that budget.
|
|
285
|
+
const identity = socketIdentity(request), kind = socketKind(request);
|
|
261
286
|
ws.handleUpgrade(request, socket, head, client => {
|
|
262
|
-
|
|
263
|
-
socketPools.
|
|
264
|
-
members.add(client);
|
|
265
|
-
client.once("close", () => members.delete(client));
|
|
266
|
-
while (members.size > 16) {
|
|
267
|
-
const oldest = members.values().next().value;
|
|
287
|
+
client.once("close", () => socketPools.remove(client));
|
|
288
|
+
for (const oldest of socketPools.add(client, identity, kind)) {
|
|
268
289
|
oldest.close(1008, "Too many connections; reconnect");
|
|
269
290
|
oldest.terminate();
|
|
270
|
-
members.delete(oldest);
|
|
271
291
|
ws.clients.delete(oldest);
|
|
272
292
|
}
|
|
273
293
|
if (overviewServer !== undefined) {
|
|
@@ -351,6 +371,8 @@ export async function serve(version, options = {}) {
|
|
|
351
371
|
// Dispatch returns ride this tick and its shared snapshots. The returns
|
|
352
372
|
// loop throttles its own peer polls and never holds up activity.
|
|
353
373
|
void handOffs?.tick().catch(() => { });
|
|
374
|
+
void mover.reconcile().catch(() => { });
|
|
375
|
+
void succession?.reconcile().catch(() => { });
|
|
354
376
|
void returns?.tick();
|
|
355
377
|
void inbox?.tick().catch(() => { });
|
|
356
378
|
})().finally(() => { recording = false; }).catch(() => { });
|