@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
@@ -0,0 +1,600 @@
1
+ // Moving a live session to another agent: the agent in the pane writes a
2
+ // hand-off, exits the way it normally does, and the target harness starts in
3
+ // the same pane, in the same folder, with that hand-off as its first prompt.
4
+ //
5
+ // The hand-off is asked for through the same durable prompt path `hand_off`
6
+ // uses, as a reply between two marker lines; the Hook reads it from the
7
+ // transcript and saves it. A reply never waits on a permission prompt, which
8
+ // a write outside the checkout would in a supervised session. When the agent
9
+ // does not answer in time, the hand-off is built from the transcript's tail,
10
+ // the git state and the original brief instead, as a worker continued on
11
+ // another account is (account-failover.ts).
12
+ //
13
+ // Nothing is committed, stashed or reset: the uncommitted changes stay in the
14
+ // checkout and the hand-off lists them. Each move is recorded in
15
+ // `<bridge>/moves/<id>.json`; a dispatching Hook asking about the old pane
16
+ // (dispatch-returns.ts `workerStates`) follows the record to the new agent,
17
+ // so the dispatch and its receipt carry on as one worker.
18
+ import { execFile } from "node:child_process";
19
+ import { randomUUID } from "node:crypto";
20
+ import { lstat, mkdir, open, readFile, readdir, rm } from "node:fs/promises";
21
+ import path from "node:path";
22
+ import { promisify } from "node:util";
23
+ import { z } from "zod";
24
+ import { logger } from "../logger.js";
25
+ import { quoted, withOriginalBrief } from "./account-failover.js";
26
+ import { DEFAULT_ACCOUNT } from "./claude-accounts.js";
27
+ import { DISPATCH_HARNESSES, moveToSchema } from "./dispatch.js";
28
+ import { hasUsable } from "./harnesses.js";
29
+ import { findPane } from "./herdr.js";
30
+ import { briefId, briefRoot, writeLaunchBrief } from "./launch-brief.js";
31
+ import { atomic, BridgeError, bridgeRoot, startingTargetSchema, targetSchema } from "./protocol.js";
32
+ import { publicAssistant } from "./schedule-watch.js";
33
+ const run = promisify(execFile);
34
+ export { moveToSchema };
35
+ export const moveRequestSchema = z.object({
36
+ target: targetSchema,
37
+ to: moveToSchema,
38
+ /** Kept on a retry: the same id returns the move already under way. */
39
+ id: z.string().uuid().optional(),
40
+ /** How long the agent gets to write its hand-off before Phren builds one. */
41
+ handoffTimeoutMs: z.number().int().min(5_000).max(900_000).optional(),
42
+ }).strict();
43
+ const MOVE_STATES = ["handing-off", "exiting", "launching", "moved", "failed"];
44
+ const timestamp = z.string().datetime();
45
+ const moveRecordSchema = z.object({
46
+ id: z.string().uuid(),
47
+ state: z.enum(MOVE_STATES),
48
+ createdAt: timestamp, updatedAt: timestamp,
49
+ from: z.object({ target: targetSchema, account: z.string().max(64).optional(), label: z.string().max(200).optional() }).strict(),
50
+ to: moveToSchema,
51
+ cwd: z.string().max(4096),
52
+ /** The dispatch the moved worker was launched for, as its turn record names it. */
53
+ dispatch: briefId.optional(),
54
+ handoff: z.object({ path: z.string().max(4096), source: z.enum(["agent", "fallback"]), reason: z.string().max(300).optional(), chars: z.number().int().nonnegative() }).strict().optional(),
55
+ /** How the old agent ended: its own exit command, an interrupt, or a kill after it hung. */
56
+ exit: z.enum(["clean", "interrupted", "killed"]).optional(),
57
+ placement: z.enum(["same-pane", "adjacent-pane"]).optional(),
58
+ target: z.union([targetSchema, startingTargetSchema]).optional(),
59
+ movedAt: timestamp.optional(),
60
+ error: z.string().max(500).optional(),
61
+ }).strict();
62
+ /** The slash command each harness ends its interactive session with. */
63
+ const EXIT_COMMANDS = { claude: "/exit", codex: "/quit", copilot: "/exit", opencode: "/exit", phren: "/exit" };
64
+ const HARNESS_NAMES = { claude: "Claude", codex: "Codex", opencode: "OpenCode", copilot: "Copilot", phren: "phren agent" };
65
+ const MOVE_KEEP_MS = 7 * 24 * 60 * 60 * 1000;
66
+ const MAX_MOVES = 256;
67
+ const MAX_RECORD_BYTES = 32_768;
68
+ /** The launch brief's limit; a longer hand-off is read from its file. */
69
+ const PROMPT_LIMIT = 32_768;
70
+ export function movesRoot() { return path.join(bridgeRoot(), "moves"); }
71
+ const recordFile = (id) => path.join(movesRoot(), `${z.string().uuid().parse(id)}.json`);
72
+ /** The hand-off sits beside the new agent's brief, in a folder Claude is given read access to. */
73
+ export const handoffPath = (id) => path.join(briefRoot(), id, "handoff.md");
74
+ let writes = Promise.resolve();
75
+ async function saveMove(record) {
76
+ const run = writes.then(async () => {
77
+ await mkdir(movesRoot(), { recursive: true, mode: 0o700 });
78
+ await atomic(recordFile(record.id), moveRecordSchema.parse(record));
79
+ });
80
+ writes = run.catch(() => undefined);
81
+ return run;
82
+ }
83
+ export async function readMove(id) {
84
+ const file = recordFile(id);
85
+ const info = await lstat(file).catch(() => undefined);
86
+ if (!info?.isFile() || info.size > MAX_RECORD_BYTES)
87
+ return undefined;
88
+ try {
89
+ return moveRecordSchema.parse(JSON.parse(await readFile(file, "utf8")));
90
+ }
91
+ catch {
92
+ return undefined;
93
+ }
94
+ }
95
+ /** Recent moves, newest first; old ones are removed on the way. */
96
+ export async function listMoves(now = Date.now()) {
97
+ const names = (await readdir(movesRoot()).catch(() => [])).filter(name => /^[a-f0-9-]{36}\.json$/.test(name));
98
+ const records = (await Promise.all(names.map(name => readMove(name.slice(0, -5))))).filter((record) => !!record)
99
+ .sort((a, b) => b.createdAt.localeCompare(a.createdAt));
100
+ const settled = (record) => record.state === "moved" || record.state === "failed";
101
+ const stale = records.filter((record, index) => settled(record) && (index >= MAX_MOVES || now - Date.parse(record.updatedAt) > MOVE_KEEP_MS));
102
+ await Promise.all(stale.map(record => rm(recordFile(record.id), { force: true }).catch(() => undefined)));
103
+ return records.filter(record => !stale.includes(record));
104
+ }
105
+ /** The move that took the agent out of `target`'s pane: a target with a
106
+ * conversation matches only that conversation; a starting one, the pane. */
107
+ export function moveFrom(records, target) {
108
+ return records.find(record => {
109
+ const from = record.from.target;
110
+ return from.server === target.server && from.pane === target.pane && from.source === target.source
111
+ && (target.session === undefined || from.session === target.session);
112
+ });
113
+ }
114
+ /** The receipt fields for a finished move. */
115
+ export function movedWorker(record) {
116
+ if (record.state !== "moved" || !record.target)
117
+ return undefined;
118
+ return { id: record.id, at: record.movedAt ?? record.updatedAt, ...(record.handoff ? { handoff: record.handoff.path } : {}),
119
+ from: { harness: record.from.target.source, ...(record.from.account ? { account: record.from.account } : {}) }, to: record.to, target: record.target };
120
+ }
121
+ /** A harness as people name it, with its account and model: "Claude (work, opus)". */
122
+ export function harnessName(to) {
123
+ const details = [to.account && to.account !== DEFAULT_ACCOUNT ? `account ${to.account}` : undefined, to.model, to.effort ? `${to.effort} effort` : undefined].filter(Boolean);
124
+ return `${HARNESS_NAMES[to.harness] ?? to.harness}${details.length ? ` (${details.join(", ")})` : ""}`;
125
+ }
126
+ const markers = (id) => {
127
+ const short = id.replaceAll("-", "").slice(0, 8);
128
+ return { begin: `=== PHREN HANDOFF ${short} BEGIN ===`, end: `=== PHREN HANDOFF ${short} END ===` };
129
+ };
130
+ /** What the moving agent is asked to write. */
131
+ export function handoffRequest(id, to) {
132
+ const { begin, end } = markers(id);
133
+ return [
134
+ `Phren is moving this session to ${harnessName(to)}, which continues the work in this same folder. Write a hand-off for it now.`,
135
+ "",
136
+ "Do not commit, stash, reset, clean or stop anything. Your uncommitted changes and anything you left running stay as they are; Phren records them.",
137
+ "",
138
+ "Reply with only the hand-off, in Markdown, between these two lines:",
139
+ begin,
140
+ end,
141
+ "",
142
+ "Use these headings:",
143
+ "## Goal: what the owner asked for, in their terms",
144
+ "## Done: what is finished, with commits, PRs and files",
145
+ "## Current state: the branch, each uncommitted change and why it is there, processes or servers you started that are still running, anything half done",
146
+ "## Decisions: what you chose and why, including approaches you ruled out",
147
+ "## Next steps: in order",
148
+ "## Open questions: for the owner, or still undecided",
149
+ "## Key files: paths, a few words each",
150
+ "",
151
+ "Write it in full; do not shorten it. Use no tools once you start it. Phren saves it to a file and starts the next agent with it.",
152
+ ].join("\n");
153
+ }
154
+ /** The hand-off between the markers in the agent's replies after the request,
155
+ * or undefined while its end marker has not arrived. Code fences around the
156
+ * block are dropped. */
157
+ export function extractHandoff(replies, id) {
158
+ const { begin, end } = markers(id);
159
+ const text = replies.join("\n\n");
160
+ const start = text.lastIndexOf(begin);
161
+ if (start < 0)
162
+ return undefined;
163
+ const stop = text.indexOf(end, start + begin.length);
164
+ if (stop < 0)
165
+ return undefined;
166
+ const body = text.slice(start + begin.length, stop).replace(/^\s*```[a-z]*\s*\n/i, "\n").replace(/\n\s*```\s*$/, "\n").trim();
167
+ return body || undefined;
168
+ }
169
+ /** The text an owner's (or another agent's) prompt row carries, without tool results or harness context. */
170
+ function userText(raw, source) {
171
+ const object = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
172
+ const blocks = (content, types) => typeof content === "string" ? content
173
+ : Array.isArray(content) ? content.map(object).filter(block => types.includes(String(block.type))).map(block => String(block.text ?? "")).join("\n") : "";
174
+ let text = "";
175
+ if (source === "claude") {
176
+ const message = object(raw.message);
177
+ if (raw.type !== "user" || message.role !== "user" || raw.isMeta === true || raw.isSidechain === true)
178
+ return undefined;
179
+ text = blocks(message.content, ["text"]);
180
+ }
181
+ else if (source === "codex") {
182
+ const payload = object(raw.payload);
183
+ if (raw.type !== "response_item" || payload.type !== "message" || payload.role !== "user")
184
+ return undefined;
185
+ text = blocks(payload.content, ["input_text", "text"]);
186
+ }
187
+ else if (source === "copilot") {
188
+ if (raw.type !== "user.message" || raw.agentId)
189
+ return undefined;
190
+ text = String(object(raw.data).content ?? "");
191
+ }
192
+ else if (source === "opencode") {
193
+ const message = object(object(raw.data).message);
194
+ if (raw.type !== "user/message" || message.role !== "user")
195
+ return undefined;
196
+ text = blocks(message.content, ["text"]);
197
+ }
198
+ text = text.trim();
199
+ // Harness context and command echoes are not the owner's words.
200
+ if (!text || /^<(environment_context|user_instructions|command-|local-command|task-notification|system-reminder)/.test(text) || text.startsWith("# AGENTS.md"))
201
+ return undefined;
202
+ return text;
203
+ }
204
+ /** The owner's prompts and the agent's replies in a transcript's lines, oldest first. */
205
+ export function conversationEntries(lines, source) {
206
+ const entries = [];
207
+ for (const line of lines) {
208
+ if (!line.trim())
209
+ continue;
210
+ let raw;
211
+ try {
212
+ raw = JSON.parse(line);
213
+ }
214
+ catch {
215
+ continue;
216
+ }
217
+ const owner = userText(raw, source);
218
+ if (owner) {
219
+ entries.push({ role: "owner", text: owner });
220
+ continue;
221
+ }
222
+ const agent = publicAssistant(raw, source);
223
+ if (agent)
224
+ entries.push({ role: "agent", text: agent });
225
+ }
226
+ return entries;
227
+ }
228
+ /** Where the move's request sits in the conversation, -1 before it arrived. */
229
+ function requestIndex(entries, id) {
230
+ const { begin } = markers(id);
231
+ for (let index = entries.length - 1; index >= 0; index--)
232
+ if (entries[index].role === "owner" && entries[index].text.includes(begin))
233
+ return index;
234
+ return -1;
235
+ }
236
+ /** The agent's replies after the move's request: the request names the move, so an older hand-off never counts. */
237
+ export function repliesAfterRequest(entries, id) {
238
+ const asked = requestIndex(entries, id);
239
+ return asked < 0 ? [] : entries.slice(asked + 1).filter(entry => entry.role === "agent").map(entry => entry.text);
240
+ }
241
+ export async function readGitState(directory) {
242
+ const git = async (...args) => (await run("git", ["-C", directory, ...args], { timeout: 5_000, maxBuffer: 8 * 1024 * 1024 })).stdout;
243
+ const root = (await git("rev-parse", "--show-toplevel").catch(() => "")).trim();
244
+ if (!root)
245
+ return undefined;
246
+ const [branch, head, upstream, status] = await Promise.all([
247
+ git("rev-parse", "--abbrev-ref", "HEAD").then(value => value.trim(), () => ""),
248
+ git("log", "-1", "--format=%h %s").then(value => value.trim(), () => ""),
249
+ git("rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}").then(value => value.trim(), () => ""),
250
+ git("status", "--porcelain=v1", "--untracked-files=all").catch(() => ""),
251
+ ]);
252
+ const counts = upstream ? (await git("rev-list", "--left-right", "--count", `${upstream}...HEAD`).catch(() => "")).trim().split(/\s+/).map(Number) : [];
253
+ return { root, ...(branch && branch !== "HEAD" ? { branch } : {}), ...(head ? { head } : {}), ...(upstream ? { upstream } : {}),
254
+ ...(counts.length === 2 && counts.every(Number.isFinite) ? { behind: counts[0], ahead: counts[1] } : {}),
255
+ changes: status.split("\n").filter(line => line.trim()) };
256
+ }
257
+ /** The commands of every process below `pids` (the agent's own children), not the agent itself. */
258
+ export async function processesBelow(pids) {
259
+ if (!pids.length || process.platform === "win32")
260
+ return [];
261
+ const { stdout } = await run("ps", ["-A", "-o", "pid=,ppid=,args="], { timeout: 5_000, maxBuffer: 8 * 1024 * 1024 });
262
+ const rows = stdout.split("\n").map(line => /^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(line)).filter((match) => !!match)
263
+ .map(match => ({ pid: Number(match[1]), ppid: Number(match[2]), args: match[3].trim() }));
264
+ const below = new Set(pids);
265
+ const found = [];
266
+ for (let grew = true; grew;) {
267
+ grew = false;
268
+ for (const row of rows)
269
+ if (below.has(row.ppid) && !below.has(row.pid)) {
270
+ below.add(row.pid);
271
+ found.push(`${row.pid} ${row.args}`);
272
+ grew = true;
273
+ }
274
+ }
275
+ return found;
276
+ }
277
+ /** What Phren itself saw at the move, appended to every hand-off. */
278
+ export function observedState(git, processes) {
279
+ const lines = ["## Checked by Phren at the move", ""];
280
+ if (!git)
281
+ lines.push("- Not a git checkout, or git could not be read.");
282
+ else {
283
+ const tracking = git.upstream ? ` tracking ${git.upstream}${git.ahead !== undefined ? ` (ahead ${git.ahead}, behind ${git.behind})` : ""}` : ", with no upstream";
284
+ lines.push(`- Branch: ${git.branch ?? "detached HEAD"}${tracking}. HEAD: ${git.head ?? "unknown"}.`);
285
+ if (!git.changes.length)
286
+ lines.push("- No uncommitted changes.");
287
+ else
288
+ lines.push(`- Uncommitted changes (${git.changes.length}). The move committed, stashed and reset nothing: they are the previous agent's work in progress, so keep them.`, "", "```", ...git.changes, "```");
289
+ }
290
+ lines.push("");
291
+ if (processes.length)
292
+ lines.push(`- Processes the previous agent had running (${processes.length}):`, "", "```", ...processes, "```");
293
+ else
294
+ lines.push("- The previous agent had no child processes running.");
295
+ return lines.join("\n");
296
+ }
297
+ /** A hand-off built without the agent: the conversation's tail, the original brief and the git state. */
298
+ export function fallbackHandoff(input) {
299
+ const lines = [
300
+ `The previous agent (${input.from}) did not write a hand-off: ${input.reason} Phren built this one from the end of its conversation instead.`,
301
+ "Check the checkout and what it already did before doing anything; do not start over.",
302
+ "",
303
+ ];
304
+ if (input.dispatch)
305
+ lines.push(`It was working on dispatch ${input.dispatch}${input.label ? ` ("${input.label}")` : ""}.`, "");
306
+ const tail = input.entries.slice(-12);
307
+ if (!tail.length)
308
+ lines.push("Its conversation could not be read.", "");
309
+ else {
310
+ lines.push(`The last ${tail.length} messages of its conversation, oldest first:`, "");
311
+ for (const entry of tail)
312
+ lines.push(...quoted(entry.role === "owner" ? "Prompt to it" : "Its reply", entry.text));
313
+ }
314
+ const head = lines.join("\n");
315
+ // Written to a file, so the brief is never cut here.
316
+ return input.original ? withOriginalBrief(head, input.original, Number.MAX_SAFE_INTEGER, "the original brief file") : head;
317
+ }
318
+ /** The hand-off file: who moved where and when, the body, then what Phren saw. */
319
+ export function handoffDocument(record, body, observed, at) {
320
+ return [
321
+ `# Hand-off from ${harnessName({ harness: record.from.target.source, account: record.from.account })} to ${harnessName(record.to)}`,
322
+ "",
323
+ `Moved by Phren at ${at} (move ${record.id}) in ${record.cwd}.${record.dispatch ? ` Dispatch ${record.dispatch}.` : ""}`,
324
+ "",
325
+ body.trim(),
326
+ "",
327
+ observed,
328
+ "",
329
+ ].join("\n");
330
+ }
331
+ /** The new agent's first prompt: the whole hand-off when it fits the brief, else where to read it. */
332
+ export function continuePrompt(document, file) {
333
+ const lead = "Phren moved this session to you. The hand-off from the previous agent follows. Continue from here: check the current state first, keep its uncommitted changes, and do not start over.";
334
+ const whole = `${lead}\n\n${document}`;
335
+ if (whole.length <= PROMPT_LIMIT)
336
+ return whole;
337
+ return `Phren moved this session to you. The previous agent's hand-off is ${document.length} characters, too long for this prompt: read all of ${file} before anything else. Then continue from here: check the current state first, keep its uncommitted changes, and do not start over.`;
338
+ }
339
+ /** A pane's place without its agent: `findPane` with a source finds it only while that agent runs. */
340
+ const placeOf = (target) => ({ workspace: target.workspace, tab: target.tab, pane: target.pane });
341
+ /** Control characters other than tab and newline cannot ride in a brief. */
342
+ const briefText = (value) => value.replace(/\r\n?/g, "\n").replace(/[\x00-\x08\x0b-\x1f\x7f]/g, "");
343
+ const DEFAULT_HANDOFF_MS = 240_000;
344
+ /** Runs moves on the computer that runs the session. A move outlives the
345
+ * request that started it (the Hook answers in seconds); its record says where it is. */
346
+ export class SessionMover {
347
+ deps;
348
+ running = new Map();
349
+ constructor(deps) {
350
+ this.deps = deps;
351
+ }
352
+ get now() { return (this.deps.now ?? Date.now)(); }
353
+ sleep(ms) { return (this.deps.sleep ?? (value => new Promise(resolve => setTimeout(resolve, value))))(ms); }
354
+ get poll() { return this.deps.pollMs ?? 2_000; }
355
+ /** Checks the move can happen, records it and starts it. Refuses before anything is typed. */
356
+ async start(input) {
357
+ const data = moveRequestSchema.parse(input);
358
+ if (data.id) {
359
+ const earlier = await readMove(data.id);
360
+ if (earlier) {
361
+ const from = earlier.from.target;
362
+ if (from.server !== data.target.server || from.pane !== data.target.pane || from.session !== data.target.session)
363
+ throw new BridgeError(409, "This move id was already used for another session.");
364
+ return earlier;
365
+ }
366
+ }
367
+ const { target, to } = data;
368
+ const active = (await listMoves(this.now)).find(record => record.from.target.server === target.server && record.from.target.pane === target.pane
369
+ && record.state !== "moved" && record.state !== "failed");
370
+ if (active || [...this.running.keys()].some(key => key === `${target.server}\0${target.pane}`))
371
+ throw new BridgeError(409, "This session is already being moved.", { code: "move_in_progress" });
372
+ const s = await this.deps.snapshot(target.server);
373
+ const pane = findPane(s, placeOf(target));
374
+ if (!pane)
375
+ throw new BridgeError(404, "That pane is no longer open.");
376
+ if (pane.agent !== target.source)
377
+ throw new BridgeError(409, `That pane no longer runs ${HARNESS_NAMES[target.source] ?? target.source}.`);
378
+ const session = await this.deps.identity(target.server, pane).catch(() => undefined);
379
+ if (session && session !== target.session)
380
+ throw new BridgeError(409, "That pane runs another conversation now.");
381
+ if (await this.deps.isConductor?.(target.server, pane).catch(() => false))
382
+ throw new BridgeError(409, "This pane is the conductor. Stop it as conductor first, or make the new agent the conductor after starting it.");
383
+ const account = target.source === "claude" ? this.deps.paneAccount?.(target.server, pane) ?? DEFAULT_ACCOUNT : undefined;
384
+ const sameHarness = to.harness === target.source && (to.harness !== "claude" || (to.account ?? account) === account);
385
+ if (sameHarness && !to.model && !to.effort)
386
+ throw new BridgeError(400, "The session already runs there. Choose another harness, account, model or effort.");
387
+ // Only harnesses signed in and usable here; an inventory that cannot be read lets the move go on, as a launch does.
388
+ const inventory = await this.deps.inventory().catch(() => undefined);
389
+ if (inventory) {
390
+ const availability = hasUsable(inventory, to.harness, to.harness === "claude" ? to.account : undefined);
391
+ if (!availability.ok) {
392
+ const usable = inventory.harnesses.filter(entry => entry.usable && DISPATCH_HARNESSES.includes(entry.source)).map(entry => entry.source);
393
+ throw new BridgeError(409, `${HARNESS_NAMES[to.harness]} can't take this session here: ${availability.reason}.${usable.length ? ` Usable here: ${usable.join(", ")}.` : ""}`, { code: availability.code });
394
+ }
395
+ }
396
+ const cwd = String(pane.foreground_cwd || pane.cwd || "");
397
+ if (!path.isAbsolute(cwd))
398
+ throw new BridgeError(409, "The pane's folder is unknown, so the new agent could not start there.");
399
+ const dispatch = await this.deps.paneDispatch?.(target.server, pane).catch(() => undefined);
400
+ const label = [pane.label, pane.agent_name].find(value => typeof value === "string" && value.trim() && !/^\d+$/.test(value));
401
+ const at = new Date(this.now).toISOString();
402
+ const record = { id: data.id ?? randomUUID(), state: "handing-off", createdAt: at, updatedAt: at,
403
+ from: { target, ...(account ? { account } : {}), ...(label ? { label: label.slice(0, 200) } : {}) }, to, cwd,
404
+ ...(dispatch && briefId.safeParse(dispatch).success ? { dispatch } : {}) };
405
+ await saveMove(record);
406
+ const key = `${target.server}\0${target.pane}`;
407
+ const work = this.run(record, data.handoffTimeoutMs ?? DEFAULT_HANDOFF_MS).finally(() => this.running.delete(key));
408
+ this.running.set(key, work);
409
+ return record;
410
+ }
411
+ /** For tests: the move under way in a pane, until it settles. */
412
+ settled(server, pane) { return this.running.get(`${server}\0${pane}`); }
413
+ async update(record, change) {
414
+ Object.assign(record, change, { updatedAt: new Date(this.now).toISOString() });
415
+ await saveMove(record);
416
+ }
417
+ async run(record, handoffMs) {
418
+ const from = record.from.target;
419
+ try {
420
+ // What the checkout and the agent's processes look like before it stops.
421
+ const pane = findPane(await this.deps.snapshot(from.server), placeOf(from));
422
+ const pids = pane ? (await this.deps.terminal.processes(from.server, from.pane).catch(() => undefined))?.foregroundPids ?? [] : [];
423
+ const [git, processes] = await Promise.all([(this.deps.git ?? readGitState)(record.cwd).catch(() => undefined),
424
+ (this.deps.processesBelow ?? processesBelow)(pids).catch(() => [])]);
425
+ const written = await this.askForHandoff(record, handoffMs);
426
+ const body = "text" in written ? written.text : await this.fallback(record, written.reason);
427
+ const document = handoffDocument(record, body, observedState(git, processes), new Date(this.now).toISOString());
428
+ const file = handoffPath(record.id);
429
+ const prompt = briefText(continuePrompt(document, file));
430
+ // The folder is the new agent's brief folder; the hand-off is written into it, whole.
431
+ await writeLaunchBrief({ id: record.id, text: prompt }, this.now, record.from.label);
432
+ await atomic(file, document);
433
+ await this.update(record, { state: "exiting", handoff: { path: file, source: "text" in written ? "agent" : "fallback",
434
+ ...("reason" in written ? { reason: written.reason.slice(0, 300) } : {}), chars: document.length } });
435
+ const exit = await this.exit(record);
436
+ await this.update(record, { state: "launching", exit });
437
+ await this.deps.afterExit?.(from.server, from.pane).catch(() => undefined);
438
+ const launched = await this.relaunch(record, prompt);
439
+ await this.update(record, { state: "moved", movedAt: new Date(this.now).toISOString(), ...launched });
440
+ logger.info("move", `Moved ${from.source} in pane ${from.pane} to ${harnessName(record.to)} (${launched.placement}); hand-off ${record.handoff?.source}.`);
441
+ }
442
+ catch (error) {
443
+ const message = (error instanceof Error ? error.message : String(error)).replace(/[\x00-\x1f\x7f]+/g, " ");
444
+ const stopped = record.state === "launching";
445
+ const hint = stopped && record.handoff ? ` The old agent has exited; start ${HARNESS_NAMES[record.to.harness]} in the pane with the hand-off at ${record.handoff.path}.` : "";
446
+ await this.update(record, { state: "failed", error: `${message}${hint}`.slice(0, 500) }).catch(() => undefined);
447
+ logger.warn("move", `Moving pane ${from.pane} to ${record.to.harness} failed: ${message}`);
448
+ }
449
+ }
450
+ /** The agent's own hand-off, or why there is none. Fails only when the session itself went away. */
451
+ async askForHandoff(record, handoffMs) {
452
+ const from = record.from.target;
453
+ const deadline = this.now + handoffMs;
454
+ try {
455
+ const sent = await this.deps.deliver(from, handoffRequest(record.id, record.to), `move-${record.id}`);
456
+ if (sent.ok !== true && sent.queued !== true)
457
+ return { reason: `the request could not be delivered (${String(sent.error ?? sent.state ?? "not confirmed")}).` };
458
+ }
459
+ catch (error) {
460
+ return { reason: `the request could not be delivered (${error instanceof Error ? error.message : String(error)}).` };
461
+ }
462
+ while (this.now < deadline) {
463
+ await this.sleep(this.poll);
464
+ const pane = findPane(await this.deps.snapshot(from.server), placeOf(from));
465
+ if (!pane || pane.agent !== from.source)
466
+ throw new BridgeError(409, "The session ended before it wrote its hand-off; nothing was started.");
467
+ const lines = await this.deps.transcript(from).catch(() => []);
468
+ const text = extractHandoff(repliesAfterRequest(conversationEntries(lines, from.source), record.id), record.id);
469
+ if (!text)
470
+ continue;
471
+ // Its turn ends with the hand-off; wait for that before typing the exit.
472
+ while (this.now < deadline) {
473
+ const now = findPane(await this.deps.snapshot(from.server), placeOf(from));
474
+ if (!now || now.agent_status !== "working")
475
+ break;
476
+ await this.sleep(this.poll);
477
+ }
478
+ return { text };
479
+ }
480
+ return { reason: `it did not reply with one within ${Math.round(handoffMs / 1000)} seconds.` };
481
+ }
482
+ async fallback(record, reason) {
483
+ const from = record.from.target;
484
+ const lines = await this.deps.transcript(from).catch(() => []);
485
+ // The move's own request and anything after it are not the work.
486
+ const entries = conversationEntries(lines, from.source);
487
+ const asked = requestIndex(entries, record.id);
488
+ const original = record.dispatch ? await this.deps.brief?.(record.dispatch).catch(() => undefined) : undefined;
489
+ return fallbackHandoff({ reason, from: harnessName({ harness: from.source, account: record.from.account }),
490
+ entries: asked < 0 ? entries : entries.slice(0, asked), ...(original ? { original } : {}),
491
+ ...(record.dispatch ? { dispatch: record.dispatch } : {}), ...(record.from.label ? { label: record.from.label } : {}) });
492
+ }
493
+ /** Ends the old agent with its own exit command; an interrupt, then a kill, only when it hangs. */
494
+ async exit(record) {
495
+ const from = record.from.target;
496
+ const exitMs = this.deps.exitMs ?? 20_000;
497
+ const gone = async (ms) => {
498
+ const until = this.now + ms;
499
+ for (;;) {
500
+ const pane = findPane(await this.deps.snapshot(from.server), placeOf(from));
501
+ if (!pane)
502
+ throw new BridgeError(409, "The pane closed while the old agent exited; nothing was started.");
503
+ if (pane.agent !== from.source)
504
+ return true;
505
+ if (this.now >= until)
506
+ return false;
507
+ await this.sleep(Math.min(this.poll, 500));
508
+ }
509
+ };
510
+ const pane = findPane(await this.deps.snapshot(from.server), placeOf(from));
511
+ // A turn still running (a hand-off that ran late) is stopped first, as Esc in the terminal would.
512
+ if (pane?.agent_status === "working") {
513
+ await this.deps.terminal.sendKeys(from.server, from.pane, ["esc"]).catch(() => undefined);
514
+ await this.sleep(1_000);
515
+ }
516
+ await this.deps.terminal.prompt(from.server, from.pane, EXIT_COMMANDS[from.source] ?? "/exit").catch(() => undefined);
517
+ if (await gone(exitMs))
518
+ return "clean";
519
+ for (let n = 0; n < 2; n++) {
520
+ await this.deps.terminal.sendKeys(from.server, from.pane, ["ctrl+c"]).catch(() => undefined);
521
+ await this.sleep(500);
522
+ }
523
+ if (await gone(5_000))
524
+ return "interrupted";
525
+ const { foregroundPids, shellPid } = await this.deps.terminal.processes(from.server, from.pane);
526
+ const agent = foregroundPids.filter(pid => pid !== shellPid);
527
+ const kill = this.deps.kill ?? ((pid, signal) => process.kill(pid, signal));
528
+ for (const signal of ["SIGTERM", "SIGKILL"]) {
529
+ for (const pid of agent) {
530
+ try {
531
+ kill(pid, signal);
532
+ }
533
+ catch { /* already gone */ }
534
+ }
535
+ if (await gone(5_000))
536
+ return "killed";
537
+ }
538
+ throw new BridgeError(409, "The old agent did not exit, even when killed; nothing was started.");
539
+ }
540
+ /** Starts the target in the old pane when its shell has what the target needs, else in a new tab beside it. */
541
+ async relaunch(record, prompt) {
542
+ const from = record.from.target;
543
+ const s = await this.deps.snapshot(from.server);
544
+ const pane = findPane(s, placeOf(from));
545
+ if (!pane)
546
+ throw new BridgeError(409, "The pane closed after the old agent exited.");
547
+ // A Claude target with no account keeps the pane's own, so its shell's CLAUDE_CONFIG_DIR is right.
548
+ const shellAccount = record.from.account ?? DEFAULT_ACCOUNT;
549
+ const account = record.to.harness === "claude" ? record.to.account ?? shellAccount : undefined;
550
+ const samePane = (this.deps.envAtStart?.(from.server) ?? false) || record.to.harness !== "claude" || account === shellAccount;
551
+ const data = { kind: record.to.harness, label: record.from.label ?? HARNESS_NAMES[record.to.harness], cwd: record.cwd,
552
+ ...(record.to.model ? { model: record.to.model } : {}), ...(record.to.effort ? { effort: record.to.effort } : {}), ...(account ? { account } : {}),
553
+ brief: { id: record.id, text: prompt }, ...(samePane ? {} : { workspaceId: from.workspace }) };
554
+ const into = samePane ? { workspaceId: from.workspace, tabId: from.tab, paneId: from.pane } : undefined;
555
+ const launched = await this.deps.launch(from.server, data, { ...(into ? { into } : {}), ...(record.dispatch ? { dispatchId: record.dispatch } : {}) });
556
+ // The target that takes no brief at launch (Copilot) gets it typed, as dispatch does.
557
+ if (launched.briefLaunched === false) {
558
+ const typedTo = targetSchema.safeParse(launched.target);
559
+ if (typedTo.success)
560
+ await this.deps.deliver(typedTo.data, prompt, `move-${record.id}-brief`).catch(() => undefined);
561
+ else
562
+ await this.deps.terminal.prompt(from.server, String(launched.paneId), prompt).catch(() => undefined);
563
+ }
564
+ if (!samePane)
565
+ await this.deps.terminal.closePane(from.server, from.pane).catch(() => undefined);
566
+ // The account the new agent runs under, also when the move named none.
567
+ const to = account ? { ...record.to, account } : record.to;
568
+ return { to, placement: samePane ? "same-pane" : "adjacent-pane", ...await this.newTarget(from.server, launched, record.to.harness) };
569
+ }
570
+ /** The new agent's full target, waiting a little for its conversation id when the launch did not have it yet. */
571
+ async newTarget(server, launched, source) {
572
+ const full = targetSchema.safeParse(launched.target);
573
+ if (full.success)
574
+ return { target: full.data };
575
+ const place = { server, workspace: String(launched.workspaceId), tab: String(launched.tabId), pane: String(launched.paneId), source };
576
+ for (const until = this.now + 30_000; this.now < until; await this.sleep(this.poll)) {
577
+ const pane = findPane(await this.deps.snapshot(server).catch(() => ({})), place);
578
+ const session = pane && pane.agent === source ? await this.deps.identity(server, pane).catch(() => undefined) : undefined;
579
+ const target = targetSchema.safeParse({ ...place, session });
580
+ if (target.success)
581
+ return { target: target.data };
582
+ }
583
+ const starting = startingTargetSchema.safeParse(launched.target);
584
+ return starting.success ? { target: starting.data } : {};
585
+ }
586
+ }
587
+ /** The last `bytes` of a transcript as lines, the first (cut) one dropped. */
588
+ export async function transcriptTail(file, bytes = 512 * 1024) {
589
+ const handle = await open(file, "r");
590
+ try {
591
+ const { size } = await handle.stat();
592
+ const start = Math.max(0, size - bytes), buffer = Buffer.alloc(size - start);
593
+ await handle.read(buffer, 0, buffer.length, start);
594
+ const lines = buffer.toString("utf8").split("\n");
595
+ return start > 0 ? lines.slice(1) : lines;
596
+ }
597
+ finally {
598
+ await handle.close();
599
+ }
600
+ }
@@ -8,6 +8,21 @@ export interface Subscription {
8
8
  }
9
9
  /** Provider identifiers, not arbitrary free text or credentials. */
10
10
  export declare function planName(value: unknown): string | undefined;
11
+ /**
12
+ * A Claude login's plan from its oauthAccount profile, as Claude names it:
13
+ * the organization type first (a Team or Enterprise seat can carry any rate
14
+ * tier), the rate tier only for Pro and Max's 5x or 20x, then the billing
15
+ * type and Claude Code's own `subscriptionType`. Internal tier codes
16
+ * ("default_raven") are never shown; an unknown plan is undefined.
17
+ */
18
+ export declare function claudePlan(profile: {
19
+ organizationType?: unknown;
20
+ seatTier?: unknown;
21
+ organizationRateLimitTier?: unknown;
22
+ userRateLimitTier?: unknown;
23
+ billingType?: unknown;
24
+ subscriptionType?: unknown;
25
+ }): string | undefined;
11
26
  export declare function subscriptionDate(value: unknown): string | undefined;
12
27
  /** Next anniversary in UTC, always using the original day (Jan 31 -> Feb 28 -> Mar 31). */
13
28
  export declare function monthlyAnniversary(startedAt: string, now: Date): string | undefined;
@@ -5,6 +5,29 @@ export function planName(value) {
5
5
  return value.trim().replace(/^default_claude_/, "").replace(/^claude_/, "").split(/[_ -]+/)
6
6
  .map(word => /^\d+x$/i.test(word) ? word.toLowerCase() : word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join(" ");
7
7
  }
8
+ const CLAUDE_PLANS = { pro: "Pro", max: "Max", team: "Team", enterprise: "Enterprise" };
9
+ /**
10
+ * A Claude login's plan from its oauthAccount profile, as Claude names it:
11
+ * the organization type first (a Team or Enterprise seat can carry any rate
12
+ * tier), the rate tier only for Pro and Max's 5x or 20x, then the billing
13
+ * type and Claude Code's own `subscriptionType`. Internal tier codes
14
+ * ("default_raven") are never shown; an unknown plan is undefined.
15
+ */
16
+ export function claudePlan(profile) {
17
+ const text = (value) => typeof value === "string" && value.length <= 64 ? value.toLowerCase() : "";
18
+ const kind = (value) => /^(?:claude_)?(pro|max|team|enterprise)(?:_subscription)?$/.exec(value)?.[1];
19
+ const tier = [text(profile.organizationRateLimitTier), text(profile.userRateLimitTier)];
20
+ const multiple = tier.map(value => /^default_claude_max_(5|20)x$/.exec(value)?.[1]).find(Boolean);
21
+ const fromTier = tier.map(value => value === "default_claude_ai" || value === "default_claude_pro" ? "pro" : /^default_claude_max(?:_\d+x)?$/.test(value) ? "max" : undefined).find(Boolean);
22
+ const plan = kind(text(profile.organizationType)) ?? fromTier ?? kind(text(profile.billingType)) ?? kind(text(profile.subscriptionType));
23
+ if (!plan)
24
+ return undefined;
25
+ if (plan === "max" && multiple)
26
+ return `Max ${multiple}x`;
27
+ if (plan === "team" && text(profile.seatTier) === "team_premium")
28
+ return "Team Premium";
29
+ return CLAUDE_PLANS[plan];
30
+ }
8
31
  export function subscriptionDate(value) {
9
32
  const time = typeof value === "string" && /^\d{4}-\d{2}-\d{2}(?:T.*)?$/.test(value) ? Date.parse(value)
10
33
  : typeof value === "number" && Number.isSafeInteger(value) && value > 0 && value < 32_503_680_000 ? value * 1000 : NaN;