@phren/cli 0.3.57 → 0.3.59

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/README.md +1 -1
  2. package/dist/bridge/account-add.d.ts +30 -0
  3. package/dist/bridge/account-add.js +125 -19
  4. package/dist/bridge/account-failover.d.ts +9 -2
  5. package/dist/bridge/account-failover.js +1 -1
  6. package/dist/bridge/account-policy.d.ts +44 -0
  7. package/dist/bridge/account-policy.js +103 -0
  8. package/dist/bridge/account-pools.d.ts +35 -0
  9. package/dist/bridge/account-pools.js +171 -0
  10. package/dist/bridge/account-usage.d.ts +18 -0
  11. package/dist/bridge/account-usage.js +57 -1
  12. package/dist/bridge/agent-hook-callback.d.ts +6 -0
  13. package/dist/bridge/agent-hook-callback.js +10 -2
  14. package/dist/bridge/agent-hook-stores.d.ts +3 -0
  15. package/dist/bridge/agent-hook-stores.js +13 -0
  16. package/dist/bridge/agent-hooks.d.ts +12 -2
  17. package/dist/bridge/agent-hooks.js +41 -4
  18. package/dist/bridge/claude-account-setup.d.ts +16 -0
  19. package/dist/bridge/claude-account-setup.js +46 -2
  20. package/dist/bridge/claude-accounts.d.ts +9 -0
  21. package/dist/bridge/claude-accounts.js +53 -15
  22. package/dist/bridge/claude-credits.d.ts +5 -1
  23. package/dist/bridge/claude-credits.js +37 -29
  24. package/dist/bridge/command.js +12 -3
  25. package/dist/bridge/computer-identity.d.ts +4 -2
  26. package/dist/bridge/computer-identity.js +7 -3
  27. package/dist/bridge/conductor-group.d.ts +1 -1
  28. package/dist/bridge/conductor-group.js +2 -2
  29. package/dist/bridge/conductor-sets.d.ts +6 -0
  30. package/dist/bridge/conductor-sets.js +8 -2
  31. package/dist/bridge/dispatch-command.js +22 -0
  32. package/dist/bridge/dispatch-returns.d.ts +23 -0
  33. package/dist/bridge/dispatch-returns.js +57 -0
  34. package/dist/bridge/dispatch.d.ts +26 -4
  35. package/dist/bridge/dispatch.js +100 -11
  36. package/dist/bridge/git-host-gitlab.js +2 -1
  37. package/dist/bridge/hand-off-queue.d.ts +71 -0
  38. package/dist/bridge/hand-off-queue.js +38 -0
  39. package/dist/bridge/harnesses.d.ts +12 -0
  40. package/dist/bridge/harnesses.js +20 -4
  41. package/dist/bridge/helper.d.ts +54 -0
  42. package/dist/bridge/helper.js +186 -0
  43. package/dist/bridge/herdr.js +6 -2
  44. package/dist/bridge/hook-fast.d.ts +3 -0
  45. package/dist/bridge/hook-fast.js +10 -2
  46. package/dist/bridge/move-computers.d.ts +15 -1
  47. package/dist/bridge/move-computers.js +123 -26
  48. package/dist/bridge/prompt-deliveries.d.ts +29 -1
  49. package/dist/bridge/prompt-deliveries.js +146 -10
  50. package/dist/bridge/schedule-watch.js +17 -3
  51. package/dist/bridge/server-routes.d.ts +4 -0
  52. package/dist/bridge/server-routes.js +66 -6
  53. package/dist/bridge/server.js +8 -2
  54. package/dist/bridge/session-move.d.ts +59 -1
  55. package/dist/bridge/session-move.js +266 -18
  56. package/dist/bridge/simulator-stream.d.ts +118 -0
  57. package/dist/bridge/simulator-stream.js +284 -0
  58. package/dist/bridge/simulators.d.ts +31 -0
  59. package/dist/bridge/simulators.js +126 -40
  60. package/dist/bridge/speech-live.js +132 -22
  61. package/dist/bridge/task-routes.d.ts +16 -16
  62. package/dist/bridge/terminal-herdr.js +6 -1
  63. package/dist/bridge/terminal-tmux.js +9 -5
  64. package/dist/bridge/terminal.d.ts +9 -2
  65. package/dist/bridge/transcript-claude.d.ts +3 -0
  66. package/dist/bridge/transcript-claude.js +175 -29
  67. package/dist/bridge/transcript-preview.d.ts +11 -2
  68. package/dist/bridge/transcript-preview.js +90 -8
  69. package/dist/bridge/turn-records.d.ts +19 -0
  70. package/dist/bridge/turn-records.js +78 -3
  71. package/dist/bridge-hook.mjs +12129 -10324
  72. package/dist/cli-registry.js +2 -2
  73. package/dist/content/citation.d.ts +4 -0
  74. package/dist/content/citation.js +21 -21
  75. package/dist/data/task-contract.d.ts +4 -4
  76. package/dist/governance/policy.js +5 -2
  77. package/dist/index.js +1 -1
  78. package/dist/modules/registry.js +4 -4
  79. package/dist/project-config.d.ts +14 -0
  80. package/dist/project-config.js +40 -1
  81. package/dist/tools/helper.d.ts +3 -0
  82. package/dist/tools/helper.js +44 -0
  83. package/package.json +1 -1
@@ -35,7 +35,7 @@ import { hasUsable } from "./harnesses.js";
35
35
  import { findPane } from "./herdr.js";
36
36
  import { briefArrival, briefId, briefRoot, assertUnusedLaunchId, writeLaunchBrief } from "./launch-brief.js";
37
37
  import { atomic, BridgeError, bridgeRoot, object, startingTargetSchema, targetSchema } from "./protocol.js";
38
- import { publicAssistant } from "./schedule-watch.js";
38
+ import { finalTurnFromLines, isClaudeUsageLimit, publicAssistant } from "./schedule-watch.js";
39
39
  const run = promisify(execFile);
40
40
  export { moveToSchema };
41
41
  export const moveRequestSchema = z.object({
@@ -45,8 +45,10 @@ export const moveRequestSchema = z.object({
45
45
  /** `resume` switches a Claude conversation to another account on this
46
46
  * computer without a hand-off: the transcript is copied into the target
47
47
  * account's home and the same conversation resumes there (`claude --resume`),
48
- * so an account at its usage limit can still switch. */
49
- continuation: z.enum(["handoff", "resume"]).default("handoff"),
48
+ * so an account at its usage limit can still switch. `summary-by-target` (a move to another computer):
49
+ * the source is not asked for a hand-off; the new agent there builds one from the copied conversation.
50
+ * A source whose last turn ended on its usage limit is moved this way without asking. */
51
+ continuation: z.enum(["handoff", "resume", "summary-by-target"]).default("handoff"),
50
52
  /** Kept on a retry: the same id returns the move already under way. */
51
53
  id: z.string().uuid().optional(),
52
54
  /** How long the agent gets to write its hand-off before Phren builds one. */
@@ -65,7 +67,9 @@ const moveRecordSchema = z.object({
65
67
  accountChoice: z.string().max(400).optional(),
66
68
  project: projectName.optional(),
67
69
  mode: z.enum(["replace", "new-chat"]).optional(),
68
- continuation: z.literal("resume").optional(),
70
+ /** `resume`: the same conversation under another account here. `summary-by-target`: the source was out of
71
+ * usage, so the agent on the other computer builds the hand-off from the copied conversation. */
72
+ continuation: z.enum(["resume", "summary-by-target"]).optional(),
69
73
  modeForced: z.literal("conductor").optional(),
70
74
  handedOffTo: z.object({ computer: z.string().optional(), target: z.union([targetSchema, startingTargetSchema]) }).strict().optional(),
71
75
  handedOffFrom: z.object({ target: targetSchema, title: z.string().max(200) }).strict().optional(),
@@ -88,6 +92,15 @@ const moveRecordSchema = z.object({
88
92
  /** The slash command each harness ends its interactive session with. */
89
93
  const EXIT_COMMANDS = { claude: "/exit", codex: "/quit", copilot: "/exit", opencode: "/exit", phren: "/exit" };
90
94
  const HARNESS_NAMES = { claude: "Claude", codex: "Codex", opencode: "OpenCode", copilot: "Copilot", phren: "phren agent" };
95
+ /** Refuses a Claude account on this computer that the pools of the pane's project or this computer rule out. */
96
+ async function refuseOutsidePools(pane, account) {
97
+ const cwd = String(pane.foreground_cwd || pane.cwd || "");
98
+ if (!path.isAbsolute(cwd))
99
+ return;
100
+ const refused = await (await import("./move-computers.js")).localPoolRefusal(cwd, account);
101
+ if (refused)
102
+ throw new BridgeError(409, `Claude account ${account} may not take this session: ${refused}.`, { code: "account_pool" });
103
+ }
91
104
  const MOVE_KEEP_MS = 7 * 24 * 60 * 60 * 1000;
92
105
  const MAX_MOVES = 256;
93
106
  const MAX_RECORD_BYTES = 32_768;
@@ -110,6 +123,16 @@ async function saveMove(record) {
110
123
  writes = run.catch(() => undefined);
111
124
  return run;
112
125
  }
126
+ /** The mark that a move's agent was sent its one Escape, beside the move's record, so a Hook restart does not
127
+ * send a second. Written before the key goes: a crash between the two counts as sent. */
128
+ const interruptFile = (id) => path.join(movesRoot(), `${z.string().uuid().parse(id)}.interrupted`);
129
+ async function markInterrupted(id) {
130
+ await mkdir(movesRoot(), { recursive: true, mode: 0o700 });
131
+ await atomic(interruptFile(id), { at: new Date().toISOString() });
132
+ }
133
+ const interruptMarked = (id) => lstat(interruptFile(id)).then(info => info.isFile(), () => false);
134
+ /** How long after the interrupt's Escape the move's own exit waits before sending another. */
135
+ const INTERRUPT_SETTLE_MS = 5_000;
113
136
  export async function readMove(id) {
114
137
  const file = recordFile(id);
115
138
  if (landedMoves.has(file))
@@ -131,7 +154,7 @@ export async function listMoves(now = Date.now()) {
131
154
  .sort((a, b) => b.createdAt.localeCompare(a.createdAt));
132
155
  const settled = (record) => record.state === "moved" || record.state === "failed";
133
156
  const stale = records.filter((record, index) => settled(record) && (index >= MAX_MOVES || now - Date.parse(record.updatedAt) > MOVE_KEEP_MS));
134
- await Promise.all(stale.map(record => rm(recordFile(record.id), { force: true }).catch(() => undefined)));
157
+ await Promise.all(stale.flatMap(record => [recordFile(record.id), interruptFile(record.id)].map(file => rm(file, { force: true }).catch(() => undefined))));
135
158
  return records.filter(record => !stale.includes(record));
136
159
  }
137
160
  /** The move that took the agent out of `target`'s pane: a target with a
@@ -364,6 +387,70 @@ export function fallbackHandoff(input) {
364
387
  // Written to a file, so the brief is never cut here.
365
388
  return input.original ? withOriginalBrief(head, input.original, Number.MAX_SAFE_INTEGER, "the original brief file") : head;
366
389
  }
390
+ /** Whether a Claude conversation's last turn ended on its subscription's usage limit (Claude's own
391
+ * rate-limit row): its agent cannot answer a hand-off request. */
392
+ export function sourceOutOfUsage(lines, source) {
393
+ return source === "claude" && isClaudeUsageLimit(finalTurnFromLines(lines, "claude").error);
394
+ }
395
+ /** Room left in a cross-computer brief for the copied conversation, once the rest of the hand-off is in. */
396
+ const TRANSCRIPT_MARGIN = 2_000;
397
+ /** What of the original dispatch brief is kept ahead of the conversation: the oldest turns, which state the task, go first. */
398
+ const ORIGINAL_RESERVE = 8_000;
399
+ /**
400
+ * The hand-off for a source that does not write one (its account is out of usage, or the owner asked), for a
401
+ * fresh agent on the target computer to build itself: what happened, then as much of the conversation as fits
402
+ * in `room` characters, newest messages kept, oldest first. The target agent writes its own summary from it first.
403
+ */
404
+ export function targetSummaryBody(input) {
405
+ const head = [
406
+ input.exhausted
407
+ ? `The previous agent (${input.from}) is out of usage on its account, so it could not write a hand-off. Phren copied its conversation instead, below, for you to build one from.`
408
+ : `The owner moved the previous agent (${input.from}) here without asking it for a hand-off. Phren copied its conversation instead, below, for you to build one from.`,
409
+ "",
410
+ "First, from this conversation, write yourself a short hand-off: the owner's goal, what is done, what is half done, and the next steps. Then check this checkout against it and continue from there; do not start over.",
411
+ "",
412
+ ...(input.dispatch ? [`It was working on dispatch ${input.dispatch}${input.label ? ` ("${input.label}")` : ""}.`, ""] : []),
413
+ ];
414
+ const summary = (kept) => `The last ${kept} of its ${input.entries.length} messages, oldest first:`;
415
+ const kept = [];
416
+ // The original brief as it will be sent (redacted, paths replaced) and only then cut to its share, so a cut
417
+ // never lands inside a credential the redaction had to see whole.
418
+ const sentOriginal = input.original === undefined ? undefined : input.prepare ? input.prepare(input.original) : input.original;
419
+ const capNote = `\n[The original brief was cut to ${ORIGINAL_RESERVE} characters; the full text is in the dispatching computer's brief.]`;
420
+ const original = sentOriginal === undefined || sentOriginal.length <= ORIGINAL_RESERVE ? sentOriginal
421
+ : `${sentOriginal.slice(0, ORIGINAL_RESERVE - capNote.length)}${capNote}`;
422
+ // The list's own heading, and room for the original brief and its cut note, are counted up front.
423
+ const reserve = original ? original.length + 200 : 0;
424
+ let used = head.join("\n").length + summary(input.entries.length).length + 2 + reserve;
425
+ for (const entry of [...input.entries].reverse()) {
426
+ // One long message never takes the whole room: its end is what was said last.
427
+ const sent = input.prepare ? input.prepare(entry.text) : entry.text;
428
+ const text = sent.length > 6_000 ? `…${sent.slice(-6_000)}` : sent;
429
+ const block = quoted(entry.role === "owner" ? "Prompt to it" : "Its reply", text);
430
+ const size = block.join("\n").length + 1;
431
+ if (used + size > input.room)
432
+ break;
433
+ kept.unshift(block);
434
+ used += size;
435
+ }
436
+ const lines = [...head];
437
+ if (!kept.length)
438
+ lines.push(input.entries.length ? "Its conversation did not fit beside the rest of this hand-off; ask the owner where it stood." : "Its conversation could not be read; ask the owner where it stood.", "");
439
+ else
440
+ lines.push(summary(kept.length), "", ...kept.flat());
441
+ const body = lines.join("\n");
442
+ // The original brief takes what room is left, cut with a note when it doesn't fit.
443
+ return original ? withOriginalBrief(body, original, input.room, "the dispatching computer's brief") : body;
444
+ }
445
+ /**
446
+ * The prompt another computer gets: full inline text only, since the peer cannot read this Hook's brief path.
447
+ * Commit ids and the complete hand-off are kept, credentials redacted in place rather than through the lossy
448
+ * approval/log summarizer.
449
+ */
450
+ function peerPrompt(record, document) {
451
+ const safeDocument = document.replaceAll(record.cwd, "<source checkout>");
452
+ return redactPeerHandoff(briefText(`Continue the owner's work from this hand-off. This is a different checkout: local uncommitted files and running processes were not copied. Check its branch and files before proceeding.\n\n${safeDocument}`));
453
+ }
367
454
  /** The hand-off file: who moved where and when, the body, then what Phren saw. */
368
455
  export function handoffDocument(record, body, observed, at, conductor = false) {
369
456
  return [
@@ -399,11 +486,26 @@ const DEFAULT_HANDOFF_MS = 240_000;
399
486
  export class SessionMover {
400
487
  deps;
401
488
  cancelled = new Set();
489
+ /** Moves this process is waiting on: their hand-off request was handed to the queue, and the wait for the
490
+ * agent's answer is not over (it answered, the wait ran out, or the owner aborted). Only these are interrupted:
491
+ * a move whose request was never sent (summary-by-target, or not yet), or one this process no longer runs
492
+ * (the Hook restarted), has no request an Escape would let in. */
493
+ asking = new Set();
494
+ /** Per move, the hand-off's end and an interrupt's check-and-send, one at a time. */
495
+ lifecycles = new Map();
402
496
  admissions = new Set();
403
497
  running = new Map();
404
498
  constructor(deps) {
405
499
  this.deps = deps;
406
500
  }
501
+ lifecycle(id, work) {
502
+ const result = (this.lifecycles.get(id) ?? Promise.resolve()).then(work);
503
+ const tail = result.catch(() => undefined);
504
+ this.lifecycles.set(id, tail);
505
+ void tail.then(() => { if (this.lifecycles.get(id) === tail)
506
+ this.lifecycles.delete(id); });
507
+ return result;
508
+ }
407
509
  get now() { return (this.deps.now ?? Date.now)(); }
408
510
  sleep(ms) { return (this.deps.sleep ?? (value => new Promise(resolve => setTimeout(resolve, value))))(ms); }
409
511
  get poll() { return this.deps.pollMs ?? 2_000; }
@@ -445,6 +547,9 @@ export class SessionMover {
445
547
  const to = { ...data.to };
446
548
  if (!peer)
447
549
  delete to.computer;
550
+ // Another computer's agent builds the hand-off; on this one, an exhausted account switches with `resume`.
551
+ if (data.continuation === "summary-by-target" && !peer)
552
+ throw new BridgeError(409, "summary-by-target continues on another computer; on this one, switch accounts with continuation resume.");
448
553
  const active = (await listMoves(this.now)).find(record => record.from.target.server === target.server && record.from.target.pane === target.pane
449
554
  && record.state !== "moved" && record.state !== "failed");
450
555
  if (active || [...this.running.keys()].some(key => key === `${target.server}\0${target.pane}`))
@@ -489,6 +594,7 @@ export class SessionMover {
489
594
  throw new BridgeError(400, "Choose another Claude account to switch to.");
490
595
  if (!claudeHome(to.account))
491
596
  throw new BridgeError(409, `No Claude account "${to.account}" on this computer.`, { code: "account_unavailable" });
597
+ await refuseOutsidePools(pane, to.account);
492
598
  if (!this.deps.copyConversation)
493
599
  throw new BridgeError(503, "This Hook cannot switch accounts.");
494
600
  await this.deps.copyConversation(target, claudeHome(to.account), true);
@@ -505,6 +611,10 @@ export class SessionMover {
505
611
  const cwd = String(pane.foreground_cwd || pane.cwd || "");
506
612
  if (!path.isAbsolute(cwd))
507
613
  throw new BridgeError(409, "The pane's folder is unknown, so the new agent could not start there.");
614
+ // A Claude account named on this computer keeps to the pools too (a peer's is checked by checkMovePeer).
615
+ // Unnamed, the new Claude runs under the pane's own account (relaunch), else default: that one is checked.
616
+ if (!peer && data.continuation !== "resume" && to.harness === "claude")
617
+ await refuseOutsidePools(pane, to.account ?? account ?? DEFAULT_ACCOUNT);
508
618
  let project;
509
619
  let accountChoice;
510
620
  let computerId;
@@ -541,7 +651,7 @@ export class SessionMover {
541
651
  const at = new Date(this.now).toISOString();
542
652
  const resume = data.continuation === "resume";
543
653
  const record = { id: data.id ?? randomUUID(), state: resume ? "exiting" : "handing-off", createdAt: at, updatedAt: at,
544
- ...(project ? { project } : {}), mode: conductor || peer ? "new-chat" : data.mode, ...(resume ? { continuation: "resume" } : {}), ...(conductor ? { modeForced: "conductor" } : {}), from: { target, ...(account ? { account } : {}), ...(label ? { label: label.slice(0, 200) } : {}) }, to, cwd, ...(computerId ? { computerId } : {}), ...(peer?.fingerprint ? { computerFingerprint: peer.fingerprint } : {}), ...(accountChoice ? { accountChoice } : {}),
654
+ ...(project ? { project } : {}), mode: conductor || peer ? "new-chat" : data.mode, ...(resume ? { continuation: "resume" } : data.continuation === "summary-by-target" ? { continuation: "summary-by-target" } : {}), ...(conductor ? { modeForced: "conductor" } : {}), from: { target, ...(account ? { account } : {}), ...(label ? { label: label.slice(0, 200) } : {}) }, to, cwd, ...(computerId ? { computerId } : {}), ...(peer?.fingerprint ? { computerFingerprint: peer.fingerprint } : {}), ...(accountChoice ? { accountChoice } : {}),
545
655
  ...(dispatch && briefId.safeParse(dispatch).success ? { dispatch } : {}), ...(workerDispatch ? { workerDispatch } : {}) };
546
656
  await assertUnusedLaunchId(record.id);
547
657
  if (conductor && peer) {
@@ -570,12 +680,53 @@ export class SessionMover {
570
680
  const pids = pane ? (await this.deps.terminal.processes(from.server, from.pane).catch(() => undefined))?.foregroundPids ?? [] : [];
571
681
  const [git, processes] = await Promise.all([(this.deps.git ?? readGitState)(record.cwd).catch(() => undefined),
572
682
  (this.deps.processesBelow ?? processesBelow)(pids).catch(() => [])]);
573
- const written = await this.askForHandoff(record, handoffMs);
574
- const fallback = "text" in written ? undefined : await this.fallback(record, written.reason);
575
- const body = "text" in written ? written.text : record.mode === "new-chat"
576
- ? `## 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.`
577
- : fallback;
578
- const document = handoffDocument(record, body, observedState(git, processes, !peer), new Date(this.now).toISOString(), !!conductor);
683
+ // A source out of usage cannot answer a hand-off request: on another computer, the new agent builds it.
684
+ const requested = record.continuation === "summary-by-target";
685
+ const lines = peer ? await this.deps.transcript(from).catch(() => undefined) : [];
686
+ // Asked for by name, the move never launches an agent with no conversation to build from.
687
+ if (requested && !lines?.length)
688
+ throw new BridgeError(409, "The conversation could not be read, so the agent on the other computer would have nothing to build a hand-off from; the old chat remains open.");
689
+ const exhausted = !!peer && sourceOutOfUsage(lines ?? [], from.source);
690
+ const byTarget = !!peer && (requested || exhausted);
691
+ if (byTarget && !requested)
692
+ await this.update(record, { continuation: "summary-by-target" });
693
+ const written = byTarget ? { reason: `${exhausted ? "its account is out of usage" : "the owner asked"}, so the agent on ${peer.name} builds the hand-off from the copied conversation.` }
694
+ : await this.askForHandoff(record, handoffMs);
695
+ // The wait is over. Its request, if still untyped, is taken back first: typed later it would ask the old
696
+ // agent (left running by a new-chat move) for a hand-off nobody reads. Then an interrupt already checking
697
+ // finishes, and none starts after (the move goes on to exit or launch, where an Escape would hit the exit
698
+ // command or the agent's last turn).
699
+ if (this.asking.has(record.id))
700
+ await this.withdrawRequest(record, "The move stopped waiting for this hand-off.");
701
+ await this.lifecycle(record.id, async () => { this.asking.delete(record.id); });
702
+ const observed = observedState(git, processes, !peer), at = new Date(this.now).toISOString();
703
+ let body;
704
+ if (byTarget) {
705
+ const original = record.dispatch ? await this.deps.brief?.(record.dispatch).catch(() => undefined) : undefined;
706
+ const entries = conversationEntries(lines ?? [], from.source);
707
+ const fit = (room) => targetSummaryBody({ from: harnessName({ harness: from.source, account: record.from.account }), exhausted,
708
+ entries, room, prepare: text => redactPeerHandoff(text.replaceAll(record.cwd, "<source checkout>")), ...(original ? { original } : {}),
709
+ ...(record.dispatch ? { dispatch: record.dispatch } : {}), ...(record.from.label ? { label: record.from.label } : {}) });
710
+ // What fits beside the rest of the hand-off in the one brief the other computer gets, measured as sent:
711
+ // the checkout path replaced and credentials redacted, either of which can lengthen the text. Messages
712
+ // are prepared that way before they are counted; the refit only catches what the rest of the brief adds.
713
+ let room = PROMPT_LIMIT - peerPrompt(record, handoffDocument(record, "", observed, at, !!conductor)).length - TRANSCRIPT_MARGIN;
714
+ body = fit(room);
715
+ for (let tries = 0; tries < 4; tries++) {
716
+ const over = peerPrompt(record, handoffDocument(record, body, observed, at, !!conductor)).length - PROMPT_LIMIT;
717
+ if (over <= 0)
718
+ break;
719
+ room -= over + 500;
720
+ body = fit(room);
721
+ }
722
+ }
723
+ else {
724
+ const fallback = "text" in written ? undefined : await this.fallback(record, written.reason);
725
+ body = "text" in written ? written.text : record.mode === "new-chat"
726
+ ? `## 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.`
727
+ : fallback;
728
+ }
729
+ const document = handoffDocument(record, body, observed, at, !!conductor);
579
730
  await this.assertNotAborted(record);
580
731
  const file = handoffPath(record.id);
581
732
  const prompt = briefText(continuePrompt(document, file));
@@ -653,6 +804,12 @@ export class SessionMover {
653
804
  }
654
805
  catch (error) {
655
806
  const message = (error instanceof Error ? error.message : String(error)).replace(/[\x00-\x1f\x7f]+/g, " ");
807
+ // A wait that failed (the pane went missing for a moment, Herdr did not answer) leaves the old agent running
808
+ // with the request still queued for it: taken back, as when the wait ends, and no interrupt after.
809
+ if (this.asking.has(record.id)) {
810
+ await this.withdrawRequest(record, "The move failed before the agent wrote its hand-off.");
811
+ await this.lifecycle(record.id, async () => { this.asking.delete(record.id); });
812
+ }
656
813
  if (roleTransferred) {
657
814
  // update() has already populated the complete moved record. The role
658
815
  // and worker routes committed; a later status save cannot undo them.
@@ -684,6 +841,72 @@ export class SessionMover {
684
841
  logger.warn("move", `Moving pane ${from.pane} to ${record.to.harness} failed: ${message}`);
685
842
  }
686
843
  }
844
+ /**
845
+ * "Stop <agent> and hand off now": Escape to the old agent only while the move's hand-off request is
846
+ * still held for it (queued behind the step it is on, not yet typed), so the step stops and the request
847
+ * goes in, and never into the hand-off the agent is writing. Checked and sent under the hand-off queue's
848
+ * lock (`whileQueued`), which is what types the request, and under the move's own lifecycle lock, which is
849
+ * what ends the hand-off wait: the move cannot go on to exit or launch between the check and the key.
850
+ * `state` says why it did not: the request is being or was typed (`typed`), the agent is writing its
851
+ * hand-off (`writing`), the move is past it, or the pane runs another agent now (`replaced`).
852
+ */
853
+ async interrupt(id, queue, escape) {
854
+ const record = await readMove(id);
855
+ if (!record)
856
+ throw new BridgeError(404, "No move with that id is recorded.");
857
+ if (record.state !== "handing-off" || !this.asking.has(id))
858
+ return { interrupted: false, state: "finished" };
859
+ // Without the queue the request was typed the moment it was sent: it is never held.
860
+ if (!queue)
861
+ return { interrupted: false, state: "typed" };
862
+ const from = record.from.target;
863
+ let answer = { interrupted: true };
864
+ const result = await queue.whileQueued(`move-${id}`, from, row => this.lifecycle(id, async () => {
865
+ // A move that left the hand-off (it answered, timed out and is exiting, or was aborted) needs no Escape.
866
+ if ((await readMove(id))?.state !== "handing-off" || !this.asking.has(id)) {
867
+ answer = { interrupted: false, state: "finished" };
868
+ return;
869
+ }
870
+ // No request waiting yet: there is nothing an Escape would let in.
871
+ if (!row) {
872
+ answer = { interrupted: false, state: "idle" };
873
+ return;
874
+ }
875
+ // One Escape per move, across Hook restarts: a second (a double tap, a retry) would land on the stopped
876
+ // agent's empty input, where Claude and Codex take Esc Esc as "go back to an earlier message".
877
+ if (await interruptMarked(id))
878
+ return;
879
+ // An agent not on a step has nothing to stop: its request goes in at the queue's next look.
880
+ const pane = findPane(await this.deps.snapshot(from.server), placeOf(from));
881
+ if (!pane || !["working", "blocked", "waiting", "unknown"].includes(String(pane.agent_status))) {
882
+ answer = { interrupted: false, state: "idle" };
883
+ return;
884
+ }
885
+ // Only the agent the request is for: the same harness, terminal and conversation (the one the queued row
886
+ // followed to, when the pane's conversation changed in the same terminal). The owner may have started
887
+ // another in the pane since; one whose conversation can't be read is not taken for it.
888
+ const session = await this.deps.identity(from.server, pane).catch(() => undefined);
889
+ const wanted = row.session ?? from.session;
890
+ if (pane.agent !== from.source || (wanted && session !== wanted)
891
+ || (typeof pane.terminal_id === "string" && pane.terminal_id !== row.terminal)) {
892
+ answer = { interrupted: false, state: "replaced" };
893
+ return;
894
+ }
895
+ // Marked before it goes, so a crash after the key counts as sent; an Escape known to have failed
896
+ // clears the mark, leaving the next tap free to try again.
897
+ await markInterrupted(id);
898
+ try {
899
+ await (escape ?? (target => this.deps.terminal.sendKeys(target.server, target.pane, ["esc"])))(from);
900
+ }
901
+ catch (error) {
902
+ await rm(interruptFile(id), { force: true }).catch(() => undefined);
903
+ throw error;
904
+ }
905
+ }));
906
+ if (!result.ran)
907
+ return { interrupted: false, state: result.state === "delivered" ? "writing" : result.state === "failed" ? "finished" : "typed" };
908
+ return answer;
909
+ }
687
910
  async abort(id) {
688
911
  const record = await readMove(id);
689
912
  if (!record)
@@ -697,20 +920,29 @@ export class SessionMover {
697
920
  }
698
921
  else if (record.state !== "handing-off" && record.state !== "failed")
699
922
  throw new BridgeError(409, "This launch may already exist; reconcile it before aborting.");
923
+ // Marked first, so a move not yet at its request never sends it (askForHandoff checks). Its request, if
924
+ // already queued and still untyped, is taken back (even one a restarted Hook no longer waits on); then, after
925
+ // an interrupt already checking and before any other, no Escape goes for an aborted move.
700
926
  this.cancelled.add(id);
927
+ if (record.state === "handing-off")
928
+ await this.withdrawRequest(record, "The owner aborted the move.");
929
+ await this.lifecycle(id, async () => { this.asking.delete(id); });
701
930
  await this.update(record, { state: "failed", error: "The owner aborted this uncommitted move; the original chat keeps its role." });
702
931
  return record;
703
932
  }
933
+ /** Takes the move's hand-off request back while it is still queued. Outside the move's lifecycle lock: an
934
+ * interrupt holds the queue's lock while it waits for that one, so this must not wait the other way round. */
935
+ async withdrawRequest(record, reason) {
936
+ await this.deps.withdraw?.(record.from.target, `move-${record.id}`, reason).catch(error => {
937
+ logger.warn("move", `Taking back the hand-off request of move ${record.id} failed: ${error instanceof Error ? error.message : String(error)}`);
938
+ });
939
+ }
704
940
  async assertNotAborted(record) {
705
941
  if (this.cancelled.has(record.id) || (await readMove(record.id))?.state === "failed" || record.modeForced === "conductor" && record.to.computer && (await this.deps.succession.status(record.id)).phase === "aborted")
706
942
  throw new BridgeError(409, "This uncommitted move was aborted; no conductor role was transferred.");
707
943
  }
708
944
  async continueOnPeer(record, peer, project, document) {
709
- // Full inline text only: the peer cannot read this Hook's brief path.
710
- // Preserve commit ids and the complete hand-off, redacting credentials
711
- // in place instead of applying the lossy approval/log summarizer to it.
712
- const safeDocument = document.replaceAll(record.cwd, "<source checkout>");
713
- const remotePrompt = redactPeerHandoff(briefText(`Continue the owner's work from this hand-off. This is a different checkout: local uncommitted files and running processes were not copied. Check its branch and files before proceeding.\n\n${safeDocument}`));
945
+ const remotePrompt = peerPrompt(record, document);
714
946
  if (remotePrompt.length > PROMPT_LIMIT)
715
947
  throw new BridgeError(409, "The hand-off is too long to send in full to another computer; the old chat remains open.");
716
948
  const checked = await (await import("./move-computers.js")).checkMovePeer(peer, project, record.to, record.modeForced === "conductor");
@@ -855,18 +1087,27 @@ export class SessionMover {
855
1087
  async askForHandoff(record, handoffMs) {
856
1088
  const from = record.from.target;
857
1089
  const deadline = this.now + handoffMs;
1090
+ // An abort before, during or after the request was sent: it is not sent, or taken back (run's catch).
1091
+ const aborted = () => { if (this.cancelled.has(record.id))
1092
+ throw new BridgeError(409, "This uncommitted move was aborted; no conductor role was transferred."); };
1093
+ aborted();
858
1094
  try {
859
1095
  const sent = await this.deps.deliver(from, handoffRequest(record.id, record.to, record.mode), `move-${record.id}`);
860
1096
  // A lost delivery acknowledgement can still have reached the agent;
861
1097
  // its marked transcript reply is authoritative for the normal window.
862
1098
  if (sent.state !== "uncertain" && sent.ok !== true && sent.queued !== true)
863
1099
  return { reason: `the request could not be delivered (${String(sent.error ?? sent.state ?? "not confirmed")}).` };
1100
+ // From here the owner may stop the agent's step so the request goes in (`interrupt`, which the queue
1101
+ // answers `typed` or `writing` once it went).
1102
+ this.asking.add(record.id);
864
1103
  }
865
1104
  catch (error) {
866
1105
  return { reason: `the request could not be delivered (${error instanceof Error ? error.message : String(error)}).` };
867
1106
  }
868
1107
  while (this.now < deadline) {
1108
+ aborted();
869
1109
  await this.sleep(this.poll);
1110
+ aborted();
870
1111
  const pane = findPane(await this.deps.snapshot(from.server), placeOf(from));
871
1112
  if (!pane || pane.agent !== from.source)
872
1113
  throw new BridgeError(409, "The session ended before it wrote its hand-off; nothing was started.");
@@ -943,7 +1184,14 @@ export class SessionMover {
943
1184
  await this.sleep(Math.min(this.poll, 500));
944
1185
  }
945
1186
  };
946
- const pane = findPane(await this.deps.snapshot(from.server), placeOf(from));
1187
+ let pane = findPane(await this.deps.snapshot(from.server), placeOf(from));
1188
+ // Just after the owner's interrupt sent its Escape, the pane can still read working: wait that out and look
1189
+ // again, rather than a second Escape at once, which Claude and Codex take as "go back to an earlier message".
1190
+ const since = await readFile(interruptFile(record.id), "utf8").then(text => Date.now() - Date.parse(String(JSON.parse(text).at)), () => Infinity);
1191
+ if (pane?.agent_status === "working" && since < INTERRUPT_SETTLE_MS) {
1192
+ await this.sleep(INTERRUPT_SETTLE_MS - since);
1193
+ pane = findPane(await this.deps.snapshot(from.server), placeOf(from));
1194
+ }
947
1195
  // A turn still running (a hand-off that ran late) is stopped first, as Esc in the terminal would.
948
1196
  if (pane?.agent_status === "working") {
949
1197
  await this.checkPromotion(record);
@@ -0,0 +1,118 @@
1
+ import type { Readable } from "node:stream";
2
+ import { type Json } from "./protocol.js";
3
+ /**
4
+ * `WS /v1/simulators/stream?udid=&fps=&size=&quality=`: one booted
5
+ * simulator's screen, live. The native helper (native/simcast.swift) reads the
6
+ * device's framebuffer through CoreSimulator, as `simctl io` does, and writes
7
+ * each changed frame as a length-prefixed JPEG; this side forwards them.
8
+ *
9
+ * Why JPEG frames from the framebuffer, not the alternatives:
10
+ * - `simctl io screenshot` took about 1.1 s a shot (Xcode 27.1, M1 Max),
11
+ * which is today's 1 fps poll and no more.
12
+ * - `simctl io recordVideo` writes a QuickTime movie that is only readable
13
+ * once finalized, so it cannot feed a live socket.
14
+ * - ScreenCaptureKit on the Simulator window needs a Screen Recording grant
15
+ * (which macOS re-asks for monthly), captures the window chrome, and stops
16
+ * when the window is minimized; the framebuffer needs no grant.
17
+ * - H.264 halves the bytes but ties frames together: a dropped frame corrupts
18
+ * the picture until the next keyframe, so "always the latest frame" would
19
+ * need keyframe requests across the socket. Every JPEG stands alone, so a
20
+ * frame the phone can't take yet is simply replaced by the next one.
21
+ * - The helper sends only frames whose framebuffer changed (its IOSurface
22
+ * seed moved): a still screen costs nothing on the wire.
23
+ *
24
+ * Frames: a text `{ type: "start", format: "jpeg", fps, size, quality, ack }`,
25
+ * then one binary message per frame, each a whole JPEG. A phone that asks
26
+ * with `ack=1` sends `{ type: "ack" }` for each frame it receives, and at
27
+ * most two frames are unacknowledged: the SSH channel and TCP buffers between
28
+ * here and the phone then never hold more than that, so what the phone shows
29
+ * is at most two frames old however slow the link. Without it, a frame is
30
+ * done once written to the gateway's socket. When the stream
31
+ * ends, the socket closes with the reason (1008 for a bad request, 1011 when
32
+ * capture failed); the phone then falls back to `/v1/simulators/screenshot`.
33
+ * Closing the socket stops the helper. Taps and keys stay on
34
+ * `/v1/simulators/action`.
35
+ */
36
+ /** A JPEG larger than this is a broken helper, not a frame. */
37
+ export declare const MAX_FRAME_BYTES: number;
38
+ /** The wire budget: about 24 Mbit/s, so animations at full rate on Wi-Fi, and
39
+ * the phone asks for a smaller `size` on a slower link. */
40
+ export declare const STREAM_BYTES_PER_SECOND: number;
41
+ /** Each stream runs its own helper; a few phones may watch at once. */
42
+ export declare const MAX_STREAMS = 4;
43
+ export interface StreamOptions {
44
+ udid: string;
45
+ fps: number;
46
+ size: number;
47
+ quality: number;
48
+ ack: boolean;
49
+ }
50
+ /** Frames in flight when the phone acknowledges them: one decoding on the
51
+ * phone while the next crosses the network. */
52
+ export declare const ACK_WINDOW = 2;
53
+ /** The query, validated before anything runs. */
54
+ export declare function streamOptions(query: URLSearchParams): StreamOptions;
55
+ /** Splits the helper's stdout into frames: a 4-byte big-endian length, then
56
+ * that many bytes. Pipes deliver arbitrary chunks, so a frame may span many. */
57
+ export declare class FrameReader {
58
+ private buffered;
59
+ private bytes;
60
+ push(chunk: Buffer): Buffer[];
61
+ }
62
+ /** Sends the newest frame only. At most `window` frames are in flight (until
63
+ * written, or until acknowledged when `acked`); frames that arrive meanwhile
64
+ * replace the one waiting, so a slow link sees fewer frames, never older
65
+ * ones. A byte budget, refilled continuously with one second of burst, bounds
66
+ * the bitrate the same way. */
67
+ export declare class LatestFrame {
68
+ private send;
69
+ private options;
70
+ private now;
71
+ private waiting?;
72
+ private inFlight;
73
+ private tokens;
74
+ private refilled;
75
+ private timer?;
76
+ private closed;
77
+ sent: number;
78
+ dropped: number;
79
+ constructor(send: (frame: Buffer, done: (error?: Error) => void) => void, options?: {
80
+ bytesPerSecond?: number;
81
+ window?: number;
82
+ acked?: boolean;
83
+ }, now?: () => number);
84
+ offer(frame: Buffer): void;
85
+ /** The phone has a frame; an acknowledgement it owes nothing for is ignored. */
86
+ ack(): void;
87
+ close(): void;
88
+ private get bytesPerSecond();
89
+ private pump;
90
+ }
91
+ /** The phone's socket, or a test double. */
92
+ export interface StreamClient {
93
+ readonly readyState: number;
94
+ send(data: string | Buffer, options: {
95
+ binary: boolean;
96
+ }, done?: (error?: Error) => void): void;
97
+ close(code?: number, reason?: string): void;
98
+ once(event: "close" | "error", listener: () => void): unknown;
99
+ on(event: "message", listener: (data: Buffer, isBinary: boolean) => void): unknown;
100
+ }
101
+ /** The capture process, or a test double. */
102
+ export interface CaptureProcess {
103
+ readonly stdout: Readable | null;
104
+ readonly stderr: Readable | null;
105
+ kill(signal?: NodeJS.Signals): boolean;
106
+ once(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): unknown;
107
+ once(event: "error", listener: (error: Error) => void): unknown;
108
+ }
109
+ export interface StreamDeps {
110
+ booted: () => Promise<Json[]>;
111
+ helper: () => Promise<string>;
112
+ spawn: (binary: string, args: string[]) => CaptureProcess;
113
+ platform: () => NodeJS.Platform;
114
+ bytesPerSecond?: number;
115
+ }
116
+ /** Streams running now, for tests and health. */
117
+ export declare function activeSimulatorStreams(): number;
118
+ export declare function streamSimulator(client: StreamClient, query: URLSearchParams, deps?: StreamDeps): Promise<void>;