@phren/cli 0.3.50 → 0.3.52
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/gitboy-webhooks.d.ts +25 -0
- package/dist/bridge/gitboy-webhooks.js +200 -0
- 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/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 +5 -0
- package/dist/bridge/server-routes.js +18 -3
- package/dist/bridge/server.js +7 -2
- package/dist/bridge/session-move.d.ts +10 -2
- package/dist/bridge/session-move.js +124 -12
- package/dist/bridge/store-pull.d.ts +22 -0
- package/dist/bridge/store-pull.js +62 -0
- package/dist/bridge-hook.mjs +3380 -2519
- package/dist/modules/registry.js +3 -3
- package/dist/sync/gitboy-webhook.d.ts +43 -0
- package/dist/sync/gitboy-webhook.js +119 -0
- package/dist/sync/pull-now.d.ts +11 -0
- package/dist/sync/pull-now.js +64 -0
- package/dist/sync/pull.d.ts +1 -1
- package/dist/sync/pull.js +4 -4
- package/dist/tools/dispatch.js +1 -1
- package/package.json +1 -1
|
@@ -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) };
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { IncomingMessage } from "node:http";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { ImmediatePulls } from "../sync/pull-now.js";
|
|
4
|
+
declare const identitySchema: z.ZodObject<{
|
|
5
|
+
storeId: z.ZodString;
|
|
6
|
+
repository: z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>;
|
|
7
|
+
branch: z.ZodString;
|
|
8
|
+
}, z.core.$strict>;
|
|
9
|
+
export type StorePullIdentity = z.infer<typeof identitySchema>;
|
|
10
|
+
export declare class StorePulls {
|
|
11
|
+
private readonly primary;
|
|
12
|
+
private readonly pulls;
|
|
13
|
+
constructor(primary: string, pulls?: ImmediatePulls);
|
|
14
|
+
private localStores;
|
|
15
|
+
/** A receiver's trusted local config may name an attachment ID; return the store's portable ID. */
|
|
16
|
+
request(storeId: string): string | undefined;
|
|
17
|
+
route(request: Pick<IncomingMessage, "headers">, data: Record<string, unknown>): Promise<{
|
|
18
|
+
ok: true;
|
|
19
|
+
}>;
|
|
20
|
+
stop(): void;
|
|
21
|
+
}
|
|
22
|
+
export {};
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { registeredStoreIdentity, resolveAllStores, storePathExists } from "../store-registry.js";
|
|
4
|
+
import { ImmediatePulls } from "../sync/pull-now.js";
|
|
5
|
+
import { runGitWithin } from "../sync/pull.js";
|
|
6
|
+
import { parseRemoteUrl } from "./git-hosts.js";
|
|
7
|
+
import { BridgeError } from "./protocol.js";
|
|
8
|
+
import { ownerRequest } from "./request-origin.js";
|
|
9
|
+
const identitySchema = z.object({
|
|
10
|
+
storeId: z.string().min(1).max(128),
|
|
11
|
+
repository: z.string().max(513).regex(/^[^/\s]+\/[^/\s]+$/).transform(value => value.toLowerCase()),
|
|
12
|
+
branch: z.string().min(1).max(1024),
|
|
13
|
+
}).strict();
|
|
14
|
+
export class StorePulls {
|
|
15
|
+
primary;
|
|
16
|
+
pulls;
|
|
17
|
+
constructor(primary, pulls = new ImmediatePulls()) {
|
|
18
|
+
this.primary = primary;
|
|
19
|
+
this.pulls = pulls;
|
|
20
|
+
}
|
|
21
|
+
localStores() {
|
|
22
|
+
// A synced primary entry can carry another computer's path. The Hook's configured root wins.
|
|
23
|
+
return resolveAllStores(this.primary).slice(0, 64).map(entry => {
|
|
24
|
+
const local = entry.role === "primary" ? path.resolve(this.primary) : entry.path;
|
|
25
|
+
return { ...entry, path: local, available: storePathExists(local) };
|
|
26
|
+
}).filter(entry => entry.available);
|
|
27
|
+
}
|
|
28
|
+
/** A receiver's trusted local config may name an attachment ID; return the store's portable ID. */
|
|
29
|
+
request(storeId) {
|
|
30
|
+
const store = this.localStores().find(entry => entry.id === storeId || registeredStoreIdentity(entry.path) === storeId);
|
|
31
|
+
if (!store)
|
|
32
|
+
return undefined;
|
|
33
|
+
this.pulls.request(store.path);
|
|
34
|
+
return registeredStoreIdentity(store.path);
|
|
35
|
+
}
|
|
36
|
+
async route(request, data) {
|
|
37
|
+
if (!(ownerRequest(request, data) || (request.headers["x-phren-origin"] === "peer" && data.origin === undefined))) {
|
|
38
|
+
throw new BridgeError(403, "Only the owner or a peer Hook can request a pull.");
|
|
39
|
+
}
|
|
40
|
+
const identity = identitySchema.parse(data);
|
|
41
|
+
// Attachment IDs never cross computers. Only inspect checkouts carrying the requested identity.
|
|
42
|
+
const candidates = this.localStores().filter(entry => registeredStoreIdentity(entry.path) === identity.storeId);
|
|
43
|
+
for (const store of candidates) {
|
|
44
|
+
// Local Git metadata only, bounded; follow the same tracking branch pollStore will pull.
|
|
45
|
+
const refs = await runGitWithin(1000, store.path, ["for-each-ref", "--format=%(HEAD)%09%(upstream:remotename)%09%(upstream:remoteref)", "refs/heads/"]);
|
|
46
|
+
if (!refs.ok)
|
|
47
|
+
continue;
|
|
48
|
+
const current = refs.output.split("\n").find(line => line.startsWith("*\t"));
|
|
49
|
+
const [, remote, branch] = current?.split("\t") ?? [];
|
|
50
|
+
if (!remote || remote === "." || branch !== `refs/heads/${identity.branch}`)
|
|
51
|
+
continue;
|
|
52
|
+
const url = await runGitWithin(1000, store.path, ["remote", "get-url", "--", remote]);
|
|
53
|
+
const repository = url.ok ? parseRemoteUrl(url.output)?.path.toLowerCase() : undefined;
|
|
54
|
+
if (repository !== identity.repository)
|
|
55
|
+
continue;
|
|
56
|
+
this.pulls.request(store.path);
|
|
57
|
+
return { ok: true };
|
|
58
|
+
}
|
|
59
|
+
throw new BridgeError(404, "Not found.");
|
|
60
|
+
}
|
|
61
|
+
stop() { this.pulls.stop(); }
|
|
62
|
+
}
|