@phren/cli 0.3.49 → 0.3.51
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/computers.js +5 -4
- package/dist/bridge/conductor-role.d.ts +4 -0
- package/dist/bridge/conductor-role.js +20 -1
- package/dist/bridge/dispatch-origins.d.ts +32 -0
- package/dist/bridge/dispatch-origins.js +44 -0
- package/dist/bridge/dispatch-returns.d.ts +2 -1
- package/dist/bridge/dispatch-returns.js +9 -2
- package/dist/bridge/dispatch.d.ts +5 -0
- package/dist/bridge/dispatch.js +119 -23
- package/dist/bridge/hand-off.d.ts +1 -0
- package/dist/bridge/hand-off.js +1 -1
- package/dist/bridge/install.d.ts +1 -0
- package/dist/bridge/install.js +7 -0
- package/dist/bridge/project-memory.d.ts +2 -0
- package/dist/bridge/project-memory.js +27 -13
- package/dist/bridge/request-origin.d.ts +6 -0
- package/dist/bridge/request-origin.js +6 -0
- package/dist/bridge/scoped-gateway.d.ts +3 -0
- package/dist/bridge/scoped-gateway.js +22 -4
- package/dist/bridge/server-routes.d.ts +1 -0
- package/dist/bridge/server-routes.js +10 -2
- package/dist/bridge/session-move.d.ts +10 -2
- package/dist/bridge/session-move.js +124 -12
- package/dist/bridge-hook.mjs +2280 -1720
- package/dist/cli/hooks-output.js +21 -3
- package/dist/content/citation-freshness.d.ts +29 -0
- package/dist/content/citation-freshness.js +311 -0
- package/dist/modules/registry.js +1 -1
- package/dist/shared/retrieval.d.ts +2 -1
- package/dist/shared/retrieval.js +40 -8
- package/dist/sync/gitboy-webhook.d.ts +43 -0
- package/dist/sync/gitboy-webhook.js +119 -0
- package/dist/tools/dispatch.js +1 -1
- package/dist/tools/search.js +34 -4
- package/package.json +1 -1
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { IncomingMessage } from "node:http";
|
|
2
|
+
import type { Json } from "./protocol.js";
|
|
3
|
+
/** Owner phone/desktop gateways and the owner's local CLI carry no agent or
|
|
4
|
+
* peer origin. Peer keys are forced through the peer scope, which rebuilds
|
|
5
|
+
* the request with its own origin header; MCP calls carry an agent origin. */
|
|
6
|
+
export declare function ownerRequest(request: Pick<IncomingMessage, "headers">, data: Json): boolean;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** Owner phone/desktop gateways and the owner's local CLI carry no agent or
|
|
2
|
+
* peer origin. Peer keys are forced through the peer scope, which rebuilds
|
|
3
|
+
* the request with its own origin header; MCP calls carry an agent origin. */
|
|
4
|
+
export function ownerRequest(request, data) {
|
|
5
|
+
return request.headers?.["x-phren-origin"] === undefined && data.origin === undefined;
|
|
6
|
+
}
|
|
@@ -16,6 +16,9 @@ export type Admission = {
|
|
|
16
16
|
};
|
|
17
17
|
/** Decide one request: its head (through the blank line) and the bytes after it. */
|
|
18
18
|
export declare function admitScopedRequest(scope: GatewayScope, rawHead: string, rest?: Buffer): Admission;
|
|
19
|
+
/** A computer key's forced scope rebuilds the HTTP envelope. Client headers
|
|
20
|
+
* cannot impersonate the owner gateway, and peer keys cannot open terminals. */
|
|
21
|
+
export declare function admitPeerRequest(rawHead: string, rest?: Buffer): Admission;
|
|
19
22
|
export interface ScopedIO {
|
|
20
23
|
input: Readable;
|
|
21
24
|
output: Writable;
|
|
@@ -123,6 +123,8 @@ export function admitScopedRequest(scope, rawHead, rest = Buffer.alloc(0)) {
|
|
|
123
123
|
if ("ok" in head)
|
|
124
124
|
return head;
|
|
125
125
|
const rule = findRule(scope, head);
|
|
126
|
+
if (!rule && head.path === "/v1/sessions/move")
|
|
127
|
+
return refuse(403, "Only the owner can move the conductor.");
|
|
126
128
|
if (!rule)
|
|
127
129
|
return refuse(403, `This key only permits ${DESCRIBE[scope]}.`);
|
|
128
130
|
let target = head.path;
|
|
@@ -163,6 +165,22 @@ export function admitScopedRequest(scope, rawHead, rest = Buffer.alloc(0)) {
|
|
|
163
165
|
const body = JSON.stringify(checked.data);
|
|
164
166
|
return { ok: true, request: `${rule.method} ${target} HTTP/1.1\r\nHost: phren.local\r\nContent-Type: application/json\r\nContent-Length: ${Buffer.byteLength(body)}\r\nConnection: close\r\n\r\n${body}` };
|
|
165
167
|
}
|
|
168
|
+
/** A computer key's forced scope rebuilds the HTTP envelope. Client headers
|
|
169
|
+
* cannot impersonate the owner gateway, and peer keys cannot open terminals. */
|
|
170
|
+
export function admitPeerRequest(rawHead, rest = Buffer.alloc(0)) {
|
|
171
|
+
const head = parseHead(rawHead);
|
|
172
|
+
if ("ok" in head)
|
|
173
|
+
return head;
|
|
174
|
+
if (!["GET", "POST", "DELETE"].includes(head.method) || !head.path.startsWith("/v1/"))
|
|
175
|
+
return refuse(403, "This key only permits Hook API requests.");
|
|
176
|
+
if (head.contentLength > 8 * 1024 * 1024 || rest.length !== head.contentLength)
|
|
177
|
+
return refuse(400, "Send one bounded request matching Content-Length.");
|
|
178
|
+
if (rest.length && !head.json)
|
|
179
|
+
return refuse(415, "Send Content-Type: application/json.");
|
|
180
|
+
const body = rest.toString("utf8");
|
|
181
|
+
const target = head.path + (head.query === null ? "" : `?${head.query}`);
|
|
182
|
+
return { ok: true, request: `${head.method} ${target} HTTP/1.1\r\nHost: phren.local\r\nX-Phren-Origin: peer\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: ${Buffer.byteLength(body)}\r\n\r\n${body}` };
|
|
183
|
+
}
|
|
166
184
|
const REASONS = { 400: "Bad Request", 403: "Forbidden", 408: "Request Timeout", 413: "Content Too Large", 415: "Unsupported Media Type", 503: "Service Unavailable" };
|
|
167
185
|
function httpResponse(status, error) {
|
|
168
186
|
const body = JSON.stringify({ error, code: status === 503 ? "hook-unavailable" : "scope-refused" });
|
|
@@ -172,7 +190,7 @@ function httpResponse(status, error) {
|
|
|
172
190
|
* a body within its cap, exactly that many bytes. Stops at a limit, the
|
|
173
191
|
* timeout or EOF; bytes beyond the request make it refused. */
|
|
174
192
|
function readRequest(scope, input) {
|
|
175
|
-
const bodyCap = Math.max(0, ...RULES[scope].map(rule => rule.body?.max ?? 0));
|
|
193
|
+
const bodyCap = scope === "peer" ? 8 * 1024 * 1024 : Math.max(0, ...RULES[scope].map(rule => rule.body?.max ?? 0));
|
|
176
194
|
return new Promise(resolve => {
|
|
177
195
|
let buffer = Buffer.alloc(0), headEnd = -1, wanted = 0;
|
|
178
196
|
const finish = (value) => {
|
|
@@ -214,12 +232,12 @@ function readRequest(scope, input) {
|
|
|
214
232
|
* reads a normal response.
|
|
215
233
|
*/
|
|
216
234
|
export async function scopedDispatch(scope, command, io) {
|
|
217
|
-
if (!isGatewayScope(scope))
|
|
235
|
+
if (scope !== "peer" && !isGatewayScope(scope))
|
|
218
236
|
throw new BridgeError(403, "Unknown key scope.");
|
|
219
237
|
if (command !== SCOPED_COMMAND)
|
|
220
|
-
throw new BridgeError(403, `This SSH key only permits \`${SCOPED_COMMAND}\` with ${DESCRIBE[scope]}.`);
|
|
238
|
+
throw new BridgeError(403, `This SSH key only permits \`${SCOPED_COMMAND}\` with ${scope === "peer" ? "Hook API requests" : DESCRIBE[scope]}.`);
|
|
221
239
|
const read = await readRequest(scope, io.input);
|
|
222
|
-
const admission = "head" in read ? admitScopedRequest(scope, read.head, read.rest) : refuse(read.status, read.error);
|
|
240
|
+
const admission = "head" in read ? (scope === "peer" ? admitPeerRequest(read.head, read.rest) : admitScopedRequest(scope, read.head, read.rest)) : refuse(read.status, read.error);
|
|
223
241
|
if (!admission.ok) {
|
|
224
242
|
await new Promise(done => io.output.write(httpResponse(admission.status, admission.error), () => done()));
|
|
225
243
|
return;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { ownerRequest } from "./request-origin.js";
|
|
1
2
|
import { listMoves, moveSessionFields, readMove } from "./session-move.js";
|
|
2
3
|
import { getTaskRoute, getTaskDirectoryRoute, updateTaskRoute, createTaskRoute, saveTaskRoute, launchTaskRoute } from "./task-routes.js";
|
|
3
4
|
import { ownerInboxView } from "./owner-inbox-view.js";
|
|
@@ -81,7 +82,7 @@ async function childActivity(source, session) {
|
|
|
81
82
|
export const capabilities = { transcript: true, progress: true, images: true, prompt: true, stop: true,
|
|
82
83
|
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,
|
|
83
84
|
approvals: true, questions: false, accountUsage: true, providers: ["codex", "claude", "copilot", "opencode"],
|
|
84
|
-
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, projectMemory: true, fileWrite: true, fileSearch: true, gitReview: true, memoryStoreBatch: true, gitHosts: true, projectHostToken: true };
|
|
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 };
|
|
85
86
|
export function capabilitiesForModules(snapshot) {
|
|
86
87
|
const allowed = new Set(snapshot.modules.flatMap(module => module.capabilities));
|
|
87
88
|
const result = Object.fromEntries(Object.entries(capabilities).filter(([name]) => allowed.has(name)));
|
|
@@ -774,7 +775,8 @@ export function createRouteHandler(ctx) {
|
|
|
774
775
|
// Answers once the move is checked and recorded; the hand-off and relaunch run on, and GET says where it is.
|
|
775
776
|
if (!ctx.mover)
|
|
776
777
|
throw new BridgeError(503, "This Hook cannot move sessions.");
|
|
777
|
-
|
|
778
|
+
const { origin: _origin, ...input } = data;
|
|
779
|
+
result = { ok: true, move: await ctx.mover.start(input, { owner: ownerRequest(request, data) }) };
|
|
778
780
|
}
|
|
779
781
|
else if (url.pathname === "/v1/sessions/rename") {
|
|
780
782
|
result = await renameSession(selectedServer(url), data);
|
|
@@ -860,10 +862,14 @@ export function createRouteHandler(ctx) {
|
|
|
860
862
|
: { ok: true, confirmation: await confirmAuthority(data, "phone") };
|
|
861
863
|
}
|
|
862
864
|
else if (url.pathname === "/v1/conductor/make") {
|
|
865
|
+
if (!ownerRequest(request, data))
|
|
866
|
+
throw new BridgeError(403, "Only the owner can change the conductor.");
|
|
863
867
|
// Serialized with launches, so a conductor launch and a make cannot both pass the set check.
|
|
864
868
|
result = await launches.run(async () => makeConductor(selectedServer(url), data));
|
|
865
869
|
}
|
|
866
870
|
else if (url.pathname === "/v1/conductor/stop") {
|
|
871
|
+
if (!ownerRequest(request, data))
|
|
872
|
+
throw new BridgeError(403, "Only the owner can change the conductor.");
|
|
867
873
|
result = await launches.run(async () => stopConductor(data));
|
|
868
874
|
}
|
|
869
875
|
else if (url.pathname === "/v1/sets/name") {
|
|
@@ -932,6 +938,8 @@ export function createRouteHandler(ctx) {
|
|
|
932
938
|
else {
|
|
933
939
|
if (url.pathname === "/v1/workspaces/launch") {
|
|
934
940
|
result = await launches.run(async () => {
|
|
941
|
+
if (data.role === "conductor" && !ownerRequest(request, data))
|
|
942
|
+
throw new BridgeError(403, "Only the owner can change the conductor.");
|
|
935
943
|
if (data.role === "conductor" && !modules.has("conductor"))
|
|
936
944
|
throw new BridgeError(404, disabledHint("conductor"));
|
|
937
945
|
if (data.agentFolder === true && (data.role === "conductor" || data.project !== undefined || (data.cwd !== undefined && data.cwd !== "") || data.worktree != null)) {
|
|
@@ -97,6 +97,7 @@ declare const moveRecordSchema: z.ZodObject<{
|
|
|
97
97
|
"new-chat": "new-chat";
|
|
98
98
|
replace: "replace";
|
|
99
99
|
}>>;
|
|
100
|
+
modeForced: z.ZodOptional<z.ZodLiteral<"conductor">>;
|
|
100
101
|
handedOffTo: z.ZodOptional<z.ZodObject<{
|
|
101
102
|
target: z.ZodUnion<readonly [z.ZodObject<{
|
|
102
103
|
server: z.ZodString;
|
|
@@ -289,7 +290,7 @@ export declare function fallbackHandoff(input: {
|
|
|
289
290
|
label?: string;
|
|
290
291
|
}): string;
|
|
291
292
|
/** The hand-off file: who moved where and when, the body, then what Phren saw. */
|
|
292
|
-
export declare function handoffDocument(record: MoveRecord, body: string, observed: string, at: string): string;
|
|
293
|
+
export declare function handoffDocument(record: MoveRecord, body: string, observed: string, at: string, conductor?: boolean): string;
|
|
293
294
|
/** The new agent's first prompt: the whole hand-off when it fits the brief, else where to read it. */
|
|
294
295
|
export declare function continuePrompt(document: string, file: string): string;
|
|
295
296
|
export interface MoverDeps {
|
|
@@ -342,11 +343,18 @@ export declare class SessionMover {
|
|
|
342
343
|
private sleep;
|
|
343
344
|
private get poll();
|
|
344
345
|
/** Checks the move can happen, records it and starts it. Refuses before anything is typed. */
|
|
345
|
-
start(input: unknown
|
|
346
|
+
start(input: unknown, caller?: {
|
|
347
|
+
owner?: boolean;
|
|
348
|
+
}): Promise<MoveRecord>;
|
|
346
349
|
/** For tests: the move under way in a pane, until it settles. */
|
|
347
350
|
settled(server: string, pane: string): Promise<void> | undefined;
|
|
348
351
|
private update;
|
|
349
352
|
private run;
|
|
353
|
+
/** An ordinary move never acquires permission to stop a conductor merely
|
|
354
|
+
* because the owner promoted its source while the hand-off was running. */
|
|
355
|
+
private checkPromotion;
|
|
356
|
+
/** Uses the same durable prompt path as the hand-off and its first brief. */
|
|
357
|
+
private conductorNotice;
|
|
350
358
|
/** The agent's own hand-off, or why there is none. Fails only when the session itself went away. */
|
|
351
359
|
private askForHandoff;
|
|
352
360
|
private fallback;
|
|
@@ -23,11 +23,12 @@ import { promisify } from "node:util";
|
|
|
23
23
|
import { z } from "zod";
|
|
24
24
|
import { logger } from "../logger.js";
|
|
25
25
|
import { quoted, withOriginalBrief } from "./account-failover.js";
|
|
26
|
+
import { recordedConductor, runsAgent, transferConductor } from "./conductor-role.js";
|
|
26
27
|
import { DEFAULT_ACCOUNT } from "./claude-accounts.js";
|
|
27
|
-
import { DISPATCH_HARNESSES, moveToSchema } from "./dispatch.js";
|
|
28
|
+
import { DISPATCH_HARNESSES, moveToSchema, repointDispatchOrigins } from "./dispatch.js";
|
|
28
29
|
import { hasUsable } from "./harnesses.js";
|
|
29
30
|
import { findPane } from "./herdr.js";
|
|
30
|
-
import { briefId, briefRoot, writeLaunchBrief } from "./launch-brief.js";
|
|
31
|
+
import { briefArrival, briefId, briefRoot, writeLaunchBrief } from "./launch-brief.js";
|
|
31
32
|
import { atomic, BridgeError, bridgeRoot, startingTargetSchema, targetSchema } from "./protocol.js";
|
|
32
33
|
import { publicAssistant } from "./schedule-watch.js";
|
|
33
34
|
const run = promisify(execFile);
|
|
@@ -50,6 +51,7 @@ const moveRecordSchema = z.object({
|
|
|
50
51
|
from: z.object({ target: targetSchema, account: z.string().max(64).optional(), label: z.string().max(200).optional() }).strict(),
|
|
51
52
|
to: moveToSchema,
|
|
52
53
|
mode: z.enum(["replace", "new-chat"]).optional(),
|
|
54
|
+
modeForced: z.literal("conductor").optional(),
|
|
53
55
|
handedOffTo: z.object({ target: z.union([targetSchema, startingTargetSchema]) }).strict().optional(),
|
|
54
56
|
handedOffFrom: z.object({ target: targetSchema, title: z.string().max(200) }).strict().optional(),
|
|
55
57
|
cwd: z.string().max(4096),
|
|
@@ -78,17 +80,23 @@ export function movesRoot() { return path.join(bridgeRoot(), "moves"); }
|
|
|
78
80
|
const recordFile = (id) => path.join(movesRoot(), `${z.string().uuid().parse(id)}.json`);
|
|
79
81
|
/** The hand-off sits beside the new agent's brief, in a folder Claude is given read access to. */
|
|
80
82
|
export const handoffPath = (id) => path.join(briefRoot(), id, "handoff.md");
|
|
83
|
+
// A committed hand-over remains observable even while its status file cannot
|
|
84
|
+
// be written. Key by full path because one process may access multiple stores.
|
|
85
|
+
const landedMoves = new Map();
|
|
81
86
|
let writes = Promise.resolve();
|
|
82
87
|
async function saveMove(record) {
|
|
83
88
|
const run = writes.then(async () => {
|
|
84
89
|
await mkdir(movesRoot(), { recursive: true, mode: 0o700 });
|
|
85
90
|
await atomic(recordFile(record.id), moveRecordSchema.parse(record));
|
|
91
|
+
landedMoves.delete(recordFile(record.id));
|
|
86
92
|
});
|
|
87
93
|
writes = run.catch(() => undefined);
|
|
88
94
|
return run;
|
|
89
95
|
}
|
|
90
96
|
export async function readMove(id) {
|
|
91
97
|
const file = recordFile(id);
|
|
98
|
+
if (landedMoves.has(file))
|
|
99
|
+
return structuredClone(landedMoves.get(file));
|
|
92
100
|
const info = await lstat(file).catch(() => undefined);
|
|
93
101
|
if (!info?.isFile() || info.size > MAX_RECORD_BYTES)
|
|
94
102
|
return undefined;
|
|
@@ -336,7 +344,7 @@ export function fallbackHandoff(input) {
|
|
|
336
344
|
return input.original ? withOriginalBrief(head, input.original, Number.MAX_SAFE_INTEGER, "the original brief file") : head;
|
|
337
345
|
}
|
|
338
346
|
/** The hand-off file: who moved where and when, the body, then what Phren saw. */
|
|
339
|
-
export function handoffDocument(record, body, observed, at) {
|
|
347
|
+
export function handoffDocument(record, body, observed, at, conductor = false) {
|
|
340
348
|
return [
|
|
341
349
|
`# Hand-off from ${harnessName({ harness: record.from.target.source, account: record.from.account })} to ${harnessName(record.to)}`,
|
|
342
350
|
"",
|
|
@@ -345,6 +353,7 @@ export function handoffDocument(record, body, observed, at) {
|
|
|
345
353
|
...(record.mode === "new-chat" ? ["## Previous chat", "",
|
|
346
354
|
`Title: ${record.from.label ?? record.from.target.source}`,
|
|
347
355
|
"Target (JSON, for opening the old chat):", "```json", JSON.stringify(record.from.target), "```", ""] : []),
|
|
356
|
+
...(conductor ? ["## Conductor role", "", "You will become the conductor when the Hook confirms the hand-over; until then don't dispatch or answer workers.", ""] : []),
|
|
348
357
|
body.trim(),
|
|
349
358
|
"",
|
|
350
359
|
observed,
|
|
@@ -376,11 +385,13 @@ export class SessionMover {
|
|
|
376
385
|
sleep(ms) { return (this.deps.sleep ?? (value => new Promise(resolve => setTimeout(resolve, value))))(ms); }
|
|
377
386
|
get poll() { return this.deps.pollMs ?? 2_000; }
|
|
378
387
|
/** Checks the move can happen, records it and starts it. Refuses before anything is typed. */
|
|
379
|
-
async start(input) {
|
|
388
|
+
async start(input, caller = {}) {
|
|
380
389
|
const data = moveRequestSchema.parse(input);
|
|
381
390
|
if (data.id) {
|
|
382
391
|
const earlier = await readMove(data.id);
|
|
383
392
|
if (earlier) {
|
|
393
|
+
if (earlier.modeForced === "conductor" && !caller.owner)
|
|
394
|
+
throw new BridgeError(403, "Only the owner can move the conductor.");
|
|
384
395
|
const from = earlier.from.target;
|
|
385
396
|
if (from.server !== data.target.server || from.pane !== data.target.pane || from.session !== data.target.session)
|
|
386
397
|
throw new BridgeError(409, "This move id was already used for another session.");
|
|
@@ -401,8 +412,15 @@ export class SessionMover {
|
|
|
401
412
|
const session = await this.deps.identity(target.server, pane).catch(() => undefined);
|
|
402
413
|
if (session && session !== target.session)
|
|
403
414
|
throw new BridgeError(409, "That pane runs another conversation now.");
|
|
404
|
-
|
|
405
|
-
|
|
415
|
+
const holdsRole = await this.deps.isConductor?.(target.server, pane) ?? false;
|
|
416
|
+
if (holdsRole && !caller.owner)
|
|
417
|
+
throw new BridgeError(403, "Only the owner can move the conductor.");
|
|
418
|
+
const conductor = holdsRole ? await recordedConductor() : undefined;
|
|
419
|
+
if (holdsRole && (!conductor || conductor.server !== target.server || conductor.pane !== target.pane)) {
|
|
420
|
+
throw new BridgeError(409, "The conductor changed during the move; nothing was transferred.");
|
|
421
|
+
}
|
|
422
|
+
if (conductor && to.harness === "copilot")
|
|
423
|
+
throw new BridgeError(400, "Copilot cannot run as a conductor.");
|
|
406
424
|
const account = target.source === "claude" ? this.deps.paneAccount?.(target.server, pane) ?? DEFAULT_ACCOUNT : undefined;
|
|
407
425
|
const sameHarness = to.harness === target.source && (to.harness !== "claude" || (to.account ?? account) === account);
|
|
408
426
|
if (sameHarness && !to.model && !to.effort)
|
|
@@ -423,11 +441,11 @@ export class SessionMover {
|
|
|
423
441
|
const label = [pane.label, pane.title, pane.terminal_title_stripped, pane.agent_name].find(value => typeof value === "string" && value.trim() && !/^\d+$/.test(value));
|
|
424
442
|
const at = new Date(this.now).toISOString();
|
|
425
443
|
const record = { id: data.id ?? randomUUID(), state: "handing-off", createdAt: at, updatedAt: at,
|
|
426
|
-
mode: data.mode, from: { target, ...(account ? { account } : {}), ...(label ? { label: label.slice(0, 200) } : {}) }, to, cwd,
|
|
444
|
+
mode: conductor ? "new-chat" : data.mode, ...(conductor ? { modeForced: "conductor" } : {}), from: { target, ...(account ? { account } : {}), ...(label ? { label: label.slice(0, 200) } : {}) }, to, cwd,
|
|
427
445
|
...(dispatch && briefId.safeParse(dispatch).success ? { dispatch } : {}) };
|
|
428
446
|
await saveMove(record);
|
|
429
447
|
const key = `${target.server}\0${target.pane}`;
|
|
430
|
-
const work = this.run(record, data.handoffTimeoutMs ?? DEFAULT_HANDOFF_MS).finally(() => this.running.delete(key));
|
|
448
|
+
const work = this.run(record, data.handoffTimeoutMs ?? DEFAULT_HANDOFF_MS, conductor).finally(() => this.running.delete(key));
|
|
431
449
|
this.running.set(key, work);
|
|
432
450
|
return record;
|
|
433
451
|
}
|
|
@@ -437,8 +455,9 @@ export class SessionMover {
|
|
|
437
455
|
Object.assign(record, change, { updatedAt: new Date(this.now).toISOString() });
|
|
438
456
|
await saveMove(record);
|
|
439
457
|
}
|
|
440
|
-
async run(record, handoffMs) {
|
|
458
|
+
async run(record, handoffMs, conductor) {
|
|
441
459
|
const from = record.from.target;
|
|
460
|
+
let roleTransferred = false;
|
|
442
461
|
try {
|
|
443
462
|
// What the checkout and the agent's processes look like before it stops.
|
|
444
463
|
const pane = findPane(await this.deps.snapshot(from.server), placeOf(from));
|
|
@@ -450,7 +469,7 @@ export class SessionMover {
|
|
|
450
469
|
const body = "text" in written ? written.text : record.mode === "new-chat"
|
|
451
470
|
? `## 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.`
|
|
452
471
|
: fallback;
|
|
453
|
-
const document = handoffDocument(record, body, observedState(git, processes), new Date(this.now).toISOString());
|
|
472
|
+
const document = handoffDocument(record, body, observedState(git, processes), new Date(this.now).toISOString(), !!conductor);
|
|
454
473
|
const file = handoffPath(record.id);
|
|
455
474
|
const prompt = briefText(continuePrompt(document, file));
|
|
456
475
|
// The folder is the new agent's brief folder; the hand-off is written into it, whole.
|
|
@@ -458,12 +477,51 @@ export class SessionMover {
|
|
|
458
477
|
await atomic(file, document);
|
|
459
478
|
await this.update(record, { state: record.mode === "new-chat" ? "launching" : "exiting", handoff: { path: file, source: "text" in written ? "agent" : "fallback",
|
|
460
479
|
...("reason" in written ? { reason: written.reason.slice(0, 300) } : {}), chars: document.length } });
|
|
480
|
+
await this.checkPromotion(record);
|
|
461
481
|
if (record.mode !== "new-chat") {
|
|
462
482
|
const exit = await this.exit(record);
|
|
463
483
|
await this.update(record, { state: "launching", exit });
|
|
464
484
|
await this.deps.afterExit?.(from.server, from.pane).catch(() => undefined);
|
|
465
485
|
}
|
|
466
486
|
const launched = await this.relaunch(record, prompt);
|
|
487
|
+
await this.checkPromotion(record);
|
|
488
|
+
if (conductor) {
|
|
489
|
+
try {
|
|
490
|
+
if (launched.linkPending || !launched.target || !("session" in launched.target))
|
|
491
|
+
throw new Error("The new conductor conversation is not linked; the hand-over was not confirmed.");
|
|
492
|
+
const confirmedTarget = launched.target;
|
|
493
|
+
let accepted = false;
|
|
494
|
+
for (const until = this.now + 30_000; this.now < until; await this.sleep(this.poll)) {
|
|
495
|
+
const arrival = (await briefArrival(record.id))?.accepted?.target;
|
|
496
|
+
if (arrival && Object.keys(confirmedTarget).every(key => arrival[key] === confirmedTarget[key])) {
|
|
497
|
+
accepted = true;
|
|
498
|
+
break;
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
if (!accepted)
|
|
502
|
+
throw new Error("The new conductor's hand-off brief was not confirmed within 30 seconds.");
|
|
503
|
+
const place = record.paneTarget;
|
|
504
|
+
const next = place && findPane(await this.deps.snapshot(place.server), place);
|
|
505
|
+
if (!place || !runsAgent(next) || next.agent !== record.to.harness)
|
|
506
|
+
throw new Error("The new agent is no longer running in its launched pane.");
|
|
507
|
+
if (!["idle", "working"].includes(String(next.agent_status)))
|
|
508
|
+
throw new Error(`The new conductor is not ready (${String(next.agent_status)}); answer its startup dialog before retrying.`);
|
|
509
|
+
if (typeof next.terminal_id !== "string" || !next.terminal_id)
|
|
510
|
+
throw new Error("The new pane has no terminal identity for worker returns.");
|
|
511
|
+
const origin = { server: place.server, workspace: place.workspace, tab: place.tab, pane: place.pane,
|
|
512
|
+
agent: record.to.harness, terminal: next.terminal_id };
|
|
513
|
+
await transferConductor(conductor, place.server, next, launched.target && "session" in launched.target ? launched.target.session : undefined, commit => repointDispatchOrigins(conductor, origin, commit));
|
|
514
|
+
roleTransferred = true;
|
|
515
|
+
const notice = await this.conductorNotice(record, "The Hook confirmed the hand-over; you are now the conductor. Continue coordinating the owner's work and existing workers.", "confirmed");
|
|
516
|
+
if (notice)
|
|
517
|
+
record.notice = notice;
|
|
518
|
+
}
|
|
519
|
+
catch (error) {
|
|
520
|
+
if (error instanceof BridgeError)
|
|
521
|
+
throw error;
|
|
522
|
+
throw new Error(`Conductor role transfer failed. The old chat was left running. ${error instanceof Error ? error.message : String(error)}`);
|
|
523
|
+
}
|
|
524
|
+
}
|
|
467
525
|
await this.update(record, { state: "moved", movedAt: new Date(this.now).toISOString(), ...launched,
|
|
468
526
|
...(record.mode === "new-chat" ? {
|
|
469
527
|
...(launched.target ? { handedOffTo: { target: launched.target } } : {}),
|
|
@@ -473,12 +531,59 @@ export class SessionMover {
|
|
|
473
531
|
}
|
|
474
532
|
catch (error) {
|
|
475
533
|
const message = (error instanceof Error ? error.message : String(error)).replace(/[\x00-\x1f\x7f]+/g, " ");
|
|
534
|
+
if (roleTransferred) {
|
|
535
|
+
// update() has already populated the complete moved record. The role
|
|
536
|
+
// and worker routes committed; a later status save cannot undo them.
|
|
537
|
+
record.state = "moved";
|
|
538
|
+
record.notice = `Conductor moved with worker routing, but saving move status failed: ${message}`.slice(0, 500);
|
|
539
|
+
delete record.error;
|
|
540
|
+
landedMoves.set(recordFile(record.id), record);
|
|
541
|
+
while (landedMoves.size > MAX_MOVES)
|
|
542
|
+
landedMoves.delete(landedMoves.keys().next().value);
|
|
543
|
+
await saveMove(record).catch(() => undefined);
|
|
544
|
+
logger.warn("move", record.notice);
|
|
545
|
+
return;
|
|
546
|
+
}
|
|
547
|
+
if (conductor && record.paneTarget) {
|
|
548
|
+
record.notice = await this.conductorNotice(record, "The conductor hand-over failed; you are not the conductor. The previous conductor keeps coordinating.", "failed")
|
|
549
|
+
?? "The new chat was told the conductor hand-over failed; it is not the conductor.";
|
|
550
|
+
}
|
|
476
551
|
const stopped = record.exit !== undefined;
|
|
477
552
|
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}.` : "";
|
|
478
553
|
await this.update(record, { state: "failed", error: `${message}${hint}`.slice(0, 500) }).catch(() => undefined);
|
|
479
554
|
logger.warn("move", `Moving pane ${from.pane} to ${record.to.harness} failed: ${message}`);
|
|
480
555
|
}
|
|
481
556
|
}
|
|
557
|
+
/** An ordinary move never acquires permission to stop a conductor merely
|
|
558
|
+
* because the owner promoted its source while the hand-off was running. */
|
|
559
|
+
async checkPromotion(record) {
|
|
560
|
+
if (record.modeForced === "conductor")
|
|
561
|
+
return;
|
|
562
|
+
const current = await recordedConductor();
|
|
563
|
+
if (current?.server === record.from.target.server && current.pane === record.from.target.pane) {
|
|
564
|
+
throw new BridgeError(409, "The pane became the conductor during the move; nothing was changed.");
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
/** Uses the same durable prompt path as the hand-off and its first brief. */
|
|
568
|
+
async conductorNotice(record, text, outcome) {
|
|
569
|
+
try {
|
|
570
|
+
const target = targetSchema.safeParse(record.target);
|
|
571
|
+
if (target.success) {
|
|
572
|
+
const sent = await this.deps.deliver(target.data, text, `move-${record.id}-conductor-${outcome}`);
|
|
573
|
+
if (sent.state === "failed" || (sent.ok !== true && sent.queued !== true) || (sent.delivered === false && sent.queued !== true)) {
|
|
574
|
+
throw new Error(String(sent.error ?? "delivery was not confirmed"));
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
else if (record.paneTarget) {
|
|
578
|
+
await this.deps.terminal.prompt(record.paneTarget.server, record.paneTarget.pane, text);
|
|
579
|
+
return `The conductor hand-over ${outcome} notice was typed to the new pane; conversation delivery is unconfirmed.`;
|
|
580
|
+
}
|
|
581
|
+
return undefined;
|
|
582
|
+
}
|
|
583
|
+
catch (error) {
|
|
584
|
+
return `The conductor hand-over ${outcome}, but the new chat's notice could not be delivered: ${error instanceof Error ? error.message : String(error)}`.slice(0, 500);
|
|
585
|
+
}
|
|
586
|
+
}
|
|
482
587
|
/** The agent's own hand-off, or why there is none. Fails only when the session itself went away. */
|
|
483
588
|
async askForHandoff(record, handoffMs) {
|
|
484
589
|
const from = record.from.target;
|
|
@@ -542,13 +647,16 @@ export class SessionMover {
|
|
|
542
647
|
const pane = findPane(await this.deps.snapshot(from.server), placeOf(from));
|
|
543
648
|
// A turn still running (a hand-off that ran late) is stopped first, as Esc in the terminal would.
|
|
544
649
|
if (pane?.agent_status === "working") {
|
|
650
|
+
await this.checkPromotion(record);
|
|
545
651
|
await this.deps.terminal.sendKeys(from.server, from.pane, ["esc"]).catch(() => undefined);
|
|
546
652
|
await this.sleep(1_000);
|
|
547
653
|
}
|
|
654
|
+
await this.checkPromotion(record);
|
|
548
655
|
await this.deps.terminal.prompt(from.server, from.pane, EXIT_COMMANDS[from.source] ?? "/exit").catch(() => undefined);
|
|
549
656
|
if (await gone(exitMs))
|
|
550
657
|
return "clean";
|
|
551
658
|
for (let n = 0; n < 2; n++) {
|
|
659
|
+
await this.checkPromotion(record);
|
|
552
660
|
await this.deps.terminal.sendKeys(from.server, from.pane, ["ctrl+c"]).catch(() => undefined);
|
|
553
661
|
await this.sleep(500);
|
|
554
662
|
}
|
|
@@ -558,6 +666,7 @@ export class SessionMover {
|
|
|
558
666
|
const agent = foregroundPids.filter(pid => pid !== shellPid);
|
|
559
667
|
const kill = this.deps.kill ?? ((pid, signal) => process.kill(pid, signal));
|
|
560
668
|
for (const signal of ["SIGTERM", "SIGKILL"]) {
|
|
669
|
+
await this.checkPromotion(record);
|
|
561
670
|
for (const pid of agent) {
|
|
562
671
|
try {
|
|
563
672
|
kill(pid, signal);
|
|
@@ -584,7 +693,8 @@ export class SessionMover {
|
|
|
584
693
|
...(record.to.model ? { model: record.to.model } : {}), ...(record.to.effort ? { effort: record.to.effort } : {}), ...(account ? { account } : {}),
|
|
585
694
|
brief: { id: record.id, text: prompt }, ...(samePane ? {} : { workspaceId: from.workspace }) };
|
|
586
695
|
const into = samePane ? { workspaceId: from.workspace, tabId: from.tab, paneId: from.pane } : undefined;
|
|
587
|
-
|
|
696
|
+
await this.checkPromotion(record);
|
|
697
|
+
const launched = await this.deps.launch(from.server, data, { ...(into ? { into } : {}), ...(record.dispatch && record.modeForced !== "conductor" ? { dispatchId: record.dispatch } : {}) });
|
|
588
698
|
// Keep the launched location even if delivering its first prompt fails.
|
|
589
699
|
const paneTarget = targetSchema.omit({ session: true }).parse({ server: from.server,
|
|
590
700
|
workspace: launched.workspaceId, tab: launched.tabId, pane: launched.paneId, source: record.to.harness });
|
|
@@ -610,8 +720,10 @@ export class SessionMover {
|
|
|
610
720
|
throw new Error(`${record.mode === "new-chat" ? "New chat" : "Target"} started but did not receive the hand-off. The launched pane was left open. ${reason}`);
|
|
611
721
|
}
|
|
612
722
|
}
|
|
613
|
-
if (!samePane && record.mode !== "new-chat")
|
|
723
|
+
if (!samePane && record.mode !== "new-chat") {
|
|
724
|
+
await this.checkPromotion(record);
|
|
614
725
|
await this.deps.terminal.closePane(from.server, from.pane).catch(() => undefined);
|
|
726
|
+
}
|
|
615
727
|
// The account the new agent runs under, also when the move named none.
|
|
616
728
|
const to = account ? { ...record.to, account } : record.to;
|
|
617
729
|
return { to, placement: samePane ? "same-pane" : "adjacent-pane", ...await this.newTarget(record, launched, record.to.harness) };
|