@phren/cli 0.3.36 → 0.3.39

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 (103) hide show
  1. package/dist/bridge/account-choice.d.ts +82 -0
  2. package/dist/bridge/account-choice.js +173 -0
  3. package/dist/bridge/account-failover.d.ts +61 -0
  4. package/dist/bridge/account-failover.js +189 -0
  5. package/dist/bridge/account-usage.d.ts +7 -2
  6. package/dist/bridge/account-usage.js +53 -8
  7. package/dist/bridge/agent-hooks.js +2 -0
  8. package/dist/bridge/changes.d.ts +5 -0
  9. package/dist/bridge/changes.js +4 -0
  10. package/dist/bridge/claude-accounts.d.ts +15 -4
  11. package/dist/bridge/claude-accounts.js +31 -16
  12. package/dist/bridge/claude-credits.d.ts +43 -0
  13. package/dist/bridge/claude-credits.js +236 -0
  14. package/dist/bridge/claude-question-dialog.js +6 -2
  15. package/dist/bridge/command.js +64 -3
  16. package/dist/bridge/device-enroll.d.ts +34 -0
  17. package/dist/bridge/device-enroll.js +57 -0
  18. package/dist/bridge/dispatch-command.d.ts +2 -0
  19. package/dist/bridge/dispatch-command.js +25 -1
  20. package/dist/bridge/dispatch-returns.d.ts +19 -0
  21. package/dist/bridge/dispatch-returns.js +93 -12
  22. package/dist/bridge/dispatch.d.ts +83 -3
  23. package/dist/bridge/dispatch.js +82 -10
  24. package/dist/bridge/file-range.d.ts +3 -0
  25. package/dist/bridge/file-range.js +5 -4
  26. package/dist/bridge/file-search.d.ts +37 -0
  27. package/dist/bridge/file-search.js +87 -0
  28. package/dist/bridge/file-write.d.ts +6 -0
  29. package/dist/bridge/file-write.js +120 -0
  30. package/dist/bridge/git-host-auth.d.ts +31 -0
  31. package/dist/bridge/git-host-auth.js +110 -0
  32. package/dist/bridge/git-host-gitboy.d.ts +46 -0
  33. package/dist/bridge/git-host-gitboy.js +296 -0
  34. package/dist/bridge/git-host-gitlab.d.ts +25 -0
  35. package/dist/bridge/git-host-gitlab.js +229 -0
  36. package/dist/bridge/git-host-http.d.ts +33 -0
  37. package/dist/bridge/git-host-http.js +70 -0
  38. package/dist/bridge/git-hosts.d.ts +92 -0
  39. package/dist/bridge/git-hosts.js +244 -0
  40. package/dist/bridge/git-publish.d.ts +15 -5
  41. package/dist/bridge/git-publish.js +69 -21
  42. package/dist/bridge/git-review.d.ts +23 -0
  43. package/dist/bridge/git-review.js +170 -0
  44. package/dist/bridge/git-sync.d.ts +14 -0
  45. package/dist/bridge/git-sync.js +143 -0
  46. package/dist/bridge/git.d.ts +20 -7
  47. package/dist/bridge/git.js +87 -68
  48. package/dist/bridge/gitboy-contract.d.ts +32 -0
  49. package/dist/bridge/gitboy-contract.js +46 -0
  50. package/dist/bridge/hand-off.d.ts +75 -3
  51. package/dist/bridge/hand-off.js +113 -27
  52. package/dist/bridge/health.d.ts +1 -1
  53. package/dist/bridge/health.js +5 -3
  54. package/dist/bridge/install.d.ts +14 -0
  55. package/dist/bridge/install.js +40 -1
  56. package/dist/bridge/launch-brief.d.ts +3 -0
  57. package/dist/bridge/launch-brief.js +16 -0
  58. package/dist/bridge/memory-store.d.ts +8 -0
  59. package/dist/bridge/memory-store.js +80 -2
  60. package/dist/bridge/pair.d.ts +6 -1
  61. package/dist/bridge/pair.js +74 -2
  62. package/dist/bridge/peers.js +4 -2
  63. package/dist/bridge/project-memory.d.ts +94 -0
  64. package/dist/bridge/project-memory.js +235 -0
  65. package/dist/bridge/push.d.ts +15 -0
  66. package/dist/bridge/push.js +39 -0
  67. package/dist/bridge/schedule-launch.js +5 -1
  68. package/dist/bridge/schedule-watch.d.ts +3 -0
  69. package/dist/bridge/schedule-watch.js +27 -1
  70. package/dist/bridge/scoped-gateway.d.ts +29 -0
  71. package/dist/bridge/scoped-gateway.js +239 -0
  72. package/dist/bridge/server-launch.d.ts +12 -0
  73. package/dist/bridge/server-launch.js +23 -12
  74. package/dist/bridge/server-pane-routes.js +54 -3
  75. package/dist/bridge/server-routes.d.ts +12 -0
  76. package/dist/bridge/server-routes.js +64 -5
  77. package/dist/bridge/server.js +50 -5
  78. package/dist/bridge/session-move.d.ts +288 -0
  79. package/dist/bridge/session-move.js +600 -0
  80. package/dist/bridge/subscription.d.ts +15 -0
  81. package/dist/bridge/subscription.js +23 -0
  82. package/dist/bridge/transport.js +21 -1
  83. package/dist/bridge/usage.d.ts +23 -4
  84. package/dist/bridge/usage.js +63 -11
  85. package/dist/bridge-hook.mjs +23280 -13252
  86. package/dist/cli/config.js +28 -2
  87. package/dist/cli-registry.js +10 -4
  88. package/dist/computers/command.js +3 -1
  89. package/dist/computers/read.d.ts +3 -0
  90. package/dist/computers/read.js +6 -0
  91. package/dist/content/summarize.d.ts +21 -0
  92. package/dist/content/summarize.js +56 -18
  93. package/dist/init/preferences.d.ts +6 -0
  94. package/dist/modules/registry.js +13 -13
  95. package/dist/project-config.d.ts +12 -0
  96. package/dist/project-config.js +29 -0
  97. package/dist/shared/retrieval.d.ts +1 -0
  98. package/dist/shared/retrieval.js +1 -1
  99. package/dist/sync/conflict-resolve.js +5 -6
  100. package/dist/tools/dispatch.js +20 -3
  101. package/dist/tools/finding.d.ts +25 -0
  102. package/dist/tools/finding.js +2 -1
  103. package/package.json +57 -1
@@ -6,9 +6,11 @@ import { servers } from "./herdr.js";
6
6
  import { describeTerminal, terminalHealth } from "./health.js";
7
7
  import { agentHook } from "./agent-hooks.js";
8
8
  import { askpass } from "./sudo.js";
9
- import { object, provider } from "./protocol.js";
9
+ import { object, provider, socketPath } from "./protocol.js";
10
10
  import { apnsSetupSteps } from "./push.js";
11
11
  import { speechKeyFile, speechKeyStatus, writeSpeechKey } from "./speech-key.js";
12
+ import { gitHostsFile, listHostTokens, writeHostToken } from "./git-host-auth.js";
13
+ import { hostInfo, PROVIDERS } from "./git-hosts.js";
12
14
  import { clearSpeechModel, clearSpeechVoice, DEFAULT_SPEECH_MODEL, FALLBACK_SPEECH_MODEL, resolveSpeechModel, resolveSpeechRegion, resolveSpeechVoice, SPEECH_REGIONS, speechModelId, speechRegion, speechVoiceFile, voiceId, writeSpeechModel, writeSpeechRegion, writeSpeechVoice } from "./speech-voice.js";
13
15
  import { AccountUsageReader, captureClaudeUsage } from "./usage.js";
14
16
  import { acceptComputer, enrollComputer } from "./computers.js";
@@ -17,7 +19,9 @@ import { ARCHIVE_MAX_FOLDERS, archiveFinishedFanouts, FANOUTS_ARCHIVE_USAGE, par
17
19
  import { harnessInventory } from "./harnesses.js";
18
20
  import { addClaudeAccount } from "./claude-account-setup.js";
19
21
  import { setAccountLabel } from "./claude-accounts.js";
22
+ import { addClaudeCredit, claudeCredits, removeClaudeCredit } from "./claude-credits.js";
20
23
  import { ModelCatalog } from "./models.js";
24
+ const CREDIT_USAGE = "Usage: phren bridge accounts credit <id> [--amount <usd> [--expires <yyyy-mm-dd>] [--since <yyyy-mm-dd>] [--label <name>] | --remove <credit>]";
21
25
  const LINK_USAGE = "Usage: phren bridge link <ssh-host> [--name <its name here>] [--as <this computer's name there>] [--back-address <address it dials>] [--yes]";
22
26
  export async function runBridge(args, version) {
23
27
  switch (args[0]) {
@@ -53,8 +57,26 @@ export async function runBridge(args, version) {
53
57
  await setAccountLabel(args[2], args.slice(3).join(" "));
54
58
  console.log(`Labeled ${args[2]} "${args.slice(3).join(" ").trim()}".`);
55
59
  }
60
+ else if (args[1] === "credit" && args[2] && !args[2].startsWith("-")) {
61
+ const flag = (name) => { const at = args.indexOf(name); if (at !== -1 && (!args[at + 1] || args[at + 1].startsWith("--")))
62
+ throw new Error(CREDIT_USAGE); return at === -1 ? undefined : args[at + 1]; };
63
+ const amount = flag("--amount"), remove = flag("--remove");
64
+ if (remove)
65
+ console.log(await removeClaudeCredit(args[2], remove) ? `Removed credit ${remove} from ${args[2]}.` : `No credit ${remove} on ${args[2]}.`);
66
+ else if (amount) {
67
+ const credit = await addClaudeCredit(args[2], { amount, expires: flag("--expires"), since: flag("--since"), label: flag("--label") });
68
+ console.log(`Credit ${credit.id} on ${args[2]}: $${credit.amountUSD.toFixed(2)} from ${credit.since.slice(0, 10)}${credit.expiresAt ? `, expires ${credit.expiresAt.slice(0, 10)}` : ""}. Usage shows the estimated balance.`);
69
+ }
70
+ else {
71
+ const credits = claudeCredits(args[2]);
72
+ if (!credits.length)
73
+ console.log(`No credits on ${args[2]}. ${CREDIT_USAGE}`);
74
+ for (const credit of credits)
75
+ console.log(`${credit.id} $${credit.amountUSD.toFixed(2)} from ${credit.since.slice(0, 10)}${credit.expiresAt ? ` expires ${credit.expiresAt.slice(0, 10)}` : ""}${credit.label ? ` ${credit.label}` : ""}`);
76
+ }
77
+ }
56
78
  else
57
- throw new Error("Usage: phren bridge accounts [add <slug> [--label <name>] | label <id> <label>]");
79
+ throw new Error("Usage: phren bridge accounts [add <slug> [--label <name>] | label <id> <label> | credit <id> [--amount <usd> [--expires <date>] [--since <date>] [--label <name>] | --remove <credit>]]");
58
80
  break;
59
81
  }
60
82
  case "discover": {
@@ -116,6 +138,36 @@ export async function runBridge(args, version) {
116
138
  console.log(`Stored the ElevenLabs key in ${speechKeyFile()} (mode 600).`);
117
139
  break;
118
140
  }
141
+ case "git-host": {
142
+ // Tokens for GitLab and gitboy, which the Hook reads over HTTP; GitHub keeps gh's sign-in.
143
+ const [, action = "list", domain, kind] = args;
144
+ if (action === "list" && args.length <= 2) {
145
+ const hosts = await listHostTokens();
146
+ if (hosts === "unsafe")
147
+ throw new Error(`${gitHostsFile()} is readable by other users; run chmod 600 on it.`);
148
+ if (!hosts.length)
149
+ console.log("No GitLab or gitboy tokens stored. Add one with phren bridge git-host set <domain> gitlab|gitboy.");
150
+ for (const host of hosts)
151
+ console.log(`${host.domain} ${host.kind}${host.user ? ` @${host.user}` : ""}`);
152
+ }
153
+ else if (action === "set" && domain && (kind === "gitlab" || kind === "gitboy") && args.length === 4) {
154
+ // The token comes from stdin, never argv, so it stays out of ps and shell history.
155
+ const token = (await readSecret(`${kind === "gitlab" ? "GitLab" : "gitboy"} token for ${domain}: `)).trim();
156
+ if (!token)
157
+ throw new Error("No token given.");
158
+ const host = hostInfo(kind, { domain: domain.toLowerCase(), webUrl: null, remote: null, source: "none" });
159
+ const { user } = await PROVIDERS[kind].whoami(process.cwd(), host, token);
160
+ await writeHostToken(domain, kind, token, user || undefined);
161
+ console.log(`Connected ${domain} (${kind})${user ? ` as @${user}` : ""}. Stored in ${gitHostsFile()} (mode 600).`);
162
+ }
163
+ else if (action === "remove" && domain && args.length === 3) {
164
+ await writeHostToken(domain, "gitlab", "");
165
+ console.log(`Forgot the token for ${domain}.`);
166
+ }
167
+ else
168
+ throw new Error(GIT_HOST_USAGE);
169
+ break;
170
+ }
119
171
  case "speech-voice": {
120
172
  // Read on every spoken reply, so a change needs no Hook restart.
121
173
  const [, action = "show", id] = args;
@@ -207,6 +259,14 @@ export async function runBridge(args, version) {
207
259
  case "ssh":
208
260
  await dispatch(process.env.SSH_ORIGINAL_COMMAND || "");
209
261
  break;
262
+ // Run by <bridge>/enroll over a password SSH session, never by the forced command.
263
+ case "enroll-device": return (await import("./device-enroll.js")).runEnrollDevice(args.slice(1), version);
264
+ case "ssh-scoped": {
265
+ const { scopedDispatch } = await import("./scoped-gateway.js");
266
+ await scopedDispatch(args[1] ?? "", process.env.SSH_ORIGINAL_COMMAND || "", { input: process.stdin, output: process.stdout, socket: socketPath() });
267
+ process.stdin.destroy();
268
+ break;
269
+ }
210
270
  case "install":
211
271
  case "update":
212
272
  await install(version, args.includes("--no-service"), args.includes("--force"));
@@ -237,7 +297,7 @@ export async function runBridge(args, version) {
237
297
  console.error(`warning: ${push.warning}`);
238
298
  break;
239
299
  }
240
- default: throw new Error("Usage: phren bridge <install|status|doctor|usage|update|rollback|uninstall|enroll-computer|accounts|discover|link|fanouts archive|speech-key set|speech-voice|speech-model|speech-region>");
300
+ default: throw new Error("Usage: phren bridge <install|status|doctor|usage|update|rollback|uninstall|enroll-computer|accounts|discover|link|fanouts archive|git-host|speech-key set|speech-voice|speech-model|speech-region>");
241
301
  }
242
302
  return 0;
243
303
  }
@@ -252,6 +312,7 @@ export function approvalPushCheck(helper) {
252
312
  const SPEECH_VOICE_USAGE = "Usage: phren bridge speech-voice [show | set <elevenlabs-voice-id> | clear]";
253
313
  const SPEECH_MODEL_USAGE = "Usage: phren bridge speech-model [show | set <elevenlabs-model-id> | clear]";
254
314
  const SPEECH_REGION_USAGE = "Usage: phren bridge speech-region [show | us | global]";
315
+ const GIT_HOST_USAGE = "Usage: phren bridge git-host [list | set <domain> gitlab|gitboy | remove <domain>] (set reads the token from stdin)";
255
316
  const SPEECH_KEY_USAGE = "Usage: phren bridge speech-key set (paste the key when asked, or pipe it on stdin)";
256
317
  /** One line from stdin: piped as is, or typed at a prompt without echo. */
257
318
  async function readSecret(prompt) {
@@ -0,0 +1,34 @@
1
+ export declare const ENROLL_DEVICE_USAGE = "enroll-device [--device ios|android] [--name <device name>] < public-key";
2
+ export type EnrollDeviceReply = {
3
+ v: 1;
4
+ ok: true;
5
+ added: boolean;
6
+ user: string;
7
+ computer: {
8
+ id: string | null;
9
+ name: string;
10
+ };
11
+ hook: string;
12
+ } | {
13
+ v: 1;
14
+ ok: false;
15
+ code: "bad-key" | "key-conflict" | "enroll-busy" | "ssh-directory" | "usage" | "internal";
16
+ error: string;
17
+ };
18
+ /**
19
+ * Adds one phone's restricted key, the same line `phren pair` writes. The
20
+ * phone runs this once over an SSH session it signed into with the user's
21
+ * password, then connects with the key. An identical line already present is
22
+ * success (`added: false`); the same key with other options is a conflict.
23
+ */
24
+ export declare function enrollDevice(input: string, options: {
25
+ device: "ios" | "android";
26
+ version: string;
27
+ sshDirectory?: string;
28
+ root?: string;
29
+ }): Promise<EnrollDeviceReply>;
30
+ /** `bridge-hook.mjs enroll-device`: the key on stdin, one JSON line out. */
31
+ export declare function runEnrollDevice(args: string[], version: string, stdin?: AsyncIterable<Buffer | string>, options?: {
32
+ sshDirectory?: string;
33
+ root?: string;
34
+ }): Promise<number>;
@@ -0,0 +1,57 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { homedir, userInfo } from "node:os";
3
+ import path from "node:path";
4
+ import { appendAuthorizedKey, publicComputerKey } from "./computers.js";
5
+ import { forcedCommand } from "./install.js";
6
+ import { computerDisplayName } from "./pair.js";
7
+ import { BridgeError, bridgeRoot } from "./protocol.js";
8
+ export const ENROLL_DEVICE_USAGE = "enroll-device [--device ios|android] [--name <device name>] < public-key";
9
+ /**
10
+ * Adds one phone's restricted key, the same line `phren pair` writes. The
11
+ * phone runs this once over an SSH session it signed into with the user's
12
+ * password, then connects with the key. An identical line already present is
13
+ * success (`added: false`); the same key with other options is a conflict.
14
+ */
15
+ export async function enrollDevice(input, options) {
16
+ try {
17
+ const publicKey = publicComputerKey(input);
18
+ const comment = options.device === "android" ? "phren-android" : "phren-iphone";
19
+ const line = `restrict,pty,${forcedCommand} ${publicKey} ${comment}`;
20
+ const encoded = publicKey.split(" ")[1];
21
+ const file = path.join(options.sshDirectory ?? path.join(homedir(), ".ssh"), "authorized_keys");
22
+ const before = await readFile(file, "utf8").catch(() => "");
23
+ await appendAuthorizedKey(line, existing => existing.split(/\s+/).includes(encoded), "This phone key is already authorized with different options.", options.sshDirectory);
24
+ const id = await readFile(path.join(options.root ?? bridgeRoot(), "computer-id"), "utf8").then(value => value.trim() || null).catch(() => null);
25
+ return { v: 1, ok: true, added: !before.split("\n").includes(line), user: userInfo().username,
26
+ computer: { id, name: await computerDisplayName() }, hook: options.version };
27
+ }
28
+ catch (error) {
29
+ const message = error.message;
30
+ const code = !(error instanceof BridgeError) ? "internal"
31
+ : error.status === 400 ? "bad-key"
32
+ : /already running/.test(message) ? "enroll-busy"
33
+ : /SSH directory/.test(message) ? "ssh-directory" : "key-conflict";
34
+ return { v: 1, ok: false, code, error: message };
35
+ }
36
+ }
37
+ /** `bridge-hook.mjs enroll-device`: the key on stdin, one JSON line out. */
38
+ export async function runEnrollDevice(args, version, stdin = process.stdin, options = {}) {
39
+ const reply = (value) => { console.log(JSON.stringify(value)); return value.ok ? 0 : 1; };
40
+ let device = "ios";
41
+ for (let i = 0; i < args.length; i++) {
42
+ if (args[i] === "--device" && (args[i + 1] === "ios" || args[i + 1] === "android"))
43
+ device = args[++i];
44
+ // The phone's name only labels this run; the key's comment is fixed.
45
+ else if (args[i] === "--name" && args[i + 1] !== undefined)
46
+ i++;
47
+ else
48
+ return reply({ v: 1, ok: false, code: "usage", error: `Usage: ${ENROLL_DEVICE_USAGE}` });
49
+ }
50
+ let input = "";
51
+ for await (const chunk of stdin) {
52
+ input += chunk.toString();
53
+ if (input.length > 4096)
54
+ return reply({ v: 1, ok: false, code: "bad-key", error: "Supply one ed25519 public key." });
55
+ }
56
+ return reply(await enrollDevice(input, { device, version, ...options }));
57
+ }
@@ -1,6 +1,8 @@
1
1
  import { type Json } from "./protocol.js";
2
2
  export declare function runDispatch(args: string[]): Promise<number>;
3
3
  export declare function runHandOff(args: string[]): Promise<number>;
4
+ /** `phren move`: a live session, named by its session id or its pane id (`wC9:p1`), to another agent, through its computer's Hook (session-move.ts). */
5
+ export declare function runMove(args: string[]): Promise<number>;
4
6
  /** One line per computer: name, reachability, link and conductor. */
5
7
  export declare function formatSets(view: Json): string;
6
8
  export declare function runConductor(args: string[]): Promise<number>;
@@ -3,7 +3,7 @@ import { prsSchema } from "./return-contract.js";
3
3
  import { parseArgs } from "node:util";
4
4
  import { hookRequest } from "./client.js";
5
5
  import { dispatchSchema } from "./dispatch.js";
6
- import { handOff } from "./hand-off.js";
6
+ import { handOff, moveSession } from "./hand-off.js";
7
7
  import { terminalPaneFromEnv } from "./terminal.js";
8
8
  import { dispatchIdFromEnv } from "./launch-brief.js";
9
9
  import { addGrant, grantSchema, listNamedGrants, removeGrant } from "./grants.js";
@@ -75,6 +75,30 @@ export async function runHandOff(args) {
75
75
  console.log(JSON.stringify(result, null, 2));
76
76
  return result.ok ? 0 : 1;
77
77
  }
78
+ const MOVE_USAGE = "Usage: phren move <session-or-pane> --to <claude|codex|opencode|copilot> [--model <model>] [--effort <effort>] [--account <id>] [--computer <name>] [--no-wait] | phren move --status <move-id> [--computer <name>]";
79
+ /** `phren move`: a live session, named by its session id or its pane id (`wC9:p1`), to another agent, through its computer's Hook (session-move.ts). */
80
+ export async function runMove(args) {
81
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: {
82
+ to: { type: "string" }, account: { type: "string" }, model: { type: "string" }, effort: { type: "string" }, computer: { type: "string" },
83
+ status: { type: "string" }, id: { type: "string" }, "no-wait": { type: "boolean" },
84
+ } });
85
+ const computer = values.computer ? { computer: values.computer } : {};
86
+ if (values.status) {
87
+ if (positionals.length)
88
+ throw new Error(MOVE_USAGE);
89
+ const result = await moveSession({ ...computer, status: true, id: values.status });
90
+ console.log(JSON.stringify(result, null, 2));
91
+ return result.ok ? 0 : 1;
92
+ }
93
+ if (positionals.length !== 1 || !values.to)
94
+ throw new Error(MOVE_USAGE);
95
+ const named = sessionId.safeParse(positionals[0]).success ? { session: positionals[0] } : { pane: positionals[0] };
96
+ const result = await moveSession({ ...computer, ...named, harness: values.to, ...(values.account ? { account: values.account } : {}),
97
+ ...(values.model ? { model: values.model } : {}), ...(values.effort ? { effort: values.effort } : {}), ...(values.id ? { id: values.id } : {}),
98
+ ...(values["no-wait"] ? { wait: false } : {}) });
99
+ console.log(JSON.stringify(result, null, 2));
100
+ return result.ok ? 0 : 1;
101
+ }
78
102
  const CONDUCTOR_USAGE = "Usage: phren conductor status | make [--pane <id>] [--mux herdr:<name>|tmux:<name>] | stop [--pane <id>] | sets [--json] | sets name <name>|--clear | grants [list|add|remove]";
79
103
  /** The Hook route for a pane's multiplexer: `--mux`, else the pane the command runs in. */
80
104
  function muxQuery(mux, here) {
@@ -9,6 +9,7 @@ import { peerRequest, type HookPeer } from "./peers.js";
9
9
  import { type ApprovalDecision, type Json, type Provider, type Target } from "./protocol.js";
10
10
  import { type FinalTurn } from "./schedule-watch.js";
11
11
  import { type TurnRecord } from "./turn-records.js";
12
+ import { type MovedWorker, type MoveRecord } from "./session-move.js";
12
13
  import { type Uncommitted } from "./worker-unfinished.js";
13
14
  export { truncateUtf8 } from "./turn-records.js";
14
15
  /**
@@ -103,6 +104,15 @@ export interface WorkerObservation {
103
104
  /** The worker's checkout could not be read in time: the turn may be done,
104
105
  * but it is not closed on that (worker-close.ts). */
105
106
  unchecked?: true;
107
+ /** Where a worker that hit its Claude usage limit was working, for the dispatch that continues it. */
108
+ checkout?: {
109
+ path: string;
110
+ branch?: string;
111
+ };
112
+ /** The worker is being moved to another agent (session-move.ts): the move's id. */
113
+ moving?: string;
114
+ /** The worker was moved to another agent; the state above is the new agent's. */
115
+ moved?: MovedWorker;
106
116
  }
107
117
  export interface WorkerReaders {
108
118
  snapshot: (server: string) => Promise<Json>;
@@ -124,6 +134,10 @@ export interface WorkerReaders {
124
134
  uncommitted?: (directory: string) => Promise<Uncommitted>;
125
135
  /** Whether other panes' folders share the worker's checkout, whose changes then are not only its own. */
126
136
  shared?: (directory: string, folders: readonly unknown[]) => Promise<boolean>;
137
+ /** The branch checked out in a folder. */
138
+ branch?: (directory: string) => Promise<string | undefined>;
139
+ /** This computer's session moves (session-move.ts), newest first. */
140
+ moves?: () => Promise<MoveRecord[]>;
127
141
  }
128
142
  export declare function paneTurn(server: string, pane: Json, source: Provider): Promise<TurnRecord | undefined>;
129
143
  /** The default readers with the approval reader of the Hook that runs the workers. */
@@ -211,6 +225,10 @@ export interface DispatchReturnsOptions {
211
225
  /** A worker's new forwarded request was recorded. Returns true when this Hook pushed it to its phone. */
212
226
  onApproval?: (receipt: Receipt, approval: NonNullable<Receipt["approval"]>) => boolean | void;
213
227
  close?: (receipt: Receipt) => Promise<Json>;
228
+ /** Continues Claude workers stopped by their usage limit on another account, after each poll (account-failover.ts). */
229
+ failover?: {
230
+ run: () => Promise<void>;
231
+ };
214
232
  now?: () => number;
215
233
  }
216
234
  /** One notice's delivery id, named by what it reports: the same returns keep the same id on a retry. */
@@ -230,6 +248,7 @@ export declare class DispatchReturns {
230
248
  private readonly localAnswer?;
231
249
  private readonly onApproval?;
232
250
  private readonly close?;
251
+ private readonly failover?;
233
252
  private lastPoll;
234
253
  private readonly lastNotice;
235
254
  /** A return is waiting for a dispatching agent that was busy: try again on
@@ -2,7 +2,9 @@ import { intentionallyClosed } from "./worker-close.js";
2
2
  import { workerPrs, readIntegrator } from "./worker-reports.js";
3
3
  import { prsSchema } from "./return-contract.js";
4
4
  import { sessionStalls } from "./stalls.js";
5
+ import { execFile } from "node:child_process";
5
6
  import { createHash } from "node:crypto";
7
+ import { promisify } from "node:util";
6
8
  import { z } from "zod";
7
9
  import { logger } from "../logger.js";
8
10
  import { arrivalOf, dispatchStatus, updateReceipt } from "./dispatch.js";
@@ -14,11 +16,12 @@ import { handOff } from "./hand-off.js";
14
16
  import { hookPeers, peerRequest } from "./peers.js";
15
17
  import { isLocalComputer } from "./dispatch-hosts.js";
16
18
  import { BridgeError, objects, startingTargetSchema, targetSchema } from "./protocol.js";
17
- import { ownerQuestion, readFinalTurn } from "./schedule-watch.js";
19
+ import { isClaudeUsageLimit, ownerQuestion, readFinalTurn } from "./schedule-watch.js";
18
20
  import { liveWork, runningTasks } from "./session-activity.js";
19
21
  import { terminalProvider } from "./terminal.js";
20
22
  import { childAgentTree, runningChildAgents } from "./transcripts.js";
21
23
  import { opencodeTurn, readTurn, TURN_REPLY_LIMIT, truncateUtf8, turnPhase } from "./turn-records.js";
24
+ import { listMoves, moveFrom, movedWorker, moveToSchema } from "./session-move.js";
22
25
  import { awaitedInReply, recentUncommitted, sharedCheckout, unfinishedTurn } from "./worker-unfinished.js";
23
26
  export { truncateUtf8 } from "./turn-records.js";
24
27
  /**
@@ -54,6 +57,19 @@ const SNAPSHOT_AGE_MS = 5_000;
54
57
  // older Hook's target schema strips it, so it is safe to send to any peer.
55
58
  const workerTarget = z.union([targetSchema.extend({ dispatch: briefId.optional() }), startingTargetSchema.extend({ dispatch: briefId.optional() })]);
56
59
  export const workerRequestSchema = z.object({ targets: z.array(workerTarget).min(1).max(64) }).strict();
60
+ const run = promisify(execFile);
61
+ async function checkedOutBranch(directory) {
62
+ const { stdout } = await run("git", ["-C", directory, "rev-parse", "--abbrev-ref", "HEAD"], { timeout: 3_000 });
63
+ const branch = stdout.trim();
64
+ return branch && branch !== "HEAD" ? branch.slice(0, 256) : undefined;
65
+ }
66
+ /** A worker stopped by its Claude usage limit: where it was working, so another account can pick it up there. */
67
+ async function limitCheckout(seen, directory, readers) {
68
+ if (!isClaudeUsageLimit(seen.error) || typeof directory !== "string" || !directory)
69
+ return {};
70
+ const branch = await (readers.branch ?? checkedOutBranch)(directory).catch(() => undefined);
71
+ return { checkout: { path: directory.slice(0, 4096), ...(branch ? { branch } : {}) } };
72
+ }
57
73
  export async function paneTurn(server, pane, source) {
58
74
  if (source !== "opencode")
59
75
  return readTurn(server, String(pane.pane_id));
@@ -72,6 +88,7 @@ const defaultReaders = {
72
88
  lost: (server, pane, session) => codexServers.lostTurn(server, pane, session),
73
89
  uncommitted: directory => recentUncommitted(directory),
74
90
  shared: sharedCheckout,
91
+ branch: checkedOutBranch,
75
92
  };
76
93
  /** The default readers with the approval reader of the Hook that runs the workers. */
77
94
  export const workerReaders = (approval) => ({ ...defaultReaders, approval });
@@ -178,7 +195,7 @@ export async function workerStates(input, readers = defaultReaders) {
178
195
  const { targets } = workerRequestSchema.parse(input);
179
196
  const snapshots = new Map();
180
197
  const freshSnapshots = new Map();
181
- const workers = await Promise.all(targets.map(async (target) => {
198
+ const observeOne = async (target) => {
182
199
  let s;
183
200
  try {
184
201
  if (!snapshots.has(target.server))
@@ -222,7 +239,8 @@ export async function workerStates(input, readers = defaultReaders) {
222
239
  const seen = await fromTurn(own, own.session, status, target.source, readers);
223
240
  const full = targetSchema.safeParse({ ...target, session: seen.session });
224
241
  const prs = full.success && seen.state === "done" ? await workerPrs(full.data, own) : undefined;
225
- return { ...seen, ...(prs ? { prs } : {}), ...await unfinished(seen, own.stop?.cwd ?? paneDirectory(pane), readers, s, pane, prs), ...(full.success && seen.state === "working" ? await readers.stall?.(full.data, { ...pane, agent_status: "working" }, liveReader(own, target.source, own.session, readers)) : {}) };
242
+ return { ...seen, ...(prs ? { prs } : {}), ...await unfinished(seen, own.stop?.cwd ?? paneDirectory(pane), readers, s, pane, prs),
243
+ ...await limitCheckout(seen, own.stop?.cwd ?? paneDirectory(pane), readers), ...(full.success && seen.state === "working" ? await readers.stall?.(full.data, { ...pane, agent_status: "working" }, liveReader(own, target.source, own.session, readers)) : {}) };
226
244
  }
227
245
  const session = expected ?? current;
228
246
  const state = ["working", "idle", "done", "blocked"].find(value => value === status) ?? "unknown";
@@ -243,11 +261,26 @@ export async function workerStates(input, readers = defaultReaders) {
243
261
  }
244
262
  const seen = { state, session, completed: turn?.completed === true, ...(end?.background ? { background: end.background } : {}), ...(turn?.error ? { error: turn.error } : {}),
245
263
  ...(turn?.interrupted ? { interrupted: true } : {}), ...replyFields(turn?.lastAssistant) };
246
- return { ...seen, ...await unfinished(seen, paneDirectory(pane), readers, s, pane) };
264
+ return { ...seen, ...await unfinished(seen, paneDirectory(pane), readers, s, pane), ...await limitCheckout(seen, paneDirectory(pane), readers) };
265
+ };
266
+ // A worker moved to another agent (session-move.ts) is followed to it: the
267
+ // old pane's conversation is gone, and the dispatching Hook is told where it went.
268
+ const moves = await (readers.moves ?? listMoves)().catch(() => []);
269
+ const effective = [...targets];
270
+ const workers = await Promise.all(targets.map(async (target, index) => {
271
+ const move = moveFrom(moves, { ...target, session: "session" in target ? target.session : undefined });
272
+ // Its hand-off turn is part of the move, never a return of its own.
273
+ if (move && move.state !== "moved" && move.state !== "failed")
274
+ return { state: "working", moving: move.id };
275
+ const moved = move ? movedWorker(move) : undefined;
276
+ if (!moved)
277
+ return observeOne(target);
278
+ effective[index] = { ...moved.target, ...(target.dispatch ? { dispatch: target.dispatch } : {}) };
279
+ return { ...await observeOne(effective[index]), moved };
247
280
  }));
248
281
  // Only a conversation this dispatch named can be answered; a starting target has no session yet.
249
282
  return { workers: workers.map((seen, index) => {
250
- const { dispatch: _dispatch, ...target } = targets[index];
283
+ const { dispatch: _dispatch, ...target } = effective[index];
251
284
  const full = "session" in target ? targetSchema.safeParse(target) : undefined;
252
285
  const approval = full?.success && seen.state !== "gone" && seen.state !== "closed" && seen.state !== "unavailable" ? readers.approval?.(full.data) : undefined;
253
286
  return approval ? { ...seen, approval } : seen;
@@ -262,7 +295,41 @@ const observationSchema = z.object({
262
295
  prs: prsSchema.optional(),
263
296
  stalled: z.boolean().optional(), stalledSince: z.string().datetime().optional(), stallFor: z.number().nonnegative().optional(),
264
297
  interrupted: z.boolean().optional(), approval: z.unknown().optional(), unfinished: z.string().max(200).optional(), unchecked: z.boolean().optional(),
298
+ checkout: z.object({ path: z.string().max(4096), branch: z.string().max(256).optional() }).strict().optional(),
299
+ moved: z.unknown().optional(),
265
300
  }).passthrough();
301
+ const movedSchema = z.object({
302
+ id: z.string().uuid(), at: z.string().datetime(), handoff: z.string().max(4096).optional(),
303
+ from: z.object({ harness: z.enum(["codex", "claude", "copilot", "phren", "opencode"]), account: z.string().max(64).optional() }).strict(),
304
+ to: moveToSchema, target: z.union([targetSchema, startingTargetSchema]),
305
+ }).strict();
306
+ /** The worker moved to another agent: the receipt now follows that agent, and keeps the move. */
307
+ function observeMove(receipt, value) {
308
+ const parsed = movedSchema.safeParse(value);
309
+ if (!parsed.success || receipt.moves?.some(move => move.id === parsed.data.id))
310
+ return false;
311
+ const { target, ...move } = parsed.data;
312
+ receipt.target = target;
313
+ receipt.harness = move.to.harness;
314
+ if (move.to.account)
315
+ receipt.account = move.to.account;
316
+ else
317
+ delete receipt.account;
318
+ if (move.to.model)
319
+ receipt.model = move.to.model;
320
+ else
321
+ delete receipt.model;
322
+ if (move.to.effort)
323
+ receipt.effort = move.to.effort;
324
+ else
325
+ delete receipt.effort;
326
+ delete receipt.accountChoice;
327
+ // The new agent's turns are its own: the old one's state and pending approval are not carried over.
328
+ delete receipt.worker;
329
+ delete receipt.approval;
330
+ receipt.moves = [...(receipt.moves ?? []), move].slice(-16);
331
+ return true;
332
+ }
266
333
  /** A worker's forwarded permission request as its Hook sent it; an invalid one is ignored, not a reason to drop the state. */
267
334
  const approvalObservation = z.object({
268
335
  actionId: z.string().min(1).max(200), tool: z.string().max(200).default("action"), title: z.string().max(200).optional(), request: z.string().max(500).optional(),
@@ -283,17 +350,18 @@ export function observe(receipt, value, now) {
283
350
  const parsed = observationSchema.safeParse(value);
284
351
  if (receipt.closedAt)
285
352
  return false;
353
+ const moved = parsed.success && parsed.data.moved !== undefined && observeMove(receipt, parsed.data.moved);
286
354
  if (!parsed.success || parsed.data.state === "unavailable" || parsed.data.state === "unknown")
287
- return false;
355
+ return moved;
288
356
  if (parsed.data.state === "closed") {
289
357
  receipt.closedAt = new Date(now).toISOString();
290
358
  return true;
291
359
  }
292
360
  if (parsed.data.state === "gone" && receipt.brief === "launch" && !receipt.worker?.sawWorking && !receipt.returned
293
361
  && now - Date.parse(receipt.createdAt) < LAUNCH_GRACE_MS)
294
- return false;
362
+ return moved;
295
363
  const state = observeState(receipt, parsed.data, now);
296
- return observeApproval(receipt, parsed.data.approval, now) || state;
364
+ return observeApproval(receipt, parsed.data.approval, now) || state || moved;
297
365
  }
298
366
  /** Follow the request the worker is waiting on: a new one is a fresh unread
299
367
  * blocked return that carries it, the same one is nothing new, and none means
@@ -402,7 +470,9 @@ function observeState(receipt, parsed, now) {
402
470
  ...(next === "working" && waitingSince ? { waitingSince } : {}) };
403
471
  if (next !== "working") {
404
472
  receipt.returned = { state: next, at, read: false,
405
- ...(seen.reply && (next === "done" || next === "needs-you") ? { reply: seen.reply, ...(seen.truncated ? { truncated: true } : {}) } : {}),
473
+ // A worker stopped by its usage limit keeps its last reply: the dispatch that continues it hands it over.
474
+ ...(seen.reply && (next === "done" || next === "needs-you" || next === "failed" && isClaudeUsageLimit(failed)) ? { reply: seen.reply, ...(seen.truncated ? { truncated: true } : {}) } : {}),
475
+ ...(next === "failed" && seen.checkout ? { checkout: seen.checkout } : {}),
406
476
  ...(next === "done" && seen.prs ? { prs: seen.prs } : {}),
407
477
  ...(next === "stalled" ? { stalledSince: seen.stalledSince, stallFor: seen.stallFor } : {}),
408
478
  ...(failed ? { error: failed } : {}), ...(question ? { question } : {}), ...(turn ? { turn } : {}),
@@ -447,7 +517,9 @@ export function returnRow(receipt) {
447
517
  ...(receipt.approval && returned.state === "blocked" ? { approval: { actionId: receipt.approval.actionId, tool: receipt.approval.tool,
448
518
  ...(receipt.approval.request ? { request: receipt.approval.request } : {}), ...(receipt.approval.title ? { title: receipt.approval.title } : {}),
449
519
  ...(receipt.approval.terminal ? { terminal: true } : {}) } } : {}),
450
- ...(receipt.target ? { target: receipt.target } : {}) };
520
+ ...(receipt.account ? { account: receipt.account } : {}), ...(receipt.accountChoice ? { accountChoice: receipt.accountChoice } : {}),
521
+ ...(receipt.continued ? { continued: receipt.continued } : {}), ...(receipt.continues ? { continues: receipt.continues } : {}),
522
+ ...(receipt.moves ? { moves: receipt.moves } : {}), ...(receipt.target ? { target: receipt.target } : {}) };
451
523
  }
452
524
  const originKey = (origin) => JSON.stringify([origin.server, origin.workspace, origin.tab, origin.pane, origin.terminal]);
453
525
  /** One notice's delivery id, named by what it reports: the same returns keep the same id on a retry. */
@@ -469,6 +541,7 @@ export class DispatchReturns {
469
541
  localAnswer;
470
542
  onApproval;
471
543
  close;
544
+ failover;
472
545
  lastPoll = -Infinity;
473
546
  lastNotice = new Map();
474
547
  /** A return is waiting for a dispatching agent that was busy: try again on
@@ -477,6 +550,7 @@ export class DispatchReturns {
477
550
  running;
478
551
  constructor(options = {}) {
479
552
  this.close = options.close;
553
+ this.failover = options.failover;
480
554
  this.peers = options.peers ?? hookPeers;
481
555
  this.request = options.request ?? peerRequest;
482
556
  this.localWorkers = options.localWorkers ?? (input => workerStates(input));
@@ -546,8 +620,15 @@ export class DispatchReturns {
546
620
  return Promise.resolve();
547
621
  if (poll)
548
622
  this.lastPoll = this.now();
549
- this.running = (async () => { if (poll)
550
- await this.poll(); await this.forwardPrs(); await this.cleanup(); await this.notify(); })()
623
+ this.running = (async () => {
624
+ if (poll) {
625
+ await this.poll();
626
+ await this.failover?.run().catch(error => logger.warn("dispatch", `Account failover: ${error instanceof Error ? error.message : String(error)}`));
627
+ }
628
+ await this.forwardPrs();
629
+ await this.cleanup();
630
+ await this.notify();
631
+ })()
551
632
  .catch(() => { }).finally(() => { this.running = undefined; });
552
633
  return this.running;
553
634
  }