@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
@@ -3,7 +3,9 @@ import { peerFingerprint } from "./dispatch-hosts.js";
3
3
  import { redactPeerHandoff } from "./peer-handoff.js";
4
4
  import { relocationSupport } from "./worker-relocation.js";
5
5
  import { continuationIntent, continuationLaunchSchema, continuationPlacement, launchContinuation } from "./continuation-launch.js";
6
- import { addClaudeAccount } from "./account-add.js";
6
+ import { addClaudeAccount, signInClaudeAccount } from "./account-add.js";
7
+ import { ACCOUNT_ROLES, isAccountRole, setAccountSettings, setComputerAllowedPools } from "./account-pools.js";
8
+ import { claudeHome } from "./claude-accounts.js";
7
9
  import { localMoveAvailability, moveComputers } from "./move-computers.js";
8
10
  import { ownerRequest, requestPeer } from "./request-origin.js";
9
11
  import { listMoves, moveSessionFields, readMove } from "./session-move.js";
@@ -43,7 +45,7 @@ import { locateProject } from "./locate.js";
43
45
  import { gitStatus } from "./git.js";
44
46
  import { gitRoot, launchDirectory, repositoryBranch, webServers, withGitReadDeadline } from "./projects.js";
45
47
  import { approvalDecisions, BridgeError, bridgeRoot, MAX_FRAME, object, objects, PROTOCOL, provider, serverName, targetFromURL, targetSchema } from "./protocol.js";
46
- import { bootedSimulators, simulatorAct, simulatorApps, simulatorScreenshot } from "./simulators.js";
48
+ import { bootedSimulators, simulatorAct, simulatorApps, simulatorDevices, simulatorScreenshot } from "./simulators.js";
47
49
  import { childAgentTree, historicalImage, publicChildAgents, refreshTranscript, runningChildAgents, targetTranscriptPath } from "./transcripts.js";
48
50
  import { listUploads, removeUpload, saveUpload, uploadImage } from "./uploads.js";
49
51
  import { currentModel, currentStep } from "./steps.js";
@@ -89,7 +91,7 @@ async function childActivity(source, session) {
89
91
  export const capabilities = { transcript: true, progress: true, images: true, prompt: true, stop: true,
90
92
  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,
91
93
  approvals: true, questions: false, accountUsage: true, providers: ["codex", "claude", "copilot", "opencode"],
92
- files: true, repositoryFiles: true, fileResolution: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, setLink: true, ownerInbox: true, workerReports: true, queuedHandOff: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, codeFiles: true, overviewStream: true, speech: true, speechTimestamps: true, speechTimestampStream: true, speechLive: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, deliveryFrames: true, paneDeliveries: true, resources: true, sudo: true, sudoOutcome: true, previewDeltas: true, quickChat: true, agentFolder: true, launchPermissionMode: true, sessionMove: true, moveNewChat: true, moveConductor: true, moveToComputer: true, moveConductorToComputer: true, moveResume: true, claudeAccountAdd: true, workerRelocation: 1, projectMemory: true, fileWrite: true, fileSearch: true, gitReview: true, memoryStoreBatch: true, gitHosts: true, projectHostToken: true };
94
+ 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", simulatorStream: process.platform === "darwin", simulatorDevices: process.platform === "darwin", simulatorDrag: process.platform === "darwin", code: true, codeFiles: true, overviewStream: true, speech: true, speechTimestamps: true, speechTimestampStream: true, speechLive: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, deliveryFrames: true, paneDeliveries: true, resources: true, sudo: true, sudoOutcome: true, previewDeltas: true, quickChat: true, agentFolder: true, launchPermissionMode: true, sessionMove: true, moveNewChat: true, moveConductor: true, moveToComputer: true, moveConductorToComputer: true, moveResume: true, claudeAccountAdd: true, accountPools: true, workerRelocation: 1, projectMemory: true, fileWrite: true, fileSearch: true, gitReview: true, memoryStoreBatch: true, gitHosts: true, projectHostToken: true };
93
95
  export function capabilitiesForModules(snapshot) {
94
96
  const allowed = new Set(snapshot.modules.flatMap(module => module.capabilities));
95
97
  const result = Object.fromEntries(Object.entries(capabilities).filter(([name]) => allowed.has(name)));
@@ -604,8 +606,9 @@ export function createRouteHandler(ctx) {
604
606
  case "/v1/web-servers":
605
607
  result = { servers: await webServers() };
606
608
  break;
609
+ // `all=1` (capability simulatorDevices): every available device with its state, for the phone's picker.
607
610
  case "/v1/simulators":
608
- result = { simulators: await bootedSimulators() };
611
+ result = { simulators: url.searchParams.get("all") === "1" ? await simulatorDevices() : await bootedSimulators() };
609
612
  break;
610
613
  case "/v1/simulators/screenshot": {
611
614
  const bytes = await simulatorScreenshot(String(url.searchParams.get("udid") ?? ""));
@@ -947,6 +950,30 @@ export function createRouteHandler(ctx) {
947
950
  harness: note.target && "harness" in note.target ? note.target.harness : "codex", prompt, label: `Code note: ${note.symbol}`.slice(0, 200) });
948
951
  } : undefined);
949
952
  }
953
+ else if (url.pathname === "/v1/sessions/move" && data.interrupt === true) {
954
+ // "Stop <agent> and hand off now": Escape only while the move's hand-off request is still held.
955
+ if (!ownerRequest(request, data))
956
+ throw new BridgeError(403, "Only the owner can interrupt a move's agent.");
957
+ if (!ctx.mover)
958
+ throw new BridgeError(503, "Session moves are unavailable.");
959
+ const { id } = z.object({ id: z.string().uuid(), interrupt: z.literal(true), origin: z.unknown().optional() }).strict().parse(data);
960
+ // Esc as /v1/keys sends it: a served OpenCode pane or a Codex pane on the Hook's own app-server stops
961
+ // its turn over its API; otherwise the key goes to the pane. A question the Hook holds is declined
962
+ // first, and the turn is still stopped: a declined question alone lets the turn carry on.
963
+ const escape = async (target) => {
964
+ if (await agentHooks.servedKeys(target, ["Escape"], "working", { abortTurn: true }))
965
+ return;
966
+ agentHooks.cancelHeldQuestion(target);
967
+ const { codexServers } = await import("./codex-servers.js");
968
+ const owned = codexServers.forTarget(target);
969
+ if (owned && await codexServers.interrupt(owned).catch(() => false)) {
970
+ agentHooks.clearTerminalPrompt(target);
971
+ return;
972
+ }
973
+ await terminalProvider().sendKeys(target.server, target.pane, ["esc"]);
974
+ };
975
+ result = { ok: true, ...await ctx.mover.interrupt(id, ctx.handOffs, escape) };
976
+ }
950
977
  else if (url.pathname === "/v1/sessions/move") {
951
978
  // Answers once the move is checked and recorded; the hand-off and relaunch run on, and GET says where it is.
952
979
  if (!ctx.mover)
@@ -990,7 +1017,31 @@ export function createRouteHandler(ctx) {
990
1017
  else if (url.pathname === "/v1/accounts/claude/add") {
991
1018
  if (!ownerRequest(request, data))
992
1019
  throw new BridgeError(403, "Only the owner can add a Claude account.");
993
- result = await launches.run(() => addClaudeAccount(data, selectedServer(url)));
1020
+ // `mode`: sign in a slot that exists but is signed out, or ask whether it is signed in yet.
1021
+ result = data.mode === undefined ? await launches.run(() => addClaudeAccount(data, selectedServer(url)))
1022
+ : data.mode === "sign-in-status" ? await signInClaudeAccount(data, selectedServer(url))
1023
+ : await launches.run(() => signInClaudeAccount(data, selectedServer(url)));
1024
+ }
1025
+ else if (url.pathname === "/v1/accounts/claude/settings") {
1026
+ // An account's pool and role (account-pools.ts): a field left out stays, null clears it.
1027
+ if (!ownerRequest(request, data))
1028
+ throw new BridgeError(403, "Only the owner can change an account's pool or role.");
1029
+ const input = z.object({ slug: z.string().max(64), pool: z.string().max(64).nullable().optional(), role: z.string().max(32).nullable().optional(), origin: z.unknown().optional() }).strict().parse(data);
1030
+ if (!claudeHome(input.slug))
1031
+ throw new BridgeError(404, `There is no Claude account "${input.slug}" on this computer.`);
1032
+ if (input.role !== undefined && input.role !== null && !isAccountRole(input.role))
1033
+ throw new BridgeError(400, `A role is ${ACCOUNT_ROLES.join(", ")}.`);
1034
+ const settings = await setAccountSettings(input.slug, { pool: input.pool, role: input.role })
1035
+ .catch((error) => { throw new BridgeError(400, error.message); });
1036
+ result = { ok: true, slug: input.slug, ...settings };
1037
+ }
1038
+ else if (url.pathname === "/v1/accounts/allowed-pools") {
1039
+ // The pools this computer's accounts may do work for; null clears the list (any pool).
1040
+ if (!ownerRequest(request, data))
1041
+ throw new BridgeError(403, "Only the owner can change this computer's allowed pools.");
1042
+ const input = z.object({ allowedPools: z.array(z.string().max(64)).max(64).nullable(), origin: z.unknown().optional() }).strict().parse(data);
1043
+ const allowedPools = await setComputerAllowedPools(input.allowedPools).catch((error) => { throw new BridgeError(400, error.message); });
1044
+ result = { ok: true, ...(allowedPools ? { allowedPools } : {}) };
994
1045
  }
995
1046
  else if (url.pathname === "/v1/sessions/rename") {
996
1047
  result = await renameSession(selectedServer(url), data);
@@ -1056,6 +1107,13 @@ export function createRouteHandler(ctx) {
1056
1107
  else if (url.pathname === "/v1/dispatch/workers") {
1057
1108
  result = await hookWorkers(agentHooks)(data);
1058
1109
  }
1110
+ else if (url.pathname === "/v1/dispatch/returns" && url.searchParams.get("peek") === "1") {
1111
+ // The unread returns, left unread: a watcher (`phren dispatch returns --watch`) beside an agent
1112
+ // conductor, which still takes them. Read here, never forwarded to a successor, which would take them.
1113
+ if (request.headers?.["x-phren-origin"] === "peer")
1114
+ throw new BridgeError(403, "Peer conductor operations require the authenticated generation-scoped routes.");
1115
+ result = { returns: await ctx.returns.take(false) };
1116
+ }
1059
1117
  else if (url.pathname === "/v1/dispatch/returns") {
1060
1118
  result = await conductorCall("returns", {}, data.origin, async () => ({ returns: await ctx.returns.take() }));
1061
1119
  }
@@ -1150,7 +1208,9 @@ export function createRouteHandler(ctx) {
1150
1208
  result = await launches.run(async () => enrollProject(z.object({ directory: z.string().max(4096).optional(), cloneUrl: z.string().max(512).optional(), project: z.string().max(100).optional(), store: z.string().max(200).optional() }).parse(data)));
1151
1209
  }
1152
1210
  else if (url.pathname === "/v1/simulators/action") {
1153
- result = await simulatorAct(z.string().parse(data.udid), z.object({ action: z.string(), bundleId: z.string().optional(), url: z.string().optional(), x: z.number().optional(), y: z.number().optional(), text: z.string().optional(), submit: z.boolean().optional() }).parse(data));
1211
+ result = await simulatorAct(z.string().parse(data.udid), z.object({ action: z.string(), bundleId: z.string().optional(), url: z.string().optional(), x: z.number().optional(), y: z.number().optional(),
1212
+ x1: z.number().optional(), y1: z.number().optional(), x2: z.number().optional(), y2: z.number().optional(), durationMs: z.number().optional(),
1213
+ text: z.string().optional(), submit: z.boolean().optional() }).parse(data));
1154
1214
  }
1155
1215
  else {
1156
1216
  if (url.pathname === "/v1/workspaces/launch") {
@@ -24,6 +24,7 @@ import { cpus, hostname, loadavg } from "node:os";
24
24
  import path from "node:path";
25
25
  import { WebSocketServer } from "ws";
26
26
  import { relayLiveSpeech } from "./speech-live.js";
27
+ import { streamSimulator } from "./simulator-stream.js";
27
28
  import { failRelay, relayTranscription } from "./speech-transcribe.js";
28
29
  import { ActivityJournal } from "./activity.js";
29
30
  import { countTick } from "./metrics.js";
@@ -113,7 +114,7 @@ export async function serve(version, options = {}) {
113
114
  localComputer: { id: computerID, name: hostname() },
114
115
  forward: (origin, text, deliveryId) => succession?.forward(origin, text, deliveryId) ?? Promise.resolve(undefined),
115
116
  // Continue on another signed-in account when a Claude worker stops at its usage limit: opt-in, `phren config account-failover on`.
116
- failover: new AccountFailover({ rooms: () => dispatches.claudeRooms(), dispatch: (input, origin, continues) => succession ? succession.automatic("dispatch", { ...input, continues }, origin, () => dispatches.dispatch(input, origin, continues)) : dispatches.dispatch(input, origin, continues) }),
117
+ failover: new AccountFailover({ rooms: context => dispatches.claudeRooms(context), dispatch: (input, origin, continues) => succession ? succession.automatic("dispatch", { ...input, continues }, origin, () => dispatches.dispatch(input, origin, continues)) : dispatches.dispatch(input, origin, continues) }),
117
118
  localWorkers: hookWorkers(agentHooks),
118
119
  close: async (receipt, verifiedPeer) => {
119
120
  const data = { target: receipt.target, dispatch: receipt.moves?.slice().reverse().find(move => move.to.computer)?.id ?? receipt.id, turn: receipt.closePending.turn };
@@ -174,6 +175,7 @@ export async function serve(version, options = {}) {
174
175
  identity: (server, pane) => paneIdentity(server, pane, true),
175
176
  terminal: terminalProvider(),
176
177
  deliver: (target, text, deliveryId) => handOffs ? handOffs.enqueue({ target, text, deliveryId }) : sendPrompt(target, text, deliveryId, async () => { }),
178
+ withdraw: async (target, deliveryId, reason) => handOffs?.withdraw(deliveryId, target, reason),
177
179
  // The new agent starts in the folder an agent already ran in, so it is trusted for the new harness too.
178
180
  launch: (server, data, options) => launches.run(() => launchSession(server, data, { trustFolder: true, ...options })),
179
181
  inventory: () => launchCheckOff() ? Promise.resolve(undefined) : harnessInventoryWithin(2_500),
@@ -280,7 +282,7 @@ export async function serve(version, options = {}) {
280
282
  http.on("upgrade", (request, socket, head) => {
281
283
  try {
282
284
  const url = new URL(request.url || "/", "http://phren.local");
283
- if (!["/v1/transcripts", "/v1/status", "/v1/overview", "/v1/speech/transcribe", "/v1/speech/live"].includes(url.pathname) || url.origin !== "http://phren.local") {
285
+ if (!["/v1/transcripts", "/v1/status", "/v1/overview", "/v1/speech/transcribe", "/v1/speech/live", "/v1/simulators/stream"].includes(url.pathname) || url.origin !== "http://phren.local") {
284
286
  socket.destroy();
285
287
  return;
286
288
  }
@@ -305,6 +307,10 @@ export async function serve(version, options = {}) {
305
307
  void relayTranscription(client, url.searchParams).catch(() => failRelay(client));
306
308
  return;
307
309
  }
310
+ if (url.pathname === "/v1/simulators/stream") {
311
+ void streamSimulator(client, url.searchParams).catch(() => client.close(1011, "Simulator stream unavailable"));
312
+ return;
313
+ }
308
314
  if (url.pathname === "/v1/speech/live") {
309
315
  void relayLiveSpeech(client, url.searchParams).catch(() => client.close(1011, "Spoken replies unavailable"));
310
316
  return;
@@ -5,6 +5,7 @@ import { moveToSchema } from "./dispatch.js";
5
5
  import { type HarnessInventory } from "./harnesses.js";
6
6
  import { type Json, type Provider, type StartingTarget, type Target } from "./protocol.js";
7
7
  import type { TerminalProvider } from "./terminal.js";
8
+ import type { HandOffQueue } from "./hand-off-queue.js";
8
9
  export { moveToSchema };
9
10
  export type MoveTo = z.infer<typeof moveToSchema>;
10
11
  export declare const moveRequestSchema: z.ZodObject<{
@@ -48,6 +49,7 @@ export declare const moveRequestSchema: z.ZodObject<{
48
49
  continuation: z.ZodDefault<z.ZodEnum<{
49
50
  handoff: "handoff";
50
51
  resume: "resume";
52
+ "summary-by-target": "summary-by-target";
51
53
  }>>;
52
54
  id: z.ZodOptional<z.ZodString>;
53
55
  handoffTimeoutMs: z.ZodOptional<z.ZodNumber>;
@@ -110,7 +112,10 @@ declare const moveRecordSchema: z.ZodObject<{
110
112
  "new-chat": "new-chat";
111
113
  replace: "replace";
112
114
  }>>;
113
- continuation: z.ZodOptional<z.ZodLiteral<"resume">>;
115
+ continuation: z.ZodOptional<z.ZodEnum<{
116
+ resume: "resume";
117
+ "summary-by-target": "summary-by-target";
118
+ }>>;
114
119
  modeForced: z.ZodOptional<z.ZodLiteral<"conductor">>;
115
120
  handedOffTo: z.ZodOptional<z.ZodObject<{
116
121
  computer: z.ZodOptional<z.ZodString>;
@@ -247,6 +252,17 @@ export interface MovedWorker {
247
252
  to: MoveTo;
248
253
  target: Target | StartingTarget;
249
254
  }
255
+ /** What "stop and hand off now" did: interrupted the step, or why not. `idle`: the agent is on no step,
256
+ * so its request goes in without one; `typed`: the request is being or was typed; `writing`: the agent took
257
+ * it and writes its hand-off; `finished`: the move is past its hand-off, or its request can no longer be
258
+ * delivered (the move then builds a hand-off itself); `replaced`: the pane now runs another agent or
259
+ * conversation than the one the move asked, which is never interrupted for it. */
260
+ export type MoveInterrupt = {
261
+ interrupted: true;
262
+ } | {
263
+ interrupted: false;
264
+ state: "idle" | "typed" | "writing" | "finished" | "replaced";
265
+ };
250
266
  export declare function movesRoot(): string;
251
267
  /** The hand-off sits beside the new agent's brief, in a folder Claude is given read access to. */
252
268
  export declare const handoffPath: (id: string) => string;
@@ -312,6 +328,25 @@ export declare function fallbackHandoff(input: {
312
328
  dispatch?: string;
313
329
  label?: string;
314
330
  }): string;
331
+ /** Whether a Claude conversation's last turn ended on its subscription's usage limit (Claude's own
332
+ * rate-limit row): its agent cannot answer a hand-off request. */
333
+ export declare function sourceOutOfUsage(lines: readonly string[], source: Provider): boolean;
334
+ /**
335
+ * The hand-off for a source that does not write one (its account is out of usage, or the owner asked), for a
336
+ * fresh agent on the target computer to build itself: what happened, then as much of the conversation as fits
337
+ * in `room` characters, newest messages kept, oldest first. The target agent writes its own summary from it first.
338
+ */
339
+ export declare function targetSummaryBody(input: {
340
+ from: string;
341
+ exhausted: boolean;
342
+ entries: readonly TailEntry[];
343
+ room: number;
344
+ original?: string;
345
+ dispatch?: string;
346
+ label?: string;
347
+ /** Each message as it will be sent (paths replaced, credentials redacted), so it is measured at its sent size. */
348
+ prepare?: (text: string) => string;
349
+ }): string;
315
350
  /** The hand-off file: who moved where and when, the body, then what Phren saw. */
316
351
  export declare function handoffDocument(record: MoveRecord, body: string, observed: string, at: string, conductor?: boolean): string;
317
352
  /** The new agent's first prompt: the whole hand-off when it fits the brief, else where to read it. */
@@ -324,6 +359,8 @@ export interface MoverDeps {
324
359
  terminal: Pick<TerminalProvider, "prompt" | "sendKeys" | "processes" | "closePane">;
325
360
  /** The `hand_off` delivery path: queued while the agent is busy. */
326
361
  deliver: (target: Target, text: string, deliveryId: string) => Promise<Json>;
362
+ /** Takes back a message `deliver` queued while it is still untyped (`HandOffQueue.withdraw`). */
363
+ withdraw?: (target: Target, deliveryId: string, reason: string) => Promise<unknown>;
327
364
  /** Starts the new agent (`startSession`), in `into` when given. */
328
365
  launch: (server: string, data: Json, options: {
329
366
  into?: {
@@ -366,9 +403,17 @@ export interface MoverDeps {
366
403
  export declare class SessionMover {
367
404
  private readonly deps;
368
405
  private readonly cancelled;
406
+ /** Moves this process is waiting on: their hand-off request was handed to the queue, and the wait for the
407
+ * agent's answer is not over (it answered, the wait ran out, or the owner aborted). Only these are interrupted:
408
+ * a move whose request was never sent (summary-by-target, or not yet), or one this process no longer runs
409
+ * (the Hook restarted), has no request an Escape would let in. */
410
+ private readonly asking;
411
+ /** Per move, the hand-off's end and an interrupt's check-and-send, one at a time. */
412
+ private readonly lifecycles;
369
413
  private readonly admissions;
370
414
  private readonly running;
371
415
  constructor(deps: MoverDeps);
416
+ private lifecycle;
372
417
  private get now();
373
418
  private sleep;
374
419
  private get poll();
@@ -381,7 +426,20 @@ export declare class SessionMover {
381
426
  settled(server: string, pane: string): Promise<void> | undefined;
382
427
  private update;
383
428
  private run;
429
+ /**
430
+ * "Stop <agent> and hand off now": Escape to the old agent only while the move's hand-off request is
431
+ * still held for it (queued behind the step it is on, not yet typed), so the step stops and the request
432
+ * goes in, and never into the hand-off the agent is writing. Checked and sent under the hand-off queue's
433
+ * lock (`whileQueued`), which is what types the request, and under the move's own lifecycle lock, which is
434
+ * what ends the hand-off wait: the move cannot go on to exit or launch between the check and the key.
435
+ * `state` says why it did not: the request is being or was typed (`typed`), the agent is writing its
436
+ * hand-off (`writing`), the move is past it, or the pane runs another agent now (`replaced`).
437
+ */
438
+ interrupt(id: string, queue?: Pick<HandOffQueue, "whileQueued">, escape?: (target: Target) => Promise<void>): Promise<MoveInterrupt>;
384
439
  abort(id: string): Promise<MoveRecord>;
440
+ /** Takes the move's hand-off request back while it is still queued. Outside the move's lifecycle lock: an
441
+ * interrupt holds the queue's lock while it waits for that one, so this must not wait the other way round. */
442
+ private withdrawRequest;
385
443
  private assertNotAborted;
386
444
  private continueOnPeer;
387
445
  /** Startup and tick recovery reuse the receiving Hook's durable move id.