@phren/cli 0.3.37 → 0.3.40

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 (96) hide show
  1. package/dist/bridge/account-failover.d.ts +4 -0
  2. package/dist/bridge/account-failover.js +12 -4
  3. package/dist/bridge/account-usage.d.ts +5 -2
  4. package/dist/bridge/account-usage.js +36 -6
  5. package/dist/bridge/agent-hooks.js +2 -0
  6. package/dist/bridge/changes.d.ts +5 -0
  7. package/dist/bridge/changes.js +4 -0
  8. package/dist/bridge/claude-accounts.d.ts +15 -4
  9. package/dist/bridge/claude-accounts.js +31 -16
  10. package/dist/bridge/claude-credits.d.ts +43 -0
  11. package/dist/bridge/claude-credits.js +236 -0
  12. package/dist/bridge/claude-question-dialog.js +6 -2
  13. package/dist/bridge/command.js +64 -3
  14. package/dist/bridge/conductor-sets.d.ts +5 -0
  15. package/dist/bridge/conductor-sets.js +23 -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 +7 -0
  21. package/dist/bridge/dispatch-returns.js +56 -6
  22. package/dist/bridge/dispatch.d.ts +52 -0
  23. package/dist/bridge/dispatch.js +14 -0
  24. package/dist/bridge/enroll.js +22 -4
  25. package/dist/bridge/file-range.d.ts +3 -0
  26. package/dist/bridge/file-range.js +5 -4
  27. package/dist/bridge/file-search.d.ts +37 -0
  28. package/dist/bridge/file-search.js +87 -0
  29. package/dist/bridge/file-write.d.ts +6 -0
  30. package/dist/bridge/file-write.js +120 -0
  31. package/dist/bridge/git-host-auth.d.ts +31 -0
  32. package/dist/bridge/git-host-auth.js +110 -0
  33. package/dist/bridge/git-host-gitboy.d.ts +46 -0
  34. package/dist/bridge/git-host-gitboy.js +296 -0
  35. package/dist/bridge/git-host-gitlab.d.ts +25 -0
  36. package/dist/bridge/git-host-gitlab.js +229 -0
  37. package/dist/bridge/git-host-http.d.ts +33 -0
  38. package/dist/bridge/git-host-http.js +70 -0
  39. package/dist/bridge/git-hosts.d.ts +92 -0
  40. package/dist/bridge/git-hosts.js +244 -0
  41. package/dist/bridge/git-publish.d.ts +15 -5
  42. package/dist/bridge/git-publish.js +69 -21
  43. package/dist/bridge/git-review.d.ts +23 -0
  44. package/dist/bridge/git-review.js +170 -0
  45. package/dist/bridge/git-sync.d.ts +14 -0
  46. package/dist/bridge/git-sync.js +143 -0
  47. package/dist/bridge/git.d.ts +20 -7
  48. package/dist/bridge/git.js +87 -68
  49. package/dist/bridge/gitboy-contract.d.ts +32 -0
  50. package/dist/bridge/gitboy-contract.js +46 -0
  51. package/dist/bridge/hand-off.d.ts +52 -2
  52. package/dist/bridge/hand-off.js +77 -24
  53. package/dist/bridge/health.d.ts +1 -1
  54. package/dist/bridge/health.js +5 -3
  55. package/dist/bridge/install.d.ts +14 -0
  56. package/dist/bridge/install.js +40 -1
  57. package/dist/bridge/memory-store.d.ts +8 -0
  58. package/dist/bridge/memory-store.js +80 -2
  59. package/dist/bridge/pair.d.ts +6 -1
  60. package/dist/bridge/pair.js +74 -2
  61. package/dist/bridge/project-memory.d.ts +94 -0
  62. package/dist/bridge/project-memory.js +235 -0
  63. package/dist/bridge/push.d.ts +15 -0
  64. package/dist/bridge/push.js +39 -0
  65. package/dist/bridge/scoped-gateway.d.ts +29 -0
  66. package/dist/bridge/scoped-gateway.js +239 -0
  67. package/dist/bridge/server-launch.d.ts +12 -0
  68. package/dist/bridge/server-launch.js +17 -10
  69. package/dist/bridge/server-pane-routes.js +54 -3
  70. package/dist/bridge/server-routes.d.ts +13 -0
  71. package/dist/bridge/server-routes.js +63 -5
  72. package/dist/bridge/server.js +44 -5
  73. package/dist/bridge/session-move.d.ts +288 -0
  74. package/dist/bridge/session-move.js +600 -0
  75. package/dist/bridge/subscription.d.ts +15 -0
  76. package/dist/bridge/subscription.js +23 -0
  77. package/dist/bridge/transport.js +21 -1
  78. package/dist/bridge/usage.d.ts +20 -3
  79. package/dist/bridge/usage.js +61 -11
  80. package/dist/bridge-hook.mjs +12822 -3248
  81. package/dist/cli-registry.js +10 -4
  82. package/dist/computers/command.js +3 -1
  83. package/dist/computers/read.d.ts +3 -0
  84. package/dist/computers/read.js +6 -0
  85. package/dist/content/summarize.d.ts +21 -0
  86. package/dist/content/summarize.js +56 -18
  87. package/dist/modules/registry.js +14 -14
  88. package/dist/project-config.d.ts +12 -0
  89. package/dist/project-config.js +29 -0
  90. package/dist/shared/retrieval.d.ts +1 -0
  91. package/dist/shared/retrieval.js +1 -1
  92. package/dist/sync/conflict-resolve.js +5 -6
  93. package/dist/tools/dispatch.js +18 -1
  94. package/dist/tools/finding.d.ts +25 -0
  95. package/dist/tools/finding.js +2 -1
  96. 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) {
@@ -1,3 +1,4 @@
1
+ import { type LinkResult, linkComputer } from "./link.js";
1
2
  import { type Json } from "./protocol.js";
2
3
  /** The Hook routes for linked computer sets (docs/conductor-sets.md). */
3
4
  interface LocalInfo {
@@ -17,4 +18,8 @@ export declare function readSets(info: LocalInfo): Promise<Json>;
17
18
  * on to every reachable member; a member's relay (with `namedAt`) is kept
18
19
  * when newer than the name held, and goes no further. */
19
20
  export declare function nameSet(data: Json): Promise<Json>;
21
+ /** `POST /v1/sets/link`: the phone's one-tap `phren bridge link <name>`. Runs
22
+ * on the computer whose set lists `name` as indirect or one-way, over this
23
+ * computer's own ssh login, one link at a time. */
24
+ export declare function linkSetMember(data: Json, link?: typeof linkComputer): Promise<LinkResult>;
20
25
  export {};
@@ -1,11 +1,12 @@
1
1
  import { z } from "zod";
2
- import { askPeers, buildSets, indirectMembers, localCaller } from "./conductor-group.js";
3
- import { readSetName, saveSetName } from "./conductor-role.js";
4
2
  import { computerLabel, readComputers } from "./computer-identity.js";
5
3
  import { localNames } from "./computer-names.js";
4
+ import { askPeers, buildSets, indirectMembers, localCaller } from "./conductor-group.js";
5
+ import { readSetName, saveSetName } from "./conductor-role.js";
6
6
  import { listsCaller } from "./health.js";
7
+ import { linkComputer } from "./link.js";
7
8
  import { optionalHookPeers, peerRequest } from "./peers.js";
8
- import { object } from "./protocol.js";
9
+ import { BridgeError, object } from "./protocol.js";
9
10
  import { localConductor } from "./server-launch.js";
10
11
  const callerSchema = z.object({ name: z.string().max(253).optional(), hostKey: z.string().max(512).optional() });
11
12
  /** `GET /v1/conductor`: this computer's live conductor and what a peer needs
@@ -77,3 +78,22 @@ export async function nameSet(data) {
77
78
  }));
78
79
  return { ok: true, name: input.name, namedAt, told: told.sort(), unreachable: unreachable.sort((a, b) => a.computer.localeCompare(b.computer)) };
79
80
  }
81
+ const linkInput = z.object({ name: z.string().trim().regex(/^[A-Za-z0-9_][A-Za-z0-9_.-]{0,252}$/, "A computer name or ssh host.") }).strict();
82
+ let linking;
83
+ /** `POST /v1/sets/link`: the phone's one-tap `phren bridge link <name>`. Runs
84
+ * on the computer whose set lists `name` as indirect or one-way, over this
85
+ * computer's own ssh login, one link at a time. */
86
+ export async function linkSetMember(data, link = linkComputer) {
87
+ if (data && typeof data === "object" && "origin" in data)
88
+ throw new BridgeError(403, "Only the owner links computers, from the phone or `phren bridge link` in their own terminal.");
89
+ const { name } = linkInput.parse(data);
90
+ if (linking)
91
+ throw new BridgeError(409, `Already linking ${linking}. Try again when it finishes.`);
92
+ linking = name;
93
+ try {
94
+ return await link(name);
95
+ }
96
+ finally {
97
+ linking = undefined;
98
+ }
99
+ }
@@ -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
  /**
@@ -108,6 +109,10 @@ export interface WorkerObservation {
108
109
  path: string;
109
110
  branch?: string;
110
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;
111
116
  }
112
117
  export interface WorkerReaders {
113
118
  snapshot: (server: string) => Promise<Json>;
@@ -131,6 +136,8 @@ export interface WorkerReaders {
131
136
  shared?: (directory: string, folders: readonly unknown[]) => Promise<boolean>;
132
137
  /** The branch checked out in a folder. */
133
138
  branch?: (directory: string) => Promise<string | undefined>;
139
+ /** This computer's session moves (session-move.ts), newest first. */
140
+ moves?: () => Promise<MoveRecord[]>;
134
141
  }
135
142
  export declare function paneTurn(server: string, pane: Json, source: Provider): Promise<TurnRecord | undefined>;
136
143
  /** The default readers with the approval reader of the Hook that runs the workers. */
@@ -21,6 +21,7 @@ import { liveWork, runningTasks } from "./session-activity.js";
21
21
  import { terminalProvider } from "./terminal.js";
22
22
  import { childAgentTree, runningChildAgents } from "./transcripts.js";
23
23
  import { opencodeTurn, readTurn, TURN_REPLY_LIMIT, truncateUtf8, turnPhase } from "./turn-records.js";
24
+ import { listMoves, moveFrom, movedWorker, moveToSchema } from "./session-move.js";
24
25
  import { awaitedInReply, recentUncommitted, sharedCheckout, unfinishedTurn } from "./worker-unfinished.js";
25
26
  export { truncateUtf8 } from "./turn-records.js";
26
27
  /**
@@ -194,7 +195,7 @@ export async function workerStates(input, readers = defaultReaders) {
194
195
  const { targets } = workerRequestSchema.parse(input);
195
196
  const snapshots = new Map();
196
197
  const freshSnapshots = new Map();
197
- const workers = await Promise.all(targets.map(async (target) => {
198
+ const observeOne = async (target) => {
198
199
  let s;
199
200
  try {
200
201
  if (!snapshots.has(target.server))
@@ -261,10 +262,25 @@ export async function workerStates(input, readers = defaultReaders) {
261
262
  const seen = { state, session, completed: turn?.completed === true, ...(end?.background ? { background: end.background } : {}), ...(turn?.error ? { error: turn.error } : {}),
262
263
  ...(turn?.interrupted ? { interrupted: true } : {}), ...replyFields(turn?.lastAssistant) };
263
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 };
264
280
  }));
265
281
  // Only a conversation this dispatch named can be answered; a starting target has no session yet.
266
282
  return { workers: workers.map((seen, index) => {
267
- const { dispatch: _dispatch, ...target } = targets[index];
283
+ const { dispatch: _dispatch, ...target } = effective[index];
268
284
  const full = "session" in target ? targetSchema.safeParse(target) : undefined;
269
285
  const approval = full?.success && seen.state !== "gone" && seen.state !== "closed" && seen.state !== "unavailable" ? readers.approval?.(full.data) : undefined;
270
286
  return approval ? { ...seen, approval } : seen;
@@ -280,7 +296,40 @@ const observationSchema = z.object({
280
296
  stalled: z.boolean().optional(), stalledSince: z.string().datetime().optional(), stallFor: z.number().nonnegative().optional(),
281
297
  interrupted: z.boolean().optional(), approval: z.unknown().optional(), unfinished: z.string().max(200).optional(), unchecked: z.boolean().optional(),
282
298
  checkout: z.object({ path: z.string().max(4096), branch: z.string().max(256).optional() }).strict().optional(),
299
+ moved: z.unknown().optional(),
283
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
+ }
284
333
  /** A worker's forwarded permission request as its Hook sent it; an invalid one is ignored, not a reason to drop the state. */
285
334
  const approvalObservation = z.object({
286
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(),
@@ -301,17 +350,18 @@ export function observe(receipt, value, now) {
301
350
  const parsed = observationSchema.safeParse(value);
302
351
  if (receipt.closedAt)
303
352
  return false;
353
+ const moved = parsed.success && parsed.data.moved !== undefined && observeMove(receipt, parsed.data.moved);
304
354
  if (!parsed.success || parsed.data.state === "unavailable" || parsed.data.state === "unknown")
305
- return false;
355
+ return moved;
306
356
  if (parsed.data.state === "closed") {
307
357
  receipt.closedAt = new Date(now).toISOString();
308
358
  return true;
309
359
  }
310
360
  if (parsed.data.state === "gone" && receipt.brief === "launch" && !receipt.worker?.sawWorking && !receipt.returned
311
361
  && now - Date.parse(receipt.createdAt) < LAUNCH_GRACE_MS)
312
- return false;
362
+ return moved;
313
363
  const state = observeState(receipt, parsed.data, now);
314
- return observeApproval(receipt, parsed.data.approval, now) || state;
364
+ return observeApproval(receipt, parsed.data.approval, now) || state || moved;
315
365
  }
316
366
  /** Follow the request the worker is waiting on: a new one is a fresh unread
317
367
  * blocked return that carries it, the same one is nothing new, and none means
@@ -469,7 +519,7 @@ export function returnRow(receipt) {
469
519
  ...(receipt.approval.terminal ? { terminal: true } : {}) } } : {}),
470
520
  ...(receipt.account ? { account: receipt.account } : {}), ...(receipt.accountChoice ? { accountChoice: receipt.accountChoice } : {}),
471
521
  ...(receipt.continued ? { continued: receipt.continued } : {}), ...(receipt.continues ? { continues: receipt.continues } : {}),
472
- ...(receipt.target ? { target: receipt.target } : {}) };
522
+ ...(receipt.moves ? { moves: receipt.moves } : {}), ...(receipt.target ? { target: receipt.target } : {}) };
473
523
  }
474
524
  const originKey = (origin) => JSON.stringify([origin.server, origin.workspace, origin.tab, origin.pane, origin.terminal]);
475
525
  /** One notice's delivery id, named by what it reports: the same returns keep the same id on a retry. */
@@ -86,6 +86,25 @@ export declare const dispatchSchema: z.ZodObject<{
86
86
  }, z.core.$strip>>;
87
87
  }, z.core.$strict>;
88
88
  export type DispatchInput = z.infer<typeof dispatchSchema>;
89
+ /** Where a session moves to (session-move.ts): a harness with its account, model and effort, as a dispatch names them. */
90
+ export declare const moveToSchema: z.ZodObject<{
91
+ harness: z.ZodEnum<{
92
+ claude: "claude";
93
+ codex: "codex";
94
+ copilot: "copilot";
95
+ opencode: "opencode";
96
+ }>;
97
+ account: z.ZodOptional<z.ZodString>;
98
+ model: z.ZodOptional<z.ZodString>;
99
+ effort: z.ZodOptional<z.ZodEnum<{
100
+ high: "high";
101
+ low: "low";
102
+ max: "max";
103
+ medium: "medium";
104
+ minimal: "minimal";
105
+ xhigh: "xhigh";
106
+ }>>;
107
+ }, z.core.$strict>;
89
108
  /** The local pane that asked for the dispatch, where return notices go. */
90
109
  export declare const originPaneSchema: z.ZodObject<{
91
110
  server: z.ZodString;
@@ -225,6 +244,39 @@ declare const receiptSchema: z.ZodObject<{
225
244
  error: z.ZodOptional<z.ZodString>;
226
245
  }, z.core.$strict>>;
227
246
  continues: z.ZodOptional<z.ZodString>;
247
+ moves: z.ZodOptional<z.ZodArray<z.ZodObject<{
248
+ id: z.ZodString;
249
+ at: z.ZodString;
250
+ handoff: z.ZodOptional<z.ZodString>;
251
+ from: z.ZodObject<{
252
+ harness: z.ZodEnum<{
253
+ claude: "claude";
254
+ codex: "codex";
255
+ copilot: "copilot";
256
+ opencode: "opencode";
257
+ phren: "phren";
258
+ }>;
259
+ account: z.ZodOptional<z.ZodString>;
260
+ }, z.core.$strict>;
261
+ to: z.ZodObject<{
262
+ harness: z.ZodEnum<{
263
+ claude: "claude";
264
+ codex: "codex";
265
+ copilot: "copilot";
266
+ opencode: "opencode";
267
+ }>;
268
+ account: z.ZodOptional<z.ZodString>;
269
+ model: z.ZodOptional<z.ZodString>;
270
+ effort: z.ZodOptional<z.ZodEnum<{
271
+ high: "high";
272
+ low: "low";
273
+ max: "max";
274
+ medium: "medium";
275
+ minimal: "minimal";
276
+ xhigh: "xhigh";
277
+ }>>;
278
+ }, z.core.$strict>;
279
+ }, z.core.$strict>>>;
228
280
  granted: z.ZodOptional<z.ZodString>;
229
281
  authority: z.ZodOptional<z.ZodString>;
230
282
  authorityConfirmed: z.ZodOptional<z.ZodString>;
@@ -43,6 +43,17 @@ export const dispatchSchema = z.object({
43
43
  parent: dispatchParentSchema.optional().describe("Explicit local conversation parent for work-tree attachment."),
44
44
  parentTarget: targetSchema.optional().describe("Complete live target for the explicit parent."),
45
45
  }).strict();
46
+ /** Where a session moves to (session-move.ts): a harness with its account, model and effort, as a dispatch names them. */
47
+ export const moveToSchema = z.object({
48
+ harness: z.enum(DISPATCH_HARNESSES).describe("Harness to continue in: claude, codex, opencode or copilot."),
49
+ account: z.string().refine(isAccountSlug, "Account must be default or a lowercase slug.").optional()
50
+ .describe("Claude account id (default, or a slug from `phren bridge accounts`); only for claude."),
51
+ model: text(200).optional().describe("Model for the new agent, otherwise the harness default."),
52
+ effort: z.enum(launchEfforts).optional().describe("Reasoning effort for the new agent, otherwise the harness default."),
53
+ }).strict().superRefine((value, context) => {
54
+ if (value.account && value.harness !== "claude")
55
+ context.addIssue({ code: "custom", message: "Only a Claude target takes an account." });
56
+ });
46
57
  const remoteTarget = z.union([targetSchema, startingTargetSchema]);
47
58
  /** The local pane that asked for the dispatch, where return notices go. */
48
59
  export const originPaneSchema = z.object({ server: serverName, workspace: id, tab: id, pane: id }).strict();
@@ -60,6 +71,9 @@ const receiptSchema = dispatchSchema.omit({ prompt: true }).extend({
60
71
  at: timestamp, error: z.string().max(500).optional() }).strict().optional()
61
72
  .describe("The worker hit its Claude usage limit: the dispatch that continues it on another account, or why none could."),
62
73
  continues: z.string().uuid().optional().describe("The dispatch this one continues after its worker hit its usage limit."),
74
+ moves: z.array(z.object({ id: z.string().uuid(), at: timestamp, handoff: z.string().max(4096).optional(),
75
+ from: z.object({ harness: provider, account: z.string().max(64).optional() }).strict(), to: moveToSchema }).strict()).max(16).optional()
76
+ .describe("Each move of this worker to another agent (session-move.ts): from, to, when, and the hand-off file on the worker's computer. `target`, `harness`, `account`, `model` and `effort` are the current agent's."),
63
77
  granted: z.string().max(200).optional().describe("Scope of the conductor grant that allowed this call."),
64
78
  authority: z.string().max(600).optional().describe("The release authority policy's line for this project, as a conductor quotes it."),
65
79
  authorityConfirmed: z.string().datetime().optional().describe("When the owner confirmed the ask-first release actions this agent dispatch used."),
@@ -106,11 +106,29 @@ export async function candidateRepos(activity, env = process.env) {
106
106
  return undefined;
107
107
  }
108
108
  };
109
+ // The journal repeats a few folders hundreds of times: one git call each.
110
+ const roots = new Map();
111
+ const rootOf = (directory) => {
112
+ let root = roots.get(directory);
113
+ if (!root) {
114
+ root = toplevel(directory);
115
+ roots.set(directory, root);
116
+ }
117
+ return root;
118
+ };
119
+ const activityDirectory = (event) => typeof event.directory === "string" && path.isAbsolute(event.directory) ? event.directory : undefined;
120
+ // Look the folders up eight at a time: a folder where git stalls (macOS can
121
+ // hold ~/Downloads from a background process) costs its 5 s timeout once.
122
+ const pending = [...new Set(activity.map(activityDirectory).filter((d) => !!d))];
123
+ await Promise.all(Array.from({ length: Math.min(8, pending.length) }, async () => {
124
+ for (let directory = pending.shift(); directory !== undefined; directory = pending.shift())
125
+ await rootOf(directory);
126
+ }));
109
127
  for (const event of [...activity].reverse()) {
110
- const directory = typeof event.directory === "string" ? event.directory : undefined;
111
- if (!directory || !path.isAbsolute(directory))
128
+ const directory = activityDirectory(event);
129
+ if (!directory)
112
130
  continue;
113
- const root = await toplevel(directory);
131
+ const root = await rootOf(directory);
114
132
  if (root)
115
133
  await offer(root, "activity", typeof event.at === "string" ? event.at : undefined);
116
134
  }
@@ -120,7 +138,7 @@ export async function candidateRepos(activity, env = process.env) {
120
138
  const directory = JSON.parse(`"${match[1]}"`);
121
139
  if (!path.isAbsolute(directory))
122
140
  continue;
123
- const root = await toplevel(directory);
141
+ const root = await rootOf(directory);
124
142
  if (root)
125
143
  await offer(root, "herdr");
126
144
  }
@@ -1,5 +1,8 @@
1
+ import { type Stats } from "node:fs";
1
2
  export declare const MAX_FILE_RANGE: number;
2
3
  export declare function fileContentType(file: string): string;
4
+ /** A file's identity and content stamp; any write, rename or replacement changes it. */
5
+ export declare function fileVersion(stat: Stats): string;
3
6
  export declare function rangeInteger(value: string | null, fallback: number): number;
4
7
  /** Roots are selected by the server, never supplied unchecked by the phone.
5
8
  * A zero length request checks existence and metadata without reading bytes.
@@ -16,7 +16,8 @@ export function fileContentType(file) {
16
16
  return types[ext] ?? (/^(ts|tsx|js|jsx|swift|py|rs|go|rb|sh|bash|zsh|c|h|cpp|hpp|cs|java|kt|html|css|scss|sql|toml|ini)$/.test(ext)
17
17
  ? "text/plain" : "application/octet-stream");
18
18
  }
19
- function version(stat) {
19
+ /** A file's identity and content stamp; any write, rename or replacement changes it. */
20
+ export function fileVersion(stat) {
20
21
  return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}`;
21
22
  }
22
23
  export function rangeInteger(value, fallback) {
@@ -57,10 +58,10 @@ export async function readFileRange(root, requested, offset, length, expectedVer
57
58
  try {
58
59
  const current = await handle.stat();
59
60
  // Recheck the name after opening, including parent directory replacements.
60
- if (!current.isFile() || version(current) !== version(metadata) || await realpath(file) !== resolved) {
61
+ if (!current.isFile() || fileVersion(current) !== fileVersion(metadata) || await realpath(file) !== resolved) {
61
62
  throw new BridgeError(409, "The file changed. Open it again.");
62
63
  }
63
- const revision = version(current);
64
+ const revision = fileVersion(current);
64
65
  if (expectedVersion !== undefined && expectedVersion !== revision)
65
66
  throw new BridgeError(409, "The file changed. Open it again.");
66
67
  if (offset > current.size)
@@ -73,7 +74,7 @@ export async function readFileRange(root, requested, offset, length, expectedVer
73
74
  break;
74
75
  read += next.bytesRead;
75
76
  }
76
- if (version(await handle.stat()) !== revision || read !== bytes.length)
77
+ if (fileVersion(await handle.stat()) !== revision || read !== bytes.length)
77
78
  throw new BridgeError(409, "The file changed. Open it again.");
78
79
  return { path: requested, offset, length: read, total: current.size, contentType: fileContentType(file),
79
80
  version: revision, eof: offset + read === current.size, data: bytes.toString("base64") };