@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.
@@ -6,3 +6,12 @@
6
6
  * offered, since sending half a sentence would be worse than nothing.
7
7
  */
8
8
  export declare function claudeSuggestion(screen: string): string | undefined;
9
+ /** The suggestion as drawn, a narrow pane's cut one ("…" at the end) included, for refusing a relay of what
10
+ * a screen read shows; undefined when there is none. */
11
+ export declare function claudeSuggestionShown(screen: string): string | undefined;
12
+ /** Claude Code showing a subagent's (or teammate's) view: its empty input box
13
+ * reads "Message @<agent>…". Text typed there goes to that agent, not the
14
+ * conversation, so a phone message typed into it never reaches the turn;
15
+ * Escape returns to the main view. */
16
+ export declare const SUBAGENT_VIEW: RegExp;
17
+ export declare function claudeSubagentView(screen: string): boolean;
@@ -20,6 +20,35 @@ const PLACEHOLDERS = [/^Try ".*"$/, /^Press (?:up|Enter) to /, /^Message @.*…$
20
20
  * offered, since sending half a sentence would be worse than nothing.
21
21
  */
22
22
  export function claudeSuggestion(screen) {
23
+ const text = liveInputDimText(screen);
24
+ if (!text || text.endsWith("…") || text.length > MAX_SUGGESTION || PLACEHOLDERS.some(pattern => pattern.test(text)))
25
+ return undefined;
26
+ return text;
27
+ }
28
+ /** The suggestion as drawn, a narrow pane's cut one ("…" at the end) included, for refusing a relay of what
29
+ * a screen read shows; undefined when there is none. */
30
+ export function claudeSuggestionShown(screen) {
31
+ const text = liveInputDimText(screen);
32
+ if (!text || text.length > MAX_SUGGESTION || PLACEHOLDERS.some(pattern => pattern.test(text)) || SUBAGENT_VIEW.test(text))
33
+ return undefined;
34
+ return text;
35
+ }
36
+ /** Claude Code showing a subagent's (or teammate's) view: its empty input box
37
+ * reads "Message @<agent>…". Text typed there goes to that agent, not the
38
+ * conversation, so a phone message typed into it never reaches the turn;
39
+ * Escape returns to the main view. */
40
+ // Only the bare placeholder, one agent name and nothing else: a suggestion
41
+ // that a narrow pane cut short ("Message @researcher to check…") is not one.
42
+ // Claude Code (2.1.303) cuts a name past 20 columns with its own "…" before the
43
+ // placeholder's: "Message @researcher-performa……".
44
+ export const SUBAGENT_VIEW = /^Message @[\w.-]{1,20}…?…$/;
45
+ export function claudeSubagentView(screen) {
46
+ const text = liveInputDimText(screen);
47
+ return !!text && SUBAGENT_VIEW.test(text);
48
+ }
49
+ /** The dim text in the live input box (between its two rules), "" when the
50
+ * box holds typed text, undefined when there is no live box on screen. */
51
+ function liveInputDimText(screen) {
23
52
  const lines = screen.split("\n").map(line => line.replace(/\r$/, ""));
24
53
  for (let index = lines.length - 2; index > 0; index--) {
25
54
  const plain = stripTerminal(lines[index]);
@@ -28,10 +57,7 @@ export function claudeSuggestion(screen) {
28
57
  // Only the live input box: a sent prompt in the history has no rules around it.
29
58
  if (!rule(stripTerminal(lines[index - 1])) || !rule(stripTerminal(lines[index + 1])))
30
59
  return undefined;
31
- const text = dimText(lines[index]);
32
- if (!text || text.endsWith("…") || text.length > MAX_SUGGESTION || PLACEHOLDERS.some(pattern => pattern.test(text)))
33
- return undefined;
34
- return text;
60
+ return dimText(lines[index]);
35
61
  }
36
62
  return undefined;
37
63
  }
@@ -89,12 +89,12 @@ export async function runHandOff(args) {
89
89
  console.log(JSON.stringify(result, null, 2));
90
90
  return result.ok ? 0 : 1;
91
91
  }
92
- 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>]";
92
+ const MOVE_USAGE = "Usage: phren move <session-or-pane> --to <claude|codex|opencode|copilot> [--model <model>] [--effort <effort>] [--account <id> [--resume]] [--computer <name>] [--no-wait] | phren move --status <move-id> [--computer <name>]";
93
93
  /** `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). */
94
94
  export async function runMove(args) {
95
95
  const { values, positionals } = parseArgs({ args, allowPositionals: true, options: {
96
96
  to: { type: "string" }, account: { type: "string" }, model: { type: "string" }, effort: { type: "string" }, computer: { type: "string" },
97
- status: { type: "string" }, id: { type: "string" }, "no-wait": { type: "boolean" },
97
+ status: { type: "string" }, id: { type: "string" }, "no-wait": { type: "boolean" }, resume: { type: "boolean" },
98
98
  } });
99
99
  const computer = values.computer ? { computer: values.computer } : {};
100
100
  if (values.status) {
@@ -109,7 +109,7 @@ export async function runMove(args) {
109
109
  const named = sessionId.safeParse(positionals[0]).success ? { session: positionals[0] } : { pane: positionals[0] };
110
110
  const result = await moveSession({ ...computer, ...named, harness: values.to, ...(values.account ? { account: values.account } : {}),
111
111
  ...(values.model ? { model: values.model } : {}), ...(values.effort ? { effort: values.effort } : {}), ...(values.id ? { id: values.id } : {}),
112
- ...(values["no-wait"] ? { wait: false } : {}) });
112
+ ...(values["no-wait"] ? { wait: false } : {}), ...(values.resume ? { resume: true } : {}) });
113
113
  console.log(JSON.stringify(result, null, 2));
114
114
  return result.ok ? 0 : 1;
115
115
  }
@@ -77,6 +77,7 @@ export declare const moveSessionSchema: z.ZodObject<{
77
77
  minimal: "minimal";
78
78
  xhigh: "xhigh";
79
79
  }>>;
80
+ resume: z.ZodOptional<z.ZodBoolean>;
80
81
  id: z.ZodOptional<z.ZodString>;
81
82
  status: z.ZodOptional<z.ZodBoolean>;
82
83
  wait: z.ZodOptional<z.ZodBoolean>;
@@ -131,6 +131,7 @@ export const moveSessionSchema = z.object({
131
131
  account: moveToSchema.shape.account,
132
132
  model: moveToSchema.shape.model,
133
133
  effort: moveToSchema.shape.effort,
134
+ resume: z.boolean().optional().describe("Switch a Claude conversation to another Claude account on this computer without a hand-off: the old agent exits, its transcript is copied into that account's home and the same conversation resumes there, so an account at its usage limit can still switch. Needs harness claude and account."),
134
135
  id: z.string().uuid().optional().describe("Move id: keep it on a retry, or pass it with status:true to read where the move is."),
135
136
  status: z.boolean().optional().describe("Read the move's state without starting one; requires id."),
136
137
  wait: z.boolean().optional().describe("Wait (up to five minutes) until the move finished or failed. Defaults to true."),
@@ -139,6 +140,8 @@ export const moveSessionSchema = z.object({
139
140
  context.addIssue({ code: "custom", message: "Provide exactly one of target, session or pane." });
140
141
  if (value.status && !value.id)
141
142
  context.addIssue({ code: "custom", message: "A status query requires id." });
143
+ if (value.resume && (value.harness !== "claude" || !value.account || value.computer))
144
+ context.addIssue({ code: "custom", message: "resume switches a Claude conversation on its own computer to another account: harness claude, an account, and no computer." });
142
145
  });
143
146
  const MOVE_WAIT_MS = 5 * 60_000;
144
147
  /** The live session in a pane, by the pane id the terminal shows. */
@@ -167,7 +170,8 @@ export async function moveSession(input, options = {}) {
167
170
  if (peer && target.server !== peer.server)
168
171
  throw new BridgeError(400, "The target belongs to a different Herdr server on that computer.");
169
172
  const to = { harness: data.harness, ...(data.account ? { account: data.account } : {}), ...(data.model ? { model: data.model } : {}), ...(data.effort ? { effort: data.effort } : {}) };
170
- move = object((await request("/v1/sessions/move", { target, to: moveToSchema.parse(to), ...(options.agent ? { origin: "agent" } : {}), ...(data.id ? { id: data.id } : {}) })).move);
173
+ move = object((await request("/v1/sessions/move", { target, to: moveToSchema.parse(to), ...(options.agent ? { origin: "agent" } : {}), ...(data.id ? { id: data.id } : {}),
174
+ ...(data.resume ? { continuation: "resume" } : {}) })).move);
171
175
  if (data.wait !== false && typeof move.id === "string") {
172
176
  const until = Date.now() + (options.waitMs ?? MOVE_WAIT_MS);
173
177
  while (!settled(move) && Date.now() < until) {
@@ -4,6 +4,13 @@ export declare function newPairingCode(): string;
4
4
  /** Codes are typed as ABC-234 or abc234; both mean the same code. */
5
5
  export declare function normalizeCode(code: string): string;
6
6
  export declare function pairingProof(code: string, label: "phone" | "computer", ...parts: string[]): string;
7
+ /**
8
+ * The short check a phone that typed the code shows to confirm: the first
9
+ * eight characters of the host key fingerprint, as "abcd efgh". A typed code
10
+ * alone could be guessed by someone on the network during pairing; matching
11
+ * this shows the phone reached this computer. Same as the app's `checkCode`.
12
+ */
13
+ export declare function pairingCheckCode(fingerprint: string | undefined | null): string | null;
7
14
  /** OpenSSH's SHA256 fingerprint of a public key line, as the phone computes it. */
8
15
  export declare function keyFingerprint(publicKeyLine: string): string | undefined;
9
16
  export declare function hostFingerprint(file?: string): Promise<string | undefined>;
@@ -32,6 +39,12 @@ export interface PairingSession {
32
39
  done: Promise<Paired>;
33
40
  close(): void;
34
41
  }
42
+ /** A phone that typed the code, waiting for the person at the computer to allow it. */
43
+ export interface PairingApproval {
44
+ device: "ios" | "android";
45
+ name?: string;
46
+ check: string | null;
47
+ }
35
48
  /** Listen for one phone. Resolves once its key is authorized; rejects on timeout or too many bad proofs. */
36
49
  export declare function startPairing(options: {
37
50
  code: string;
@@ -42,10 +55,19 @@ export declare function startPairing(options: {
42
55
  port?: number;
43
56
  timeoutMs?: number;
44
57
  sshDirectory?: string;
58
+ /**
59
+ * Asked before a phone that typed the code is authorized: a typed code can
60
+ * be cracked from a captured request, so the person at the computer allows
61
+ * the phone whose key check matches the one it shows. Without it, typed
62
+ * pairing is refused.
63
+ */
64
+ approve?: (phone: PairingApproval) => Promise<boolean>;
45
65
  }): Promise<PairingSession>;
46
66
  export declare const PAIR_USAGE = "phren pair [--minutes <1-30>] [--port <n>] [--no-install] | phren pair --scope gitboy-read|gitboy-write --key <public-key-file|-> [--no-install]";
47
67
  /** The authorized_keys line for a scoped key: no PTY, no forwarding, its own forced command. */
48
68
  export declare function scopedKeyLine(scope: GatewayScope, publicKey: string): string;
49
69
  /** Authorize a server's key for one scope. Options on the supplied line are discarded and rebuilt. */
50
70
  export declare function acceptScopedKey(scope: GatewayScope, input: string, sshDirectory?: string): Promise<string>;
71
+ /** A name safe to print in a terminal: control and format characters dropped, at most 80 characters. */
72
+ export declare function printableName(name: string): string;
51
73
  export declare function runPair(args: string[], version: string): Promise<number>;
@@ -37,6 +37,18 @@ function sameProof(expected, received) {
37
37
  const a = Buffer.from(expected), b = Buffer.from(received);
38
38
  return a.length === b.length && timingSafeEqual(a, b);
39
39
  }
40
+ /**
41
+ * The short check a phone that typed the code shows to confirm: the first
42
+ * eight characters of the host key fingerprint, as "abcd efgh". A typed code
43
+ * alone could be guessed by someone on the network during pairing; matching
44
+ * this shows the phone reached this computer. Same as the app's `checkCode`.
45
+ */
46
+ export function pairingCheckCode(fingerprint) {
47
+ if (!fingerprint?.startsWith("SHA256:"))
48
+ return null;
49
+ const body = fingerprint.slice("SHA256:".length);
50
+ return body.length >= 8 ? `${body.slice(0, 4)} ${body.slice(4, 8)}` : null;
51
+ }
40
52
  /** OpenSSH's SHA256 fingerprint of a public key line, as the phone computes it. */
41
53
  export function keyFingerprint(publicKeyLine) {
42
54
  const blob = publicKeyLine.trim().split(/\s+/)[1];
@@ -91,10 +103,12 @@ export function pairingURL(offer) {
91
103
  const request = z.object({
92
104
  v: z.literal(1), publicKey: z.string().max(512), proof: z.string().max(128),
93
105
  device: z.enum(["ios", "android"]).default("ios"), name: z.string().max(80).optional(),
106
+ typed: z.boolean().optional(),
94
107
  });
95
108
  /** Listen for one phone. Resolves once its key is authorized; rejects on timeout or too many bad proofs. */
96
109
  export async function startPairing(options) {
97
110
  let failures = 0, finished = false, timer;
111
+ let approvals = Promise.resolve();
98
112
  let resolve, reject;
99
113
  const done = new Promise((yes, no) => { resolve = yes; reject = no; });
100
114
  const server = createServer((incoming, response) => { void handle(incoming, response); });
@@ -135,6 +149,21 @@ export async function startPairing(options) {
135
149
  setImmediate(() => finish(new Error("Too many wrong pairing codes; pairing closed. Run phren pair again.")));
136
150
  throw new BridgeError(403, "That pairing code doesn't match this computer.");
137
151
  }
152
+ if (input.typed) {
153
+ // One question at a time, each bound to its own phone: a single answer
154
+ // never allows two keys.
155
+ const ask = approvals.then(() => finished || incoming.socket.destroyed ? false
156
+ : options.approve ? options.approve({ device: input.device, name: input.name, check: pairingCheckCode(keyFingerprint(publicKey)) }) : false);
157
+ approvals = ask.catch(() => false);
158
+ const allowed = await ask;
159
+ if (finished)
160
+ throw new BridgeError(410, "Pairing is closed. Run phren pair again.");
161
+ // A phone that gave up while the question waited gets nothing written.
162
+ if (incoming.socket.destroyed)
163
+ return;
164
+ if (!allowed)
165
+ throw new BridgeError(403, "The computer didn't allow this phone. Run phren pair again and allow it there.");
166
+ }
138
167
  const comment = input.device === "android" ? "phren-android" : "phren-iphone";
139
168
  const encoded = publicKey.split(" ")[1];
140
169
  await appendAuthorizedKey(`restrict,pty,${forcedCommand} ${publicKey} ${comment}`, existing => existing.split(/\s+/).includes(encoded), "This phone key is already authorized with different options.", options.sshDirectory);
@@ -248,6 +277,44 @@ async function runScopedPair(args, version) {
248
277
  console.log(` Revoke: remove the ${SCOPE_KEY_COMMENT[scope]} line from ${path.join(homedir(), ".ssh/authorized_keys")}.`);
249
278
  return 0;
250
279
  }
280
+ /** A name safe to print in a terminal: control and format characters dropped, at most 80 characters. */
281
+ export function printableName(name) {
282
+ return name.replace(/[\p{Cc}\p{Cf}\u2028\u2029]/gu, "").slice(0, 80);
283
+ }
284
+ /** How long the terminal waits for an answer: less than the phone waits, so a late yes never authorizes a phone that gave up. */
285
+ const APPROVAL_WAIT_MS = 100_000;
286
+ /**
287
+ * The terminal's say on a phone that typed the code; no terminal, no typed
288
+ * pairing. No answer in time is no, and Ctrl-C at the question cancels pairing.
289
+ */
290
+ async function askToAllow(phone, cancel) {
291
+ if (!process.stdin.isTTY) {
292
+ console.log("\n A phone typed the code, but there's no terminal here to allow it. Scan the QR code instead.");
293
+ return false;
294
+ }
295
+ const { createInterface } = await import("node:readline/promises");
296
+ const prompt = createInterface({ input: process.stdin, output: process.stdout });
297
+ const abort = new AbortController();
298
+ const timer = setTimeout(() => abort.abort(), APPROVAL_WAIT_MS);
299
+ prompt.on("SIGINT", () => { abort.abort(); cancel(); });
300
+ try {
301
+ // The name comes from the request: printed without control characters, so
302
+ // it can't hide or forge the check line with terminal escapes.
303
+ const name = phone.name ? printableName(phone.name) : "";
304
+ const who = name ? `"${name}"` : "A phone";
305
+ console.log(`\n ${who} typed the code. Its screen shows a key check${phone.check ? `; it should be: ${phone.check}` : "."}`);
306
+ const answer = await prompt.question(" Allow this phone? [y/N] ", { signal: abort.signal });
307
+ return /^y(es)?$/i.test(answer.trim());
308
+ }
309
+ catch {
310
+ console.log("\n Not allowed.");
311
+ return false;
312
+ }
313
+ finally {
314
+ clearTimeout(timer);
315
+ prompt.close();
316
+ }
317
+ }
251
318
  export async function runPair(args, version) {
252
319
  if (args.includes("--scope"))
253
320
  return runScopedPair(args, version);
@@ -286,7 +353,10 @@ export async function runPair(args, version) {
286
353
  console.error("No network address found. Connect to Wi-Fi or Tailscale and try again.");
287
354
  return 1;
288
355
  }
289
- const session = await startPairing({ code, user, sshPort, fingerprint, name, port, timeoutMs: minutes * 60_000 });
356
+ let cancelPairing = () => { };
357
+ const session = await startPairing({ code, user, sshPort, fingerprint, name, port, timeoutMs: minutes * 60_000,
358
+ approve: phone => askToAllow(phone, () => cancelPairing()) });
359
+ cancelPairing = () => session.close();
290
360
  const url = pairingURL({ hosts, port: session.port, user, sshPort, fingerprint, code, name });
291
361
  const { renderUnicodeCompact } = await import("uqr");
292
362
  console.log(`\nConnect your phone to ${name}`);
@@ -294,6 +364,9 @@ export async function runPair(args, version) {
294
364
  console.log(renderUnicodeCompact(url, { border: 2 }));
295
365
  const typed = `${code.slice(0, 3)}-${code.slice(3)}`;
296
366
  console.log(`\n Can't scan? Choose "Enter code" and type: ${hosts[0]}${session.port === PAIR_PORT ? "" : `:${session.port}`} ${typed}`);
367
+ const check = pairingCheckCode(fingerprint);
368
+ if (check)
369
+ console.log(` The phone then asks you to match: Check: ${check}`);
297
370
  if (process.env.WSL_DISTRO_NAME) {
298
371
  console.log(`\n This is WSL: Windows may block inbound port ${session.port} (and SSH) from the phone. If it cannot connect, run once in an admin PowerShell:`);
299
372
  console.log(` New-NetFirewallHyperVRule -Name phren-pair -DisplayName "Phren pairing" -Direction Inbound -VMCreatorId '{40E0AC32-46A5-438A-A0B2-2B479E8F2E90}' -Protocol TCP -LocalPorts ${session.port},22`);
@@ -1,4 +1,6 @@
1
1
  import { type Json, type Provider, type Target } from "./protocol.js";
2
+ /** A delivery the agent's turn ended without: the reason the phone shows. */
3
+ export declare const TURN_ENDED_WITHOUT_IT = "The agent finished its turn without taking the message.";
2
4
  export type DeliveryOutcome = "delivered" | "pending";
3
5
  /** What a phone message is known to have become. `queued`: typed into the
4
6
  * pane and held by the agent until its turn ends. `failed` carries a reason
@@ -114,6 +116,13 @@ export declare class PromptDeliveries {
114
116
  * callback for a row already claimed (the idle check settled it, the hook
115
117
  * came late) settles nothing more. */
116
118
  submitted(target: Target, prompt: string): Promise<void>;
119
+ /** Claude submits the messages it held while busy as one turn, joined by newlines, so no single message's
120
+ * hash matches the prompt. Each open message in the pane whose words are a run of whole lines of it settles,
121
+ * the longest run first at each line and the oldest of identical messages first, so "yes" never settles
122
+ * inside "yes, but later". Only hashes of the line runs are compared, never stored. Only messages still held
123
+ * (typed or queued) are matched: a failed one could take the lines of messages that are held, and a late
124
+ * take of a failed message stays its own hook's to report. */
125
+ private settleJoined;
117
126
  /** Marks `record` delivered, with the transcript entry that settled it when known. */
118
127
  private settle;
119
128
  /** Whether the transcript shows the agent took `record`'s message, claiming the entry it settled with.
@@ -4,6 +4,8 @@ import { open } from "node:fs/promises";
4
4
  import { z } from "zod";
5
5
  import { atomicInPrivateDir, object, objects, provider } from "./protocol.js";
6
6
  import { transcriptPath, unwrapPastedContent } from "./transcripts.js";
7
+ /** A delivery the agent's turn ended without: the reason the phone shows. */
8
+ export const TURN_ENDED_WITHOUT_IT = "The agent finished its turn without taking the message.";
7
9
  /** A message is kept this long, by its id, so a late status or a retry still
8
10
  * finds it: a busy Codex turn can run far past the old ten minutes. */
9
11
  export const DELIVERY_RETENTION_MS = 24 * 3_600_000;
@@ -31,6 +33,12 @@ export function promptKey(text) {
31
33
  }
32
34
  const PICTURE_PATH_LINE = /^\s*\/.*\.(?:png|jpe?g|gif|webp)\s*$/i;
33
35
  export const promptHash = (text) => createHash("sha256").update(promptKey(text)).digest("hex");
36
+ /** A submitted prompt is searched for held messages joined into it over at most this many of its lines. */
37
+ const JOINED_MAX_LINES = 64;
38
+ /** Of the open messages in a pane, at most this many are matched against a joined prompt's lines. */
39
+ const JOINED_MAX_OPEN = 32;
40
+ /** The line runs hashed for one joined prompt come to at most this many characters. */
41
+ const JOINED_MAX_CHARS = 1_048_576;
34
42
  const recordSchema = z.object({
35
43
  id: z.string().regex(/^[A-Za-z0-9_-]{8,64}$/).optional(), hash: z.string().regex(/^[0-9a-f]{64}$/),
36
44
  server: z.string().min(1).max(200), pane: z.string().min(1).max(200), source: provider, session: z.string().min(1).max(200),
@@ -40,6 +48,9 @@ const recordSchema = z.object({
40
48
  entry: z.number().optional(),
41
49
  /** Whether that entry is a user row (one its agent's UserPromptSubmit fired for), not a mid-turn queue removal. */
42
50
  entryHook: z.boolean().optional(),
51
+ /** From a joined prompt (`settleJoined`): "part", a message settled inside it, claims no row of its own (the turn's
52
+ * row carries other words); "turn", the joined words themselves, no message of anyone's, claims that row. */
53
+ joined: z.enum(["part", "turn"]).optional(),
43
54
  }).strict();
44
55
  /** One message per record, bound to the pane it was typed into (server, pane,
45
56
  * agent kind), not to the conversation: a Codex thread or a Claude /clear can
@@ -94,7 +105,7 @@ export class PromptDeliveries {
94
105
  if (!this.file)
95
106
  return;
96
107
  // A record without a phone id is kept once it claimed a transcript row, so after a restart that row is not offered to another message.
97
- const rows = this.records.filter(record => record.id || record.entry !== undefined).map(({ idleSince: _, checkedAt: __, hookClaim: ___, seenRow: ____, ...row }) => row);
108
+ const rows = this.records.filter(record => record.id || record.entry !== undefined || record.joined === "turn").map(({ idleSince: _, checkedAt: __, hookClaim: ___, seenRow: ____, ...row }) => row);
98
109
  const file = this.file;
99
110
  this.writing = this.writing.then(() => atomicInPrivateDir(file, { records: rows })).catch(() => undefined);
100
111
  }
@@ -254,8 +265,13 @@ export class PromptDeliveries {
254
265
  return open.find(entry => entry.session === target.session) ?? open[0];
255
266
  };
256
267
  let record = pick();
257
- if (!record)
268
+ if (!record) {
269
+ // A prompt that is one known message's own words (a late hook for a message already settled) is not a join.
270
+ // Records from an earlier join never get a hook of their own, so they do not count.
271
+ if (!this.records.some(other => other.hash === hash && this.samePane(other, target) && other.joined === undefined) && this.settleJoined(target, prompt))
272
+ this.save();
258
273
  return;
274
+ }
259
275
  let entry;
260
276
  if (target.source === "claude") {
261
277
  // A hook settles a message only by claiming a row for it: rows all claimed by earlier messages is a
@@ -298,6 +314,52 @@ export class PromptDeliveries {
298
314
  this.settle(record, entry, target.session, entry !== undefined ? true : undefined);
299
315
  this.save();
300
316
  }
317
+ /** Claude submits the messages it held while busy as one turn, joined by newlines, so no single message's
318
+ * hash matches the prompt. Each open message in the pane whose words are a run of whole lines of it settles,
319
+ * the longest run first at each line and the oldest of identical messages first, so "yes" never settles
320
+ * inside "yes, but later". Only hashes of the line runs are compared, never stored. Only messages still held
321
+ * (typed or queued) are matched: a failed one could take the lines of messages that are held, and a late
322
+ * take of a failed message stays its own hook's to report. */
323
+ settleJoined(target, prompt) {
324
+ const candidates = this.records.filter(record => this.samePane(record, target) && PromptDeliveries.open(record))
325
+ .sort((a, b) => a.at - b.at).slice(0, JOINED_MAX_OPEN);
326
+ if (!candidates.length)
327
+ return false;
328
+ const lines = unwrapPastedContent(prompt).split("\n").filter(line => !PICTURE_PATH_LINE.test(line));
329
+ if (lines.length < 2 || lines.length > JOINED_MAX_LINES)
330
+ return false;
331
+ const matched = [];
332
+ let budget = JOINED_MAX_CHARS;
333
+ for (let start = 0; start < lines.length;) {
334
+ let next = start + 1;
335
+ for (let end = lines.length; end > start; end--) {
336
+ const run = lines.slice(start, end).join("\n");
337
+ if ((budget -= run.length) < 0)
338
+ break;
339
+ if (!promptKey(run))
340
+ continue;
341
+ const hash = promptHash(run), same = candidates.filter(record => record.hash === hash && !matched.includes(record));
342
+ const record = same.find(entry => entry.session === target.session) ?? same[0];
343
+ if (record) {
344
+ matched.push(record);
345
+ next = end;
346
+ break;
347
+ }
348
+ }
349
+ start = next;
350
+ }
351
+ if (!matched.length)
352
+ return false;
353
+ for (const record of matched) {
354
+ record.joined = "part";
355
+ this.settle(record, undefined, target.session);
356
+ }
357
+ // The turn's row carries the joined words: a hook-settled record of them (no phone id) claims it as
358
+ // `taken` lets any hook-settled message, so a later message with the same words cannot take it.
359
+ this.records.push({ hash: promptHash(prompt), server: target.server, pane: target.pane, source: target.source, session: target.session,
360
+ state: "delivered", at: this.now(), settledAt: this.now(), joined: "turn" });
361
+ return true;
362
+ }
301
363
  /** Marks `record` delivered, with the transcript entry that settled it when known. */
302
364
  settle(record, entry, session, hook) {
303
365
  record.state = "delivered";
@@ -334,7 +396,8 @@ export class PromptDeliveries {
334
396
  // A message the agent's hook settled before its row was written took that row without recording it: the
335
397
  // scan reaches back to it, and it claims (and keeps) the earliest unclaimed user row stamped after it was
336
398
  // typed and soon after its hook, oldest first, before any open message is offered a row.
337
- const hooked = this.records.filter(other => same(other) && other.state === "delivered" && other.entry === undefined)
399
+ // One settled inside a joined prompt took that prompt's row, which carries other words: it has none to claim.
400
+ const hooked = this.records.filter(other => same(other) && other.state === "delivered" && other.entry === undefined && other.joined !== "part")
338
401
  .sort((a, b) => (a.settledAt ?? a.at) - (b.settledAt ?? b.at));
339
402
  const from = Math.min(record.at, ...hooked.map(other => other.at));
340
403
  const found = (await this.landed({ ...record, at: from }).catch(() => [])).sort((a, b) => a.offset - b.offset);
@@ -460,7 +523,7 @@ export class PromptDeliveries {
460
523
  record.state = "failed";
461
524
  record.settledAt = now;
462
525
  changed = true;
463
- record.reason = "The agent finished its turn without taking the message.";
526
+ record.reason = TURN_ENDED_WITHOUT_IT;
464
527
  }
465
528
  if (changed)
466
529
  this.save();
@@ -61,6 +61,10 @@ export interface LaunchOptions {
61
61
  /** The `PHREN_DISPATCH_ID` the agent gets when it is not the brief's own id:
62
62
  * a moved worker keeps the dispatch it was launched for. */
63
63
  dispatchId?: string;
64
+ /** Resume this Claude conversation (`claude --resume`) instead of starting a
65
+ * new one: a conversation switched to another account (session-move.ts).
66
+ * An option, not request data, so only the Hook itself resumes a session. */
67
+ resumeClaude?: string;
64
68
  }
65
69
  /**
66
70
  * "Open on a computer": a new Herdr workspace (or a tab in an existing one)
@@ -401,6 +401,9 @@ async function startSession(server, data, options) {
401
401
  if (role === "conductor" && data.mode === "chat")
402
402
  throw new BridgeError(400, "A conductor needs agent mode with tools.");
403
403
  const phrenArgs = await phrenLaunchArgs(kind, data);
404
+ const resumeClaude = options.resumeClaude === undefined ? undefined : z.string().uuid("resumeClaude must be a Claude session id.").parse(options.resumeClaude);
405
+ if (resumeClaude && (kind !== "claude" || role !== "agent" || data.brief != null))
406
+ throw new BridgeError(400, "Only a Claude worker without a brief resumes a conversation.");
404
407
  // A dispatched worker's or scheduled run's first prompt. It rides on the
405
408
  // launch where the harness takes one; elsewhere the caller types it.
406
409
  const brief = data.brief === undefined || data.brief === null ? undefined : launchBriefSchema.parse(data.brief);
@@ -445,7 +448,7 @@ async function startSession(server, data, options) {
445
448
  workspace = undefined;
446
449
  const args = role === "conductor" ? [...await prepareConductor(kind, effort, model), ...(kind === "phren" ? phrenArgs : [])]
447
450
  : [...(kind === "phren" ? [...PHREN_AGENT_ARGS, ...phrenArgs] : []), ...(model && kind === "phren" ? phrenModelArgs(model) : model && modelFlag[kind] ? [modelFlag[kind], model] : []), ...(data.effort === undefined ? [] : effortArgs(kind, effort)),
448
- ...(permissionMode && kind === "claude" ? ["--permission-mode", CLAUDE_NAMES[permissionMode]] : []), ...(permissionMode && kind === "codex" ? codexModeFlags(permissionMode) : []), ...(permissionMode && kind === "copilot" ? copilotModeFlags(permissionMode) : [])];
451
+ ...(permissionMode && kind === "claude" ? ["--permission-mode", CLAUDE_NAMES[permissionMode]] : []), ...(resumeClaude ? ["--resume", resumeClaude] : []), ...(permissionMode && kind === "codex" ? codexModeFlags(permissionMode) : []), ...(permissionMode && kind === "copilot" ? copilotModeFlags(permissionMode) : [])];
449
452
  // A Codex worker runs on a Phren-owned app-server (codex-servers.ts): the
450
453
  // pane joins the thread the Hook started, and the brief is that thread's
451
454
  // first turn. The typed arguments below stay the fallback.
@@ -36,6 +36,18 @@ export declare function herdrWorktreeWorkers(s: Json): WorktreeWorker[];
36
36
  /** What `takesPrompt` checks before typing into a Claude pane Herdr reads working: nothing structured
37
37
  * pending there and no dialog on its screen. */
38
38
  export declare function promptGuards(agentHooks: Pick<AgentHooks, "approval" | "terminalPrompt" | "servedQuestion">, target: Target): PromptGuards;
39
+ /** A Claude pane showing a subagent's view (its empty input reads "Message
40
+ * @<agent>…") takes typed text for that subagent, so a phone message never
41
+ * reached the turn and failed when it ended (owner, 2026-10-21). Escape returns
42
+ * to the main view. It is pressed once, only while that view shows: in the main
43
+ * view Escape would interrupt the turn, so a view still showing after it is left
44
+ * as it is and logged. True when the view was left. */
45
+ export declare function leaveClaudeSubagentView(agentHooks: Pick<AgentHooks, "paneAnsi">, target: Target, waitMs?: number): Promise<boolean>;
46
+ /** A phone message the turn ended without, in a Claude pane that now shows a
47
+ * subagent's view (opened while the message waited): leave the view and type
48
+ * it again under the same delivery id, once. Any other outcome, a changed
49
+ * pane, or ten minutes end the watch. */
50
+ export declare function retryAfterSubagentView(agentHooks: AgentHooks, target: Target, terminal: unknown, text: string, id: string, intervalMs?: number, limitMs?: number, escapeWaitMs?: number): void;
39
51
  /** A busy Claude Code queues typed text on Enter, but after a long paste
40
52
  * ("paste again to expand") it can swallow that Enter and leave the text in
41
53
  * its input line, where it stays after the turn ends. Follow the pane: once