@phren/cli 0.3.56 → 0.3.57

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.
@@ -2,6 +2,8 @@ import { EXPECTED_REPOSITORY_REQUIRED, isGitWriteRoute } from "./git-write-polic
2
2
  import path from "node:path";
3
3
  import { setTimeout as sleep } from "node:timers/promises";
4
4
  import { z } from "zod";
5
+ import { TURN_ENDED_WITHOUT_IT } from "./prompt-deliveries.js";
6
+ import { claudeSubagentView } from "./claude-suggestion.js";
5
7
  import { gitBranches, gitDiscard, gitLog, gitPulls, gitShow, gitStage, gitStatus, gitTree, gitUnstage } from "./git.js";
6
8
  import { fanoutWorktrees } from "./fanouts.js";
7
9
  import { gitWorktrees, resolveWorktree } from "./git-worktrees.js";
@@ -26,6 +28,7 @@ import { fileSearchSchema, listRepositoryFiles, searchRepository } from "./file-
26
28
  import { deliveryIdSchema, PromptOnce, promptScope } from "./prompt-once.js";
27
29
  import { promptWithStartupRetry } from "./prompt-startup.js";
28
30
  import { sendServedPrompt, servedPane } from "./opencode-panes.js";
31
+ import { claudeSuggestionShown } from "./claude-suggestion.js";
29
32
  export /** A file from the phone: a plain name and base64 bytes, bounded. */ function uploadBody(data) {
30
33
  const name = z.string().regex(/^[A-Za-z0-9_][A-Za-z0-9_ .()-]{0,199}$/).refine(n => !n.includes("..")).parse(data.name);
31
34
  const encoded = z.string().max(11_184_812).regex(/^[A-Za-z0-9+/]*={0,2}$/).parse(data.data);
@@ -126,6 +129,27 @@ export function promptGuards(agentHooks, target) {
126
129
  return { held: () => !!(agentHooks.approval(target) || agentHooks.terminalPrompt(target) || agentHooks.servedQuestion(target)),
127
130
  screen: () => terminalProvider().readScreen(target.server, target.pane, { scope: "pane", source: "visible", lines: 40, format: "ansi", timeoutMs: 2_000 }) };
128
131
  }
132
+ /** Whether a hand-off would relay the Claude pane's own prompt suggestion: the dim guess at the owner's next message
133
+ * that Claude draws in its empty input box. Read as plain text it looks like an owner message left unsent, Enter does
134
+ * not submit it, and a conductor watching panes relayed three of them as the owner's words, one a merge instruction
135
+ * the owner never gave (2026-10-18). An unreadable screen does not refuse. */
136
+ async function relaysSuggestion(target, text) {
137
+ let screen = "";
138
+ try {
139
+ screen = await terminalProvider().readScreen(target.server, target.pane, { scope: "pane", source: "visible", lines: 40, format: "ansi", timeoutMs: 2_000 });
140
+ }
141
+ catch {
142
+ return false;
143
+ }
144
+ const shown = claudeSuggestionShown(screen);
145
+ // Case is kept (file and branch names differ by it); a leading voice marker says nothing about who wrote the words.
146
+ const plain = (value) => value.replace(/\s+/g, " ").trim().replace(/^\[voice\]\s*/i, "");
147
+ if (shown === undefined)
148
+ return false;
149
+ // A narrow pane cuts a long suggestion with "…": its visible part, with or without the mark, is all a screen read shows.
150
+ const words = plain(text), cut = shown.endsWith("…") ? plain(shown.slice(0, -1)) : undefined;
151
+ return words === plain(shown) || (cut !== undefined && (words === cut || words === `${cut}…` || words === `${cut} …`));
152
+ }
129
153
  /** Herdr answered the request with a refusal (a 409 carrying its own error code): it performed nothing. */
130
154
  const herdrRefused = (error) => error instanceof BridgeError && error.status === 409 && typeof error.details?.herdrCode === "string";
131
155
  /** An idle agent that has not taken typed text within the first wait
@@ -151,6 +175,88 @@ async function resubmitIfIdle(agentHooks, target, text) {
151
175
  return outcome;
152
176
  return await status() === "working" ? "pending" : "unsubmitted";
153
177
  }
178
+ /** A Claude pane showing a subagent's view (its empty input reads "Message
179
+ * @<agent>…") takes typed text for that subagent, so a phone message never
180
+ * reached the turn and failed when it ended (owner, 2026-10-21). Escape returns
181
+ * to the main view. It is pressed once, only while that view shows: in the main
182
+ * view Escape would interrupt the turn, so a view still showing after it is left
183
+ * as it is and logged. True when the view was left. */
184
+ export async function leaveClaudeSubagentView(agentHooks, target, waitMs = 250) {
185
+ if (target.source !== "claude")
186
+ return false;
187
+ const shows = async () => {
188
+ let screen;
189
+ try {
190
+ screen = await agentHooks.paneAnsi?.(target);
191
+ }
192
+ catch {
193
+ screen = undefined;
194
+ }
195
+ return screen !== undefined && claudeSubagentView(screen);
196
+ };
197
+ if (!await shows())
198
+ return false;
199
+ process.stderr.write(`phren hook: ${target.server}:${target.pane} shows a subagent view; Escape back to the conversation before typing\n`);
200
+ await terminalProvider().sendKeys(target.server, target.pane, ["esc"]);
201
+ await sleep(waitMs);
202
+ if (!await shows())
203
+ return true;
204
+ process.stderr.write(`phren hook: ${target.server}:${target.pane} still shows a subagent view after Escape; not pressing it again\n`);
205
+ return false;
206
+ }
207
+ /** A phone message the turn ended without, in a Claude pane that now shows a
208
+ * subagent's view (opened while the message waited): leave the view and type
209
+ * it again under the same delivery id, once. Any other outcome, a changed
210
+ * pane, or ten minutes end the watch. */
211
+ export function retryAfterSubagentView(agentHooks, target, terminal, text, id, intervalMs = 2_000, limitMs = 600_000, escapeWaitMs = 250) {
212
+ const started = Date.now();
213
+ const look = async () => {
214
+ if (Date.now() - started > limitMs)
215
+ return;
216
+ const status = agentHooks.deliveries.status(id, target);
217
+ if (status.state !== "failed") {
218
+ if (status.state !== "delivered")
219
+ schedule();
220
+ return;
221
+ }
222
+ if (status.reason !== TURN_ENDED_WITHOUT_IT)
223
+ return;
224
+ // The same conversation, as the route checks it: a /clear or /resume in the
225
+ // same terminal is another conversation, never given the old message.
226
+ // A refusal (409: the conversation changed or the pane went) ends the watch;
227
+ // a look that failed for now (a timeout) or an agent busy again waits.
228
+ let pane;
229
+ try {
230
+ pane = await validateTarget(target, true, true);
231
+ }
232
+ catch (error) {
233
+ if (error instanceof BridgeError && error.status === 409)
234
+ return;
235
+ schedule();
236
+ return;
237
+ }
238
+ if (!pane || pane.terminal_id !== terminal)
239
+ return;
240
+ if (!["idle", "done"].includes(String(pane.agent_status))) {
241
+ schedule();
242
+ return;
243
+ }
244
+ if (!await leaveClaudeSubagentView(agentHooks, target, escapeWaitMs))
245
+ return;
246
+ // Checked again with nothing awaited before the record is replaced: a retry
247
+ // from the phone may have delivered it meanwhile.
248
+ const now = agentHooks.deliveries.status(id, target);
249
+ if (now.state !== "failed" || now.reason !== TURN_ENDED_WITHOUT_IT)
250
+ return;
251
+ process.stderr.write(`phren hook: retrying phone message ${id} in the conversation after leaving the subagent view\n`);
252
+ const expected = agentHooks.deliveries.expect(target, text, 1_500, undefined, id, typeof terminal === "string" ? terminal : undefined);
253
+ await terminalProvider().prompt(target.server, target.pane, text);
254
+ if (await expected === "pending")
255
+ await resubmitIfIdle(agentHooks, target, text);
256
+ };
257
+ const schedule = () => { const timer = setTimeout(() => void look().catch(() => undefined), intervalMs); timer.unref?.(); };
258
+ schedule();
259
+ }
154
260
  /** A busy Claude Code queues typed text on Enter, but after a long paste
155
261
  * ("paste again to expand") it can swallow that Enter and leave the text in
156
262
  * its input line, where it stays after the turn ends. Follow the pane: once
@@ -402,6 +508,9 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
402
508
  // A Claude lead waiting on its background agents takes a prompt though Herdr reads it working (`takesPrompt`).
403
509
  if (data.hookQueued === true && !await takesPrompt(target.server, pane, target.session, promptGuards(agentHooks, target)))
404
510
  throw new BridgeError(409, "The worker is busy; the hand-off remains queued.", { code: "hand-off-busy" });
511
+ if (data.hookQueued === true && target.source === "claude" && typeof data.text === "string" && await relaysSuggestion(target, data.text)) {
512
+ throw new BridgeError(409, "That text is Claude's own suggested next prompt, drawn dim in the agent's empty input box. The owner did not send it, so it was not typed.", { code: "prompt-suggestion" });
513
+ }
405
514
  if (status === "unknown" || (["blocked", "waiting"].includes(status) && (agentHooks.approval(target) || agentHooks.terminalPrompt(target) || agentHooks.servedQuestion(target)))) {
406
515
  throw new BridgeError(409, "This agent needs input in the terminal first.");
407
516
  }
@@ -478,6 +587,7 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
478
587
  try {
479
588
  await typing();
480
589
  typed = true;
590
+ await leaveClaudeSubagentView(agentHooks, target);
481
591
  await terminalProvider().prompt(target.server, target.pane, text);
482
592
  }
483
593
  catch (error) {
@@ -508,6 +618,8 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
508
618
  else
509
619
  followQueuedDelivery(agentHooks, target, pane.terminal_id, text);
510
620
  }
621
+ if (deliveryId && target.source === "claude" && outcome !== "delivered")
622
+ retryAfterSubagentView(agentHooks, target, pane.terminal_id, text, deliveryId);
511
623
  // A bare slash command opens the agent's own menu; the phone may
512
624
  // walk it with keys for the next half minute. The command rides
513
625
  // along so a Codex /permissions walk can find its confirmation.
@@ -144,6 +144,7 @@ export declare const capabilities: {
144
144
  moveConductor: boolean;
145
145
  moveToComputer: boolean;
146
146
  moveConductorToComputer: boolean;
147
+ moveResume: boolean;
147
148
  claudeAccountAdd: boolean;
148
149
  workerRelocation: number;
149
150
  projectMemory: boolean;
@@ -89,7 +89,7 @@ async function childActivity(source, session) {
89
89
  export const capabilities = { transcript: true, progress: true, images: true, prompt: true, stop: true,
90
90
  terminal: "ssh-pty", shell: "ssh-pty", paneTerminal: "ssh-pty", paneLayout: true, deskPresence: true, herdr: true, sessionRename: true, diff: true, webServers: true, webPreview: "ssh-exec", activity: true,
91
91
  approvals: true, questions: false, accountUsage: true, providers: ["codex", "claude", "copilot", "opencode"],
92
- files: true, repositoryFiles: true, fileResolution: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, setLink: true, ownerInbox: true, workerReports: true, queuedHandOff: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, codeFiles: true, overviewStream: true, speech: true, speechTimestamps: true, speechTimestampStream: true, speechLive: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, deliveryFrames: true, paneDeliveries: true, resources: true, sudo: true, sudoOutcome: true, previewDeltas: true, quickChat: true, agentFolder: true, launchPermissionMode: true, sessionMove: true, moveNewChat: true, moveConductor: true, moveToComputer: true, moveConductorToComputer: true, claudeAccountAdd: true, workerRelocation: 1, projectMemory: true, fileWrite: true, fileSearch: true, gitReview: true, memoryStoreBatch: true, gitHosts: true, projectHostToken: true };
92
+ files: true, repositoryFiles: true, fileResolution: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, setLink: true, ownerInbox: true, workerReports: true, queuedHandOff: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, codeFiles: true, overviewStream: true, speech: true, speechTimestamps: true, speechTimestampStream: true, speechLive: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, deliveryFrames: true, paneDeliveries: true, resources: true, sudo: true, sudoOutcome: true, previewDeltas: true, quickChat: true, agentFolder: true, launchPermissionMode: true, sessionMove: true, moveNewChat: true, moveConductor: true, moveToComputer: true, moveConductorToComputer: true, moveResume: true, claudeAccountAdd: true, workerRelocation: 1, projectMemory: true, fileWrite: true, fileSearch: true, gitReview: true, memoryStoreBatch: true, gitHosts: true, projectHostToken: true };
93
93
  export function capabilitiesForModules(snapshot) {
94
94
  const allowed = new Set(snapshot.modules.flatMap(module => module.capabilities));
95
95
  const result = Object.fromEntries(Object.entries(capabilities).filter(([name]) => allowed.has(name)));
@@ -56,7 +56,7 @@ import { typedMuxRequest } from "./mux-wire.js";
56
56
  import { overviewStream } from "./server-overview.js";
57
57
  import { transcriptStreams } from "./server-stream.js";
58
58
  import { launchSession } from "./server-launch.js";
59
- import { SessionMover, transcriptTail } from "./session-move.js";
59
+ import { copyClaudeConversation, SessionMover, transcriptTail } from "./session-move.js";
60
60
  import { harnessInventoryWithin, launchCheckOff } from "./harnesses.js";
61
61
  import { paneAccount, paneAccountKey } from "./pane-accounts.js";
62
62
  import { readTurn } from "./turn-records.js";
@@ -178,6 +178,7 @@ export async function serve(version, options = {}) {
178
178
  launch: (server, data, options) => launches.run(() => launchSession(server, data, { trustFolder: true, ...options })),
179
179
  inventory: () => launchCheckOff() ? Promise.resolve(undefined) : harnessInventoryWithin(2_500),
180
180
  transcript: async (target) => transcriptTail(await targetTranscriptPath(target)),
181
+ copyConversation: async (target, home, check) => copyClaudeConversation(await targetTranscriptPath(target), home, process.env, check),
181
182
  paneAccount: (server, pane) => paneAccount(paneAccountKey(server, pane.pane_id), typeof pane.terminal_id === "string" ? pane.terminal_id : undefined)?.id,
182
183
  paneDispatch: async (server, pane) => {
183
184
  const dispatch = (await readTurn(server, String(pane.pane_id)))?.dispatch;
@@ -1,5 +1,6 @@
1
1
  import type { ConductorSuccessionService } from "./conductor-succession.js";
2
2
  import { z } from "zod";
3
+ import { type ClaudeHome } from "./claude-accounts.js";
3
4
  import { moveToSchema } from "./dispatch.js";
4
5
  import { type HarnessInventory } from "./harnesses.js";
5
6
  import { type Json, type Provider, type StartingTarget, type Target } from "./protocol.js";
@@ -44,6 +45,10 @@ export declare const moveRequestSchema: z.ZodObject<{
44
45
  "new-chat": "new-chat";
45
46
  replace: "replace";
46
47
  }>>;
48
+ continuation: z.ZodDefault<z.ZodEnum<{
49
+ handoff: "handoff";
50
+ resume: "resume";
51
+ }>>;
47
52
  id: z.ZodOptional<z.ZodString>;
48
53
  handoffTimeoutMs: z.ZodOptional<z.ZodNumber>;
49
54
  }, z.core.$strict>;
@@ -105,6 +110,7 @@ declare const moveRecordSchema: z.ZodObject<{
105
110
  "new-chat": "new-chat";
106
111
  replace: "replace";
107
112
  }>>;
113
+ continuation: z.ZodOptional<z.ZodLiteral<"resume">>;
108
114
  modeForced: z.ZodOptional<z.ZodLiteral<"conductor">>;
109
115
  handedOffTo: z.ZodOptional<z.ZodObject<{
110
116
  computer: z.ZodOptional<z.ZodString>;
@@ -326,10 +332,14 @@ export interface MoverDeps {
326
332
  paneId: string;
327
333
  };
328
334
  dispatchId?: string;
335
+ resumeClaude?: string;
329
336
  }) => Promise<Json>;
330
337
  inventory: () => Promise<HarnessInventory | undefined>;
331
338
  /** The conversation's transcript lines, its tail is enough. */
332
339
  transcript: (target: Target) => Promise<string[]>;
340
+ /** Copies a Claude conversation into another account's home (`copyClaudeConversation` over its transcript).
341
+ * With `check`, only resolves and validates both ends, so a move is refused before the old agent exits. */
342
+ copyConversation?: (target: Target, to: ClaudeHome, check?: boolean) => Promise<string>;
333
343
  git?: (directory: string) => Promise<GitState | undefined>;
334
344
  processesBelow?: (pids: readonly number[]) => Promise<string[]>;
335
345
  /** The Claude account the pane runs under, when known. */
@@ -385,6 +395,10 @@ export declare class SessionMover {
385
395
  /** The agent's own hand-off, or why there is none. Fails only when the session itself went away. */
386
396
  private askForHandoff;
387
397
  private fallback;
398
+ /** The same conversation under another Claude account: the old agent exits,
399
+ * its transcript (now final) is copied into the target home, and Claude
400
+ * resumes it there. Nothing is asked of the old agent, so its quota does not matter. */
401
+ private switchAccount;
388
402
  /** Ends the old agent with its own exit command; an interrupt, then a kill, only when it hangs. */
389
403
  private exit;
390
404
  /** Starts the target in the old pane when its shell has what the target needs, else in a new tab beside it. */
@@ -394,3 +408,14 @@ export declare class SessionMover {
394
408
  }
395
409
  /** The last `bytes` of a transcript as lines, the first (cut) one dropped. */
396
410
  export declare function transcriptTail(file: string, bytes?: number): Promise<string[]>;
411
+ /**
412
+ * Copies a Claude conversation into another account's home, at the same
413
+ * `projects/<folder key>/<session>.jsonl` path Claude reads it from with
414
+ * `--resume`, together with the session's own folder (subagent transcripts,
415
+ * tool results) when it has one. A copy already there is replaced: the
416
+ * source is the conversation as it stands now. Returns the copied transcript.
417
+ * Both ends are checked against the homes' real `projects` folders, so a
418
+ * symlinked folder inside the target home cannot redirect the write. With
419
+ * `check`, nothing is written.
420
+ */
421
+ export declare function copyClaudeConversation(file: string, to: ClaudeHome, env?: NodeJS.ProcessEnv, check?: boolean): Promise<string>;
@@ -22,14 +22,14 @@ import { redactApproval } from "./approval-summary.js";
22
22
  import { stableComputerName } from "./computer-names.js";
23
23
  import { execFile } from "node:child_process";
24
24
  import { randomUUID } from "node:crypto";
25
- import { lstat, mkdir, open, readFile, readdir, realpath, rm } from "node:fs/promises";
25
+ import { copyFile, cp, lstat, mkdir, open, readFile, readdir, realpath, rename, rm, stat } from "node:fs/promises";
26
26
  import path from "node:path";
27
27
  import { promisify } from "node:util";
28
28
  import { z } from "zod";
29
29
  import { logger } from "../logger.js";
30
30
  import { quoted, withOriginalBrief } from "./account-failover.js";
31
31
  import { recordedConductor, runsAgent, transferConductor } from "./conductor-role.js";
32
- import { DEFAULT_ACCOUNT } from "./claude-accounts.js";
32
+ import { claudeHome, claudeHomes, DEFAULT_ACCOUNT } from "./claude-accounts.js";
33
33
  import { DISPATCH_HARNESSES, DispatchService, dispatchProjectDirectory, projectName, moveToSchema, repointDispatchOrigins } from "./dispatch.js";
34
34
  import { hasUsable } from "./harnesses.js";
35
35
  import { findPane } from "./herdr.js";
@@ -42,6 +42,11 @@ export const moveRequestSchema = z.object({
42
42
  target: targetSchema,
43
43
  to: moveToSchema,
44
44
  mode: z.enum(["replace", "new-chat"]).default("replace"),
45
+ /** `resume` switches a Claude conversation to another account on this
46
+ * computer without a hand-off: the transcript is copied into the target
47
+ * account's home and the same conversation resumes there (`claude --resume`),
48
+ * so an account at its usage limit can still switch. */
49
+ continuation: z.enum(["handoff", "resume"]).default("handoff"),
45
50
  /** Kept on a retry: the same id returns the move already under way. */
46
51
  id: z.string().uuid().optional(),
47
52
  /** How long the agent gets to write its hand-off before Phren builds one. */
@@ -60,6 +65,7 @@ const moveRecordSchema = z.object({
60
65
  accountChoice: z.string().max(400).optional(),
61
66
  project: projectName.optional(),
62
67
  mode: z.enum(["replace", "new-chat"]).optional(),
68
+ continuation: z.literal("resume").optional(),
63
69
  modeForced: z.literal("conductor").optional(),
64
70
  handedOffTo: z.object({ computer: z.string().optional(), target: z.union([targetSchema, startingTargetSchema]) }).strict().optional(),
65
71
  handedOffFrom: z.object({ target: targetSchema, title: z.string().max(200) }).strict().optional(),
@@ -468,6 +474,25 @@ export class SessionMover {
468
474
  const sameHarness = to.harness === target.source && (to.harness !== "claude" || (to.account ?? account) === account);
469
475
  if (!peer && sameHarness && !to.model && !to.effort)
470
476
  throw new BridgeError(400, "The session already runs there. Choose another harness, account, model or effort.");
477
+ if (data.continuation === "resume") {
478
+ if (peer)
479
+ throw new BridgeError(400, "Switching account keeps the conversation on this computer; continue on another computer with a hand-off.");
480
+ if (target.source !== "claude" || to.harness !== "claude")
481
+ throw new BridgeError(400, "Only a Claude conversation can switch account.");
482
+ if (!target.session)
483
+ throw new BridgeError(409, "The conversation has no session id yet, so it cannot resume under another account.");
484
+ if (data.mode === "new-chat")
485
+ throw new BridgeError(400, "Switching account continues the same conversation; it cannot keep the old chat running.");
486
+ if (conductor)
487
+ throw new BridgeError(409, "Switching the conductor's account is not supported yet; use Continue in… for the conductor.");
488
+ if (!to.account || to.account === account)
489
+ throw new BridgeError(400, "Choose another Claude account to switch to.");
490
+ if (!claudeHome(to.account))
491
+ throw new BridgeError(409, `No Claude account "${to.account}" on this computer.`, { code: "account_unavailable" });
492
+ if (!this.deps.copyConversation)
493
+ throw new BridgeError(503, "This Hook cannot switch accounts.");
494
+ await this.deps.copyConversation(target, claudeHome(to.account), true);
495
+ }
471
496
  // Only harnesses signed in and usable here; an inventory that cannot be read lets the move go on, as a launch does.
472
497
  const inventory = peer ? undefined : await this.deps.inventory().catch(() => undefined);
473
498
  if (inventory) {
@@ -514,8 +539,9 @@ export class SessionMover {
514
539
  const workerDispatch = peer && dispatch ? await (await import("./worker-relocation.js")).preflightWorkerRelocation(dispatch, target) : undefined;
515
540
  const label = [pane.label, pane.title, pane.terminal_title_stripped, pane.agent_name].find(value => typeof value === "string" && value.trim() && !/^\d+$/.test(value));
516
541
  const at = new Date(this.now).toISOString();
517
- const record = { id: data.id ?? randomUUID(), state: "handing-off", createdAt: at, updatedAt: at,
518
- ...(project ? { project } : {}), mode: conductor || peer ? "new-chat" : data.mode, ...(conductor ? { modeForced: "conductor" } : {}), from: { target, ...(account ? { account } : {}), ...(label ? { label: label.slice(0, 200) } : {}) }, to, cwd, ...(computerId ? { computerId } : {}), ...(peer?.fingerprint ? { computerFingerprint: peer.fingerprint } : {}), ...(accountChoice ? { accountChoice } : {}),
542
+ const resume = data.continuation === "resume";
543
+ const record = { id: data.id ?? randomUUID(), state: resume ? "exiting" : "handing-off", createdAt: at, updatedAt: at,
544
+ ...(project ? { project } : {}), mode: conductor || peer ? "new-chat" : data.mode, ...(resume ? { continuation: "resume" } : {}), ...(conductor ? { modeForced: "conductor" } : {}), from: { target, ...(account ? { account } : {}), ...(label ? { label: label.slice(0, 200) } : {}) }, to, cwd, ...(computerId ? { computerId } : {}), ...(peer?.fingerprint ? { computerFingerprint: peer.fingerprint } : {}), ...(accountChoice ? { accountChoice } : {}),
519
545
  ...(dispatch && briefId.safeParse(dispatch).success ? { dispatch } : {}), ...(workerDispatch ? { workerDispatch } : {}) };
520
546
  await assertUnusedLaunchId(record.id);
521
547
  if (conductor && peer) {
@@ -525,7 +551,7 @@ export class SessionMover {
525
551
  }
526
552
  await saveMove(record);
527
553
  const key = `${target.server}\0${target.pane}`;
528
- const work = this.run(record, data.handoffTimeoutMs ?? DEFAULT_HANDOFF_MS, conductor, peer, project).finally(() => this.running.delete(key));
554
+ const work = (resume ? this.switchAccount(record) : this.run(record, data.handoffTimeoutMs ?? DEFAULT_HANDOFF_MS, conductor, peer, project)).finally(() => this.running.delete(key));
529
555
  this.running.set(key, work);
530
556
  return record;
531
557
  }
@@ -870,6 +896,36 @@ export class SessionMover {
870
896
  entries: asked < 0 ? entries : entries.slice(0, asked), ...(original ? { original } : {}),
871
897
  ...(record.dispatch ? { dispatch: record.dispatch } : {}), ...(record.from.label ? { label: record.from.label } : {}) });
872
898
  }
899
+ /** The same conversation under another Claude account: the old agent exits,
900
+ * its transcript (now final) is copied into the target home, and Claude
901
+ * resumes it there. Nothing is asked of the old agent, so its quota does not matter. */
902
+ async switchAccount(record) {
903
+ const from = record.from.target;
904
+ let copied = false;
905
+ try {
906
+ const exit = await this.exit(record);
907
+ await this.update(record, { exit });
908
+ await this.checkPromotion(record);
909
+ const home = claudeHome(record.to.account);
910
+ if (!home)
911
+ throw new BridgeError(409, `No Claude account "${record.to.account}" on this computer.`);
912
+ await this.deps.copyConversation(from, home);
913
+ copied = true;
914
+ await this.update(record, { state: "launching" });
915
+ const launched = await this.relaunch(record, { resume: from.session });
916
+ await this.update(record, { state: "moved", movedAt: new Date(this.now).toISOString(), ...launched });
917
+ logger.info("move", `Switched Claude in pane ${from.pane} from account ${record.from.account ?? DEFAULT_ACCOUNT} to ${record.to.account} (${launched.placement}).`);
918
+ }
919
+ catch (error) {
920
+ const message = (error instanceof Error ? error.message : String(error)).replace(/[\x00-\x1f\x7f]+/g, " ");
921
+ // Until the copy is complete only the old account holds the conversation.
922
+ const resumeHome = claudeHome(copied ? record.to.account : record.from.account);
923
+ const hint = record.exit !== undefined
924
+ ? ` The old agent has exited; resume it with \`claude --resume ${from.session}\`${resumeHome && !resumeHome.isDefault ? ` under CLAUDE_CONFIG_DIR=${resumeHome.dir}` : ""}.` : "";
925
+ await this.update(record, { state: "failed", error: `${message}${hint}`.slice(0, 500) }).catch(() => undefined);
926
+ logger.warn("move", `Switching the account of pane ${from.pane} failed: ${message}`);
927
+ }
928
+ }
873
929
  /** Ends the old agent with its own exit command; an interrupt, then a kill, only when it hangs. */
874
930
  async exit(record) {
875
931
  const from = record.from.target;
@@ -922,7 +978,8 @@ export class SessionMover {
922
978
  throw new BridgeError(409, "The old agent did not exit, even when killed; nothing was started.");
923
979
  }
924
980
  /** Starts the target in the old pane when its shell has what the target needs, else in a new tab beside it. */
925
- async relaunch(record, prompt) {
981
+ async relaunch(record, start) {
982
+ const prompt = typeof start === "string" ? start : undefined;
926
983
  const from = record.from.target;
927
984
  const s = await this.deps.snapshot(from.server);
928
985
  const pane = findPane(s, placeOf(from));
@@ -934,10 +991,11 @@ export class SessionMover {
934
991
  const samePane = record.mode !== "new-chat" && ((this.deps.envAtStart?.(from.server) ?? false) || record.to.harness !== "claude" || account === shellAccount);
935
992
  const data = { kind: record.to.harness, label: record.from.label ?? HARNESS_NAMES[record.to.harness], cwd: record.cwd,
936
993
  ...(record.to.model ? { model: record.to.model } : {}), ...(record.to.effort ? { effort: record.to.effort } : {}), ...(account ? { account } : {}),
937
- brief: { id: record.id, text: prompt }, ...(samePane ? {} : { workspaceId: from.workspace }) };
994
+ ...(prompt === undefined ? {} : { brief: { id: record.id, text: prompt } }), ...(samePane ? {} : { workspaceId: from.workspace }) };
938
995
  const into = samePane ? { workspaceId: from.workspace, tabId: from.tab, paneId: from.pane } : undefined;
939
996
  await this.checkPromotion(record);
940
- const launched = await this.deps.launch(from.server, data, { ...(into ? { into } : {}), ...(record.dispatch && record.modeForced !== "conductor" ? { dispatchId: record.dispatch } : {}) });
997
+ const launched = await this.deps.launch(from.server, data, { ...(into ? { into } : {}), ...(record.dispatch && record.modeForced !== "conductor" ? { dispatchId: record.dispatch } : {}),
998
+ ...(prompt === undefined ? { resumeClaude: start.resume } : {}) });
941
999
  // Keep the launched location even if delivering its first prompt fails.
942
1000
  const paneTarget = targetSchema.omit({ session: true }).parse({ server: from.server,
943
1001
  workspace: launched.workspaceId, tab: launched.tabId, pane: launched.paneId, source: record.to.harness });
@@ -945,7 +1003,7 @@ export class SessionMover {
945
1003
  await this.update(record, { paneTarget, placement: samePane ? "same-pane" : "adjacent-pane",
946
1004
  ...(launchedTarget.success ? { target: launchedTarget.data } : {}) });
947
1005
  // The target that takes no brief at launch (Copilot) gets it typed, as dispatch does.
948
- if (launched.briefLaunched === false) {
1006
+ if (prompt !== undefined && launched.briefLaunched === false) {
949
1007
  try {
950
1008
  const typedTo = targetSchema.safeParse(launched.target);
951
1009
  if (typedTo.success) {
@@ -1007,3 +1065,64 @@ export async function transcriptTail(file, bytes = 512 * 1024) {
1007
1065
  await handle.close();
1008
1066
  }
1009
1067
  }
1068
+ /**
1069
+ * Copies a Claude conversation into another account's home, at the same
1070
+ * `projects/<folder key>/<session>.jsonl` path Claude reads it from with
1071
+ * `--resume`, together with the session's own folder (subagent transcripts,
1072
+ * tool results) when it has one. A copy already there is replaced: the
1073
+ * source is the conversation as it stands now. Returns the copied transcript.
1074
+ * Both ends are checked against the homes' real `projects` folders, so a
1075
+ * symlinked folder inside the target home cannot redirect the write. With
1076
+ * `check`, nothing is written.
1077
+ */
1078
+ export async function copyClaudeConversation(file, to, env = process.env, check = false) {
1079
+ const real = async (dir) => realpath(dir).catch(() => path.resolve(dir));
1080
+ const inside = (child, parent) => child.startsWith(parent + path.sep);
1081
+ const source = await real(file);
1082
+ // A home's projects folder may be a link elsewhere, as transcriptPath allows.
1083
+ const homes = await Promise.all(claudeHomes(env).map(async (home) => ({ home, dir: await real(home.dir), projects: await real(path.join(home.dir, "projects")) })));
1084
+ const longest = (list) => list.sort((a, b) => b.projects.length - a.projects.length)[0];
1085
+ const match = longest(homes.filter(item => inside(source, item.projects))) ?? longest(homes.filter(item => inside(source, item.dir)));
1086
+ if (!match)
1087
+ throw new BridgeError(409, "The conversation's transcript is not in a Claude home on this computer.");
1088
+ const from = match.home;
1089
+ if (from.dir === to.dir)
1090
+ throw new BridgeError(400, "The conversation already belongs to that account.");
1091
+ const projects = match.projects;
1092
+ const relative = path.relative(projects, source);
1093
+ if (!relative || !inside(source, projects) || !relative.endsWith(".jsonl")) {
1094
+ throw new BridgeError(409, "The conversation's transcript is not under its Claude home's projects folder.");
1095
+ }
1096
+ const targetProjects = path.join(to.dir, "projects");
1097
+ const destination = path.join(targetProjects, relative);
1098
+ // The deepest folder that exists on the way must resolve inside the target home's projects folder (or be the home itself).
1099
+ const targetRoot = await real(targetProjects);
1100
+ let existing = path.dirname(destination);
1101
+ while (!(await lstat(existing).catch(() => undefined)) && existing !== path.dirname(existing) && existing !== to.dir)
1102
+ existing = path.dirname(existing);
1103
+ const resolved = await real(existing);
1104
+ if (resolved !== targetRoot && !inside(resolved, targetRoot) && resolved !== await real(to.dir)) {
1105
+ throw new BridgeError(409, "The other account's projects folder points outside its Claude home.");
1106
+ }
1107
+ if (check)
1108
+ return destination;
1109
+ await mkdir(path.dirname(destination), { recursive: true, mode: 0o700 });
1110
+ const temporary = `${destination}.${randomUUID()}.tmp`;
1111
+ try {
1112
+ await copyFile(source, temporary);
1113
+ await rename(temporary, destination);
1114
+ }
1115
+ catch (error) {
1116
+ await rm(temporary, { force: true }).catch(() => undefined);
1117
+ throw error;
1118
+ }
1119
+ const folder = source.slice(0, -".jsonl".length);
1120
+ if ((await stat(folder).catch(() => undefined))?.isDirectory()) {
1121
+ const folderTo = destination.slice(0, -".jsonl".length);
1122
+ // A link left at the folder's place is replaced, never followed.
1123
+ if ((await lstat(folderTo).catch(() => undefined))?.isSymbolicLink())
1124
+ await rm(folderTo, { force: true });
1125
+ await cp(folder, folderTo, { recursive: true, force: true, verbatimSymlinks: true });
1126
+ }
1127
+ return destination;
1128
+ }
@@ -51,17 +51,37 @@ export function failRelay(client) {
51
51
  }
52
52
  export function relayTranscription(client, query, options = {}) {
53
53
  const connect = options.connect ?? ((url, key) => new WebSocket(url, { headers: { "xi-api-key": key } }));
54
+ // The phone sends the audio it held while connecting as soon as the
55
+ // socket opens, before the key and region below are read: listen now and
56
+ // replay those frames once the relay is set up, so no opening word is lost.
57
+ let receive;
58
+ let early = [], earlyBytes = 0, hungUp = false;
59
+ client.on("message", (data, isBinary) => {
60
+ if (receive) {
61
+ receive(data, isBinary);
62
+ return;
63
+ }
64
+ // Past the relay's own limit the replay ends the session anyway.
65
+ if (early && (earlyBytes += data.length) <= MAX_PENDING_BYTES)
66
+ early.push([data, isBinary]);
67
+ });
68
+ client.on("close", () => { hungUp = true; });
54
69
  return (async () => {
55
70
  const key = await (options.key ?? readSpeechKey)();
56
71
  const tell = (frame) => { if (client.readyState === OPEN)
57
72
  client.send(JSON.stringify(frame)); };
73
+ if (hungUp)
74
+ return;
58
75
  if (!key) {
59
76
  tell({ type: "error", code: "transcribe-unconfigured", error: "This computer has no ElevenLabs key." });
60
77
  client.close(1008, "No ElevenLabs key");
61
78
  return;
62
79
  }
63
80
  const origin = options.origin ?? (await resolveSpeechRegion()).origin;
81
+ if (hungUp)
82
+ return;
64
83
  const upstream = connect(transcribeURL(query, origin), key);
84
+ // Held until ElevenLabs answers; null is the phone's stop, kept in its place.
65
85
  let pending = [], pendingBytes = 0, closed = false;
66
86
  const finish = (code = 1000, reason = "") => {
67
87
  if (closed)
@@ -82,13 +102,15 @@ export function relayTranscription(client, query, options = {}) {
82
102
  const chunk = (audio, commit = false) => JSON.stringify({
83
103
  message_type: "input_audio_chunk", audio_base_64: audio.toString("base64"), commit, sample_rate: TRANSCRIBE_RATE
84
104
  });
85
- client.on("message", (data, isBinary) => {
105
+ receive = (data, isBinary) => {
86
106
  if (closed)
87
107
  return;
88
108
  if (!isBinary) {
89
109
  // The phone's only text frame: the person stopped, commit what's left.
90
110
  if (upstream.readyState === OPEN)
91
111
  upstream.send(chunk(Buffer.alloc(0), true));
112
+ else
113
+ pending.push(null);
92
114
  return;
93
115
  }
94
116
  if (upstream.readyState === OPEN) {
@@ -102,12 +124,15 @@ export function relayTranscription(client, query, options = {}) {
102
124
  return;
103
125
  }
104
126
  pending.push(data);
105
- });
127
+ };
128
+ for (const [data, isBinary] of early ?? [])
129
+ receive(data, isBinary);
130
+ early = undefined;
106
131
  client.on("close", () => finish());
107
132
  client.on("error", () => finish());
108
133
  upstream.on("open", () => {
109
134
  for (const audio of pending)
110
- upstream.send(chunk(audio));
135
+ upstream.send(audio ? chunk(audio) : chunk(Buffer.alloc(0), true));
111
136
  pending = [];
112
137
  pendingBytes = 0;
113
138
  if (!closed)
@@ -18,13 +18,31 @@ export function phrenCommandLine(args) {
18
18
  return [["phren", ...args].map(shellWord).join(" "),
19
19
  `herdr pane release-agent "$HERDR_PANE_ID" --source ${PHREN_REPORT_SOURCE} --agent phren >/dev/null 2>&1`].join("; ");
20
20
  }
21
- /** Whether `pane` runs phren-agent as Herdr reports it, for the prompt and key fallbacks below. */
22
- async function reportedPhren(server, pane) {
21
+ /** Herdr's `agent.prompt` and `agent.send_keys` take only agents it started
22
+ * and still holds as active. A worker launched with its brief as the
23
+ * harness's first prompt goes straight to work and can stay `launch_pending`
24
+ * there, and an agent restarted in its pane (or alive across a Herdr restart)
25
+ * is detected but never named again; Herdr refuses all of them with
26
+ * `agent_not_ready` for good. Such a pane is typed into instead, the way the
27
+ * terminal view types, when its foreground program is the harness Herdr
28
+ * detects there (phren-agent counts by report alone, as Herdr cannot detect
29
+ * it). For a prompt Herdr must also read the agent at rest or at work, so
30
+ * text never lands in a starting harness or answers a dialog it draws. */
31
+ async function typableAgent(server, pane, forPrompt) {
23
32
  const info = object((await rpc(server, "pane.get", { pane_id: pane }).catch(() => ({}))).pane);
24
- return info.agent === "phren";
33
+ if (info.agent === "phren")
34
+ return true;
35
+ if (typeof info.agent !== "string" || !info.agent)
36
+ return false;
37
+ if (forPrompt && !["idle", "working", "done"].includes(String(info.agent_status)))
38
+ return false;
39
+ const processes = object((await rpc(server, "pane.process_info", { pane_id: pane }).catch(() => ({}))).process_info);
40
+ // The shell in the foreground would run the text as a command.
41
+ if (!Number.isSafeInteger(processes.foreground_process_group_id) || processes.foreground_process_group_id === processes.shell_pid)
42
+ return false;
43
+ return objects(processes.foreground_processes).some(p => typeof p.cmdline === "string" && agentFromCommand(p.cmdline) === info.agent);
25
44
  }
26
- /** Herdr's `agent.prompt` and `agent.send_keys` take only agents it started;
27
- * a phren-agent pane it knows by report gets the pane calls instead. */
45
+ /** The refusal `typableAgent` answers: an agent Herdr does not hold as named. */
28
46
  function unnamedAgent(error) {
29
47
  return error instanceof BridgeError && error.details?.herdrCode === "agent_not_ready" && /not an active named agent/.test(error.message);
30
48
  }
@@ -88,7 +106,7 @@ export const herdrTerminal = {
88
106
  await rpc(server, "agent.send_keys", { target: pane, keys });
89
107
  }
90
108
  catch (error) {
91
- if (!unnamedAgent(error) || !await reportedPhren(server, pane))
109
+ if (!unnamedAgent(error) || !await typableAgent(server, pane, false))
92
110
  throw error;
93
111
  await rpc(server, "pane.send_keys", { pane_id: pane, keys });
94
112
  }
@@ -115,9 +133,11 @@ export const herdrTerminal = {
115
133
  await rpc(server, "agent.prompt", { target: pane, text });
116
134
  }
117
135
  catch (error) {
118
- if (!unnamedAgent(error) || !await reportedPhren(server, pane))
136
+ if (!unnamedAgent(error) || !await typableAgent(server, pane, true))
119
137
  throw error;
120
- // One bracketed paste keeps the newlines in phren-agent's composer; Enter submits it.
138
+ // One bracketed paste keeps the newlines in the agent's composer; Enter submits it.
139
+ // The route's delivery record (by deliveryId) is already armed: the agent's
140
+ // UserPromptSubmit settles it, as for a prompt Herdr typed.
121
141
  await rpc(server, "pane.send_text", { pane_id: pane, text: `\x1b[200~${text}\x1b[201~` }, signal);
122
142
  await new Promise(resolve => setTimeout(resolve, 150));
123
143
  await rpc(server, "pane.send_keys", { pane_id: pane, keys: ["Enter"] }, signal);