@phren/cli 0.3.55 → 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.
Files changed (36) hide show
  1. package/dist/bridge/agent-hook-callback.js +1 -0
  2. package/dist/bridge/agent-hooks.js +1 -0
  3. package/dist/bridge/claude-suggestion.d.ts +9 -0
  4. package/dist/bridge/claude-suggestion.js +30 -4
  5. package/dist/bridge/dispatch-command.js +3 -3
  6. package/dist/bridge/dispatch-returns.d.ts +4 -0
  7. package/dist/bridge/dispatch-returns.js +10 -3
  8. package/dist/bridge/hand-off-queue.d.ts +21 -0
  9. package/dist/bridge/hand-off-queue.js +31 -2
  10. package/dist/bridge/hand-off.d.ts +1 -0
  11. package/dist/bridge/hand-off.js +5 -1
  12. package/dist/bridge/pair.d.ts +22 -0
  13. package/dist/bridge/pair.js +74 -1
  14. package/dist/bridge/prompt-deliveries.d.ts +21 -0
  15. package/dist/bridge/prompt-deliveries.js +140 -24
  16. package/dist/bridge/server-launch.d.ts +4 -0
  17. package/dist/bridge/server-launch.js +4 -1
  18. package/dist/bridge/server-pane-routes.d.ts +16 -0
  19. package/dist/bridge/server-pane-routes.js +132 -4
  20. package/dist/bridge/server-routes.d.ts +1 -0
  21. package/dist/bridge/server-routes.js +1 -1
  22. package/dist/bridge/server.js +9 -2
  23. package/dist/bridge/session-activity.d.ts +28 -0
  24. package/dist/bridge/session-activity.js +30 -0
  25. package/dist/bridge/session-move.d.ts +25 -0
  26. package/dist/bridge/session-move.js +128 -9
  27. package/dist/bridge/speech-transcribe.js +28 -3
  28. package/dist/bridge/terminal-herdr.js +28 -8
  29. package/dist/bridge/turn-records.d.ts +2 -0
  30. package/dist/bridge/turn-records.js +6 -1
  31. package/dist/bridge-hook.mjs +1900 -1524
  32. package/dist/cli-registry.js +2 -2
  33. package/dist/modules/registry.js +1 -1
  34. package/dist/tools/dispatch.js +3 -2
  35. package/package.json +1 -1
  36. package/starter/global/skills/conductor/SKILL.md +7 -0
@@ -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;
@@ -15,6 +17,11 @@ const MAX_RECORDS = 512;
15
17
  const LANDED_CHECK_MS = 3_000;
16
18
  /** The transcript scan starts this long before a message was typed (clock skew), so entries up to this far back may belong to an earlier message. */
17
19
  const ENTRY_SLACK_MS = 5_000;
20
+ /** Claude writes a submitted row after its hooks return; a message its hook settled claims only a row stamped within this long of that. */
21
+ const HOOK_ROW_MS = 30_000;
22
+ /** Typed text holds its pane (nothing more is typed there) at most this long when the pane sends no
23
+ * UserPromptSubmit or Stop to settle it: a message such an agent took or dropped never settles. */
24
+ export const IN_FLIGHT_MS = 45_000;
18
25
  /** What the agent hands its UserPromptSubmit hook is the terminal's pasted
19
26
  * form of what Phren typed; compare the words, not the wrapping. Claude Code
20
27
  * also takes each attached picture's path line out of the text and puts an
@@ -26,6 +33,12 @@ export function promptKey(text) {
26
33
  }
27
34
  const PICTURE_PATH_LINE = /^\s*\/.*\.(?:png|jpe?g|gif|webp)\s*$/i;
28
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;
29
42
  const recordSchema = z.object({
30
43
  id: z.string().regex(/^[A-Za-z0-9_-]{8,64}$/).optional(), hash: z.string().regex(/^[0-9a-f]{64}$/),
31
44
  server: z.string().min(1).max(200), pane: z.string().min(1).max(200), source: provider, session: z.string().min(1).max(200),
@@ -33,6 +46,11 @@ const recordSchema = z.object({
33
46
  reason: z.string().max(500).optional(), at: z.number(), settledAt: z.number().optional(), stoppedAt: z.number().optional(),
34
47
  /** The transcript entry (byte offset) that settled it, so no other message claims the same one. */
35
48
  entry: z.number().optional(),
49
+ /** Whether that entry is a user row (one its agent's UserPromptSubmit fired for), not a mid-turn queue removal. */
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(),
36
54
  }).strict();
37
55
  /** One message per record, bound to the pane it was typed into (server, pane,
38
56
  * agent kind), not to the conversation: a Codex thread or a Claude /clear can
@@ -49,6 +67,8 @@ export class PromptDeliveries {
49
67
  writing = Promise.resolve();
50
68
  /** Panes (server, pane, agent) that sent a UserPromptSubmit or Stop since the Hook started. */
51
69
  hookPanes = new Set();
70
+ /** When each pane (server, pane, agent) last sent a Stop since the Hook started. */
71
+ lastStop = new Map();
52
72
  paneKey(target) { return [target.server, target.pane, target.source].join("|"); }
53
73
  static open(record) { return record.state === "typed" || record.state === "queued"; }
54
74
  /** Open, or failed with its own hook's claim still waiting for its row (a late delivery). */
@@ -85,7 +105,7 @@ export class PromptDeliveries {
85
105
  if (!this.file)
86
106
  return;
87
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.
88
- 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);
89
109
  const file = this.file;
90
110
  this.writing = this.writing.then(() => atomicInPrivateDir(file, { records: rows })).catch(() => undefined);
91
111
  }
@@ -137,6 +157,14 @@ export class PromptDeliveries {
137
157
  }
138
158
  /** A message Phren typed into `target`'s pane that no conversation there has submitted yet. */
139
159
  pending(target, text) { return !!this.open(target, text); }
160
+ /** Whether `record` still holds its pane: open, and either young or in a pane whose hooks will settle it. */
161
+ inFlight(record) {
162
+ return PromptDeliveries.open(record) && (this.now() - record.at < IN_FLIGHT_MS || this.hookPanes.has(this.paneKey(record)));
163
+ }
164
+ /** Whether any message typed into `target`'s pane is still waiting to be taken or refused. */
165
+ holding(target) { return this.records.some(record => this.samePane(record, target) && this.inFlight(record)); }
166
+ /** Whether phone message `id` may still be taken: held by the agent, and in flight as `holding` counts it. */
167
+ held(id, target) { const record = this.find(id, target); return !!record && this.inFlight(record); }
140
168
  /** Wait again for a message `expect` reported pending, after a second Enter. */
141
169
  awaitLate(target, text, waitMs = 2_500) {
142
170
  const record = this.open(target, text);
@@ -228,13 +256,22 @@ export class PromptDeliveries {
228
256
  async submitted(target, prompt) {
229
257
  const hash = promptHash(prompt);
230
258
  this.hookPanes.add(this.paneKey(target));
259
+ // A failed message stays matchable for a late take only until the pane's next Stop: a turn that ended
260
+ // without it means a later identical prompt is a new one.
261
+ const stop = this.lastStop.get(this.paneKey(target)) ?? -Infinity;
231
262
  const pick = () => {
232
- const open = this.records.filter(record => record.hash === hash && this.samePane(record, target) && record.state !== "delivered");
263
+ const open = this.records.filter(record => record.hash === hash && this.samePane(record, target) && record.state !== "delivered"
264
+ && (record.state !== "failed" || (record.settledAt ?? record.at) >= stop));
233
265
  return open.find(entry => entry.session === target.session) ?? open[0];
234
266
  };
235
267
  let record = pick();
236
- 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();
237
273
  return;
274
+ }
238
275
  let entry;
239
276
  if (target.source === "claude") {
240
277
  // A hook settles a message only by claiming a row for it: rows all claimed by earlier messages is a
@@ -251,30 +288,80 @@ export class PromptDeliveries {
251
288
  if (!record)
252
289
  return;
253
290
  // Claims are per conversation: another conversation's rows can sit at the same byte offset.
254
- const claimed = new Set(this.records.filter(other => other.hash === hash && this.samePane(other, target) && other.session === target.session && other.entry !== undefined).map(other => other.entry));
255
- // A transcript that cannot be read settles on the hook's word, unless a message with these words already
256
- // claimed a row in this conversation: the callback may be that message's, late, so it waits for a row.
257
- if (!rows && !claimed.size) {
291
+ // Only user rows count: a mid-turn queue removal never had a hook, so it says nothing about this callback.
292
+ const claimed = new Set(this.records.filter(other => other.hash === hash && this.samePane(other, target) && other.session === target.session && other.entry !== undefined && other.entryHook !== false).map(other => other.entry));
293
+ const free = rows?.filter(row => !claimed.has(row.offset)).sort((a, b) => a.offset - b.offset)[0];
294
+ // Claude writes the submitted row only after its UserPromptSubmit hooks return, and this callback is one
295
+ // of them: the row for this submission is never readable yet. So no free row (or a transcript that cannot
296
+ // be read) settles on the hook's word at once, as the agent took it and started its turn. The row it
297
+ // writes next stays this message's (`taken` counts hook-settled messages first). Only when a message
298
+ // with these words already claimed a row in this conversation may the callback be that message's, late:
299
+ // then it waits for a row of its own, looked for in the conversation that made the claim.
300
+ if (!free && !claimed.size) {
258
301
  this.settle(record, undefined, target.session);
259
302
  this.save();
260
303
  return;
261
304
  }
262
- // The claim is looked for in the conversation that made it (it may have replaced the one the message was typed for).
263
- if (!rows?.length) {
264
- record.hookClaim = true;
265
- record.session = target.session;
305
+ if (!free) {
306
+ if (!rows?.length) {
307
+ record.hookClaim = true;
308
+ record.session = target.session;
309
+ }
266
310
  return;
267
311
  }
268
- const free = rows.filter(row => !claimed.has(row.offset)).sort((a, b) => a.offset - b.offset)[0];
269
- if (!free)
270
- return;
271
312
  entry = free.offset;
272
313
  }
273
- this.settle(record, entry, target.session);
314
+ this.settle(record, entry, target.session, entry !== undefined ? true : undefined);
274
315
  this.save();
275
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
+ }
276
363
  /** Marks `record` delivered, with the transcript entry that settled it when known. */
277
- settle(record, entry, session) {
364
+ settle(record, entry, session, hook) {
278
365
  record.state = "delivered";
279
366
  record.settledAt = this.now();
280
367
  delete record.reason;
@@ -284,6 +371,8 @@ export class PromptDeliveries {
284
371
  record.session = session;
285
372
  if (entry !== undefined)
286
373
  record.entry = entry;
374
+ if (hook !== undefined)
375
+ record.entryHook = hook;
287
376
  this.release(record, "delivered");
288
377
  }
289
378
  /** Whether the transcript shows the agent took `record`'s message, claiming the entry it settled with.
@@ -304,12 +393,31 @@ export class PromptDeliveries {
304
393
  const key = [record.hash, record.server, record.pane, record.session, working].join("|");
305
394
  let free = pass.get(key);
306
395
  if (!free) {
307
- const found = (await this.landed(record).catch(() => [])).sort((a, b) => a.offset - b.offset);
396
+ // A message the agent's hook settled before its row was written took that row without recording it: the
397
+ // scan reaches back to it, and it claims (and keeps) the earliest unclaimed user row stamped after it was
398
+ // typed and soon after its hook, oldest first, before any open message is offered a row.
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")
401
+ .sort((a, b) => (a.settledAt ?? a.at) - (b.settledAt ?? b.at));
402
+ const from = Math.min(record.at, ...hooked.map(other => other.at));
403
+ const found = (await this.landed({ ...record, at: from }).catch(() => [])).sort((a, b) => a.offset - b.offset);
308
404
  const used = new Set(this.records.filter(other => same(other) && other.entry !== undefined).map(other => other.entry));
309
- // A message the agent's hook settled took a user row without recording it (a transcript it could not read):
310
- // the oldest user rows are theirs, whether the agent works or not.
311
- let hooked = this.records.filter(other => same(other) && other.state === "delivered" && other.entry === undefined && (other.settledAt ?? 0) >= record.at - ENTRY_SLACK_MS).length;
312
- const unclaimed = found.filter(entry => !used.has(entry.offset)).filter(entry => !(entry.hook && hooked-- > 0));
405
+ let claimedRows = false;
406
+ for (const other of hooked) {
407
+ if (other.entry !== undefined)
408
+ continue;
409
+ const row = found.find(entry => entry.hook && !used.has(entry.offset)
410
+ && (entry.at === undefined || (entry.at >= other.at - ENTRY_SLACK_MS && entry.at <= (other.settledAt ?? other.at) + HOOK_ROW_MS)));
411
+ if (!row)
412
+ continue;
413
+ other.entry = row.offset;
414
+ other.entryHook = true;
415
+ used.add(row.offset);
416
+ claimedRows = true;
417
+ }
418
+ if (claimedRows)
419
+ this.save();
420
+ const unclaimed = found.filter(entry => !used.has(entry.offset) && (entry.at === undefined || entry.at >= record.at - ENTRY_SLACK_MS));
313
421
  if (working) {
314
422
  // A user row is its hook's to settle, unless that hook already came (before the row could be read), or
315
423
  // the pane sends no callbacks at all: then a row two checks in a row saw unclaimed settles it.
@@ -331,12 +439,14 @@ export class PromptDeliveries {
331
439
  if (entry === undefined)
332
440
  return false;
333
441
  record.entry = entry.offset;
442
+ record.entryHook = entry.hook;
334
443
  return true;
335
444
  }
336
445
  /** A turn in `target`'s pane ended: the agent now takes held input or never will. */
337
446
  stopped(target) {
338
447
  const at = this.now();
339
448
  this.hookPanes.add(this.paneKey(target));
449
+ this.lastStop.set(this.paneKey(target), at);
340
450
  let marked = false;
341
451
  for (const record of this.records)
342
452
  if (this.samePane(record, target) && (record.state === "typed" || record.state === "queued") && record.at < at) {
@@ -413,7 +523,7 @@ export class PromptDeliveries {
413
523
  record.state = "failed";
414
524
  record.settledAt = now;
415
525
  changed = true;
416
- record.reason = "The agent finished its turn without taking the message.";
526
+ record.reason = TURN_ENDED_WITHOUT_IT;
417
527
  }
418
528
  if (changed)
419
529
  this.save();
@@ -431,6 +541,9 @@ export function matchingOffsets(buffer, start, record) {
431
541
  for (let index = lines.length - 1; index >= 0; index--) {
432
542
  const line = lines[index];
433
543
  offset -= Buffer.byteLength(line) + (index < lines.length - 1 ? 1 : 0);
544
+ // Only a row that can carry user text is parsed: the scan reads the whole tail now, not just its newest rows.
545
+ if (!line.includes('"user') && !line.includes("queue-operation"))
546
+ continue;
434
547
  let row;
435
548
  try {
436
549
  row = object(JSON.parse(line));
@@ -438,12 +551,15 @@ export function matchingOffsets(buffer, start, record) {
438
551
  catch {
439
552
  continue;
440
553
  }
554
+ // Rows are not in time order: Claude writes a queued message's attachment rows, stamped when it was
555
+ // typed, after the queue removal that took it. An older row is skipped, never the end of the scan,
556
+ // or a message typed after an earlier queued one is never found (seen 2026-10-17: taken, reported failed).
441
557
  const stamp = Date.parse(String(row.timestamp ?? ""));
442
558
  if (Number.isFinite(stamp) && stamp < record.at - 5_000)
443
- break;
559
+ continue;
444
560
  // One entry per row, even when its content repeats the words.
445
561
  if (userTexts(row).some(text => promptHash(text) === record.hash))
446
- entries.push({ offset, hook: row.type === "user" });
562
+ entries.push({ offset, hook: row.type === "user", ...(Number.isFinite(stamp) ? { at: stamp } : {}) });
447
563
  }
448
564
  return entries;
449
565
  }
@@ -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.
@@ -5,6 +5,7 @@ import { type WorktreeWorker } from "./git-worktrees.js";
5
5
  import { type ModelSwitcher } from "./model-switch.js";
6
6
  import { type PermissionModeSwitcher } from "./permission-mode.js";
7
7
  import type { SettingsSwitcher } from "./settings-switch.js";
8
+ import { type PromptGuards } from "./session-activity.js";
8
9
  import { type Json, type Target } from "./protocol.js";
9
10
  import type { CodexQuestions } from "./questions.js";
10
11
  import { type SideQuestions } from "./side-questions.js";
@@ -32,6 +33,21 @@ export declare function gitRepository(pane: Json, target: Target, child: unknown
32
33
  * an agent launched into a new worktree from the phone is named here. Listed
33
34
  * last, so a sub-agent or fan-out manifest for the same folder wins a tie. */
34
35
  export declare function herdrWorktreeWorkers(s: Json): WorktreeWorker[];
36
+ /** What `takesPrompt` checks before typing into a Claude pane Herdr reads working: nothing structured
37
+ * pending there and no dialog on its screen. */
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;
35
51
  /** A busy Claude Code queues typed text on Enter, but after a long paste
36
52
  * ("paste again to expand") it can swallow that Enter and leave the text in
37
53
  * its input line, where it stays after the turn ends. Follow the pane: once
@@ -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";
@@ -15,6 +17,7 @@ import { CodexServerUnavailable, codexServers } from "./codex-servers.js";
15
17
  import { refuseWorkingSlash } from "./model-switch.js";
16
18
  import { PERMISSION_MODE_VALUES, refuseAgentOrigin } from "./permission-mode.js";
17
19
  import { sessionWebServers } from "./session-servers.js";
20
+ import { takesPrompt } from "./session-activity.js";
18
21
  import { gitRoot, repositoryDiff, withGitReadDeadline } from "./projects.js";
19
22
  import { BridgeError, MAX_FRAME, object, objects, startingTargetSchema, targetSchema } from "./protocol.js";
20
23
  import { childAgent, childAgentTree, conversationNamedPaths, targetTranscriptPath } from "./transcripts.js";
@@ -25,6 +28,7 @@ import { fileSearchSchema, listRepositoryFiles, searchRepository } from "./file-
25
28
  import { deliveryIdSchema, PromptOnce, promptScope } from "./prompt-once.js";
26
29
  import { promptWithStartupRetry } from "./prompt-startup.js";
27
30
  import { sendServedPrompt, servedPane } from "./opencode-panes.js";
31
+ import { claudeSuggestionShown } from "./claude-suggestion.js";
28
32
  export /** A file from the phone: a plain name and base64 bytes, bounded. */ function uploadBody(data) {
29
33
  const name = z.string().regex(/^[A-Za-z0-9_][A-Za-z0-9_ .()-]{0,199}$/).refine(n => !n.includes("..")).parse(data.name);
30
34
  const encoded = z.string().max(11_184_812).regex(/^[A-Za-z0-9+/]*={0,2}$/).parse(data.data);
@@ -119,6 +123,35 @@ function claudeQuestionAnswer(data) {
119
123
  }
120
124
  /** A secret typed into a terminal prompt: printable, bounded, never logged. */
121
125
  const secretText = z.string().min(1).max(256).refine(t => !/[\x00-\x1f\x7f]/.test(t));
126
+ /** What `takesPrompt` checks before typing into a Claude pane Herdr reads working: nothing structured
127
+ * pending there and no dialog on its screen. */
128
+ export function promptGuards(agentHooks, target) {
129
+ return { held: () => !!(agentHooks.approval(target) || agentHooks.terminalPrompt(target) || agentHooks.servedQuestion(target)),
130
+ screen: () => terminalProvider().readScreen(target.server, target.pane, { scope: "pane", source: "visible", lines: 40, format: "ansi", timeoutMs: 2_000 }) };
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
+ }
153
+ /** Herdr answered the request with a refusal (a 409 carrying its own error code): it performed nothing. */
154
+ const herdrRefused = (error) => error instanceof BridgeError && error.status === 409 && typeof error.details?.herdrCode === "string";
122
155
  /** An idle agent that has not taken typed text within the first wait
123
156
  * likely lost the Enter while it redrew (an update notice, a resize): the
124
157
  * text sits in its input line. Press Enter once more and wait again. A
@@ -131,8 +164,10 @@ async function resubmitIfIdle(agentHooks, target, text) {
131
164
  catch {
132
165
  return "unknown";
133
166
  } };
167
+ // A pane that turned working started a turn: its UserPromptSubmit is on its way (the agent runs its
168
+ // other hooks too). Wait for it rather than answering "queued" for a message the agent took.
134
169
  if (await status() === "working")
135
- return "pending";
170
+ return await agentHooks.deliveries.awaitLate(target, text);
136
171
  const late = agentHooks.deliveries.awaitLate(target, text);
137
172
  await terminalProvider().sendKeys(target.server, target.pane, ["enter"]);
138
173
  const outcome = await late;
@@ -140,6 +175,88 @@ async function resubmitIfIdle(agentHooks, target, text) {
140
175
  return outcome;
141
176
  return await status() === "working" ? "pending" : "unsubmitted";
142
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
+ }
143
260
  /** A busy Claude Code queues typed text on Enter, but after a long paste
144
261
  * ("paste again to expand") it can swallow that Enter and leave the text in
145
262
  * its input line, where it stays after the turn ends. Follow the pane: once
@@ -388,8 +505,12 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
388
505
  // is pending there: an approval the Hook holds or saw, or a
389
506
  // status Herdr cannot read. Otherwise the answer keys are the way.
390
507
  const status = String(pane.agent_status);
391
- if (data.hookQueued === true && !["idle", "done"].includes(status))
508
+ // A Claude lead waiting on its background agents takes a prompt though Herdr reads it working (`takesPrompt`).
509
+ if (data.hookQueued === true && !await takesPrompt(target.server, pane, target.session, promptGuards(agentHooks, target)))
392
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
+ }
393
514
  if (status === "unknown" || (["blocked", "waiting"].includes(status) && (agentHooks.approval(target) || agentHooks.terminalPrompt(target) || agentHooks.servedQuestion(target)))) {
394
515
  throw new BridgeError(409, "This agent needs input in the terminal first.");
395
516
  }
@@ -462,12 +583,17 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
462
583
  let outcome = await promptWithStartupRetry(async () => {
463
584
  const refused = new AbortController();
464
585
  const expected = agentHooks.deliveries.expect(target, text, busy && target.source !== "claude" ? 300 : 1_500, refused.signal, deliveryId, typeof pane.terminal_id === "string" ? pane.terminal_id : undefined);
465
- await typing();
586
+ let typed = false;
466
587
  try {
588
+ await typing();
589
+ typed = true;
590
+ await leaveClaudeSubagentView(agentHooks, target);
467
591
  await terminalProvider().prompt(target.server, target.pane, text);
468
592
  }
469
593
  catch (error) {
470
- if (agentNotReady(error))
594
+ // Nothing reached the pane: the reservation failed first, the agent was not ready, or Herdr refused the
595
+ // request (its `agent.prompt` is one call). The record goes, or it would hold the pane's hand-offs.
596
+ if (!typed || agentNotReady(error) || herdrRefused(error))
471
597
  refused.abort();
472
598
  throw error;
473
599
  }
@@ -492,6 +618,8 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
492
618
  else
493
619
  followQueuedDelivery(agentHooks, target, pane.terminal_id, text);
494
620
  }
621
+ if (deliveryId && target.source === "claude" && outcome !== "delivered")
622
+ retryAfterSubagentView(agentHooks, target, pane.terminal_id, text, deliveryId);
495
623
  // A bare slash command opens the agent's own menu; the phone may
496
624
  // walk it with keys for the next half minute. The command rides
497
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)));
@@ -12,7 +12,7 @@ import { hookPeers, peerRequest } from "./peers.js";
12
12
  import { handOff } from "./hand-off.js";
13
13
  import { sessionStalls } from "./stalls.js";
14
14
  import { HandOffQueue } from "./hand-off-queue.js";
15
- import { paneRouteOnce } from "./server-pane-routes.js";
15
+ import { paneRouteOnce, promptGuards } from "./server-pane-routes.js";
16
16
  import { FanoutMessages } from "./fanout-messages.js";
17
17
  import { activateModules as moduleSnapshot } from "../modules/runtime.js";
18
18
  import { disabledHint } from "../modules/registry.js";
@@ -56,10 +56,11 @@ 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";
63
+ import { takesPrompt } from "./session-activity.js";
63
64
  import { readLaunchBrief } from "./launch-brief.js";
64
65
  import { conductorPane, readRoleState } from "./conductor-role.js";
65
66
  import { terminalKind, terminalProvider } from "./terminal.js";
@@ -108,6 +109,7 @@ export async function serve(version, options = {}) {
108
109
  // Follows what dispatched workers do and tells the dispatching agent.
109
110
  let succession;
110
111
  const returns = dispatches ? new DispatchReturns({
112
+ takesPrompt: (target, pane) => takesPrompt(target.server, pane, target.session, promptGuards(agentHooks, target)),
111
113
  localComputer: { id: computerID, name: hostname() },
112
114
  forward: (origin, text, deliveryId) => succession?.forward(origin, text, deliveryId) ?? Promise.resolve(undefined),
113
115
  // Continue on another signed-in account when a Claude worker stops at its usage limit: opt-in, `phren config account-failover on`.
@@ -155,6 +157,10 @@ export async function serve(version, options = {}) {
155
157
  },
156
158
  notify: (target, text, deliveryId, computer) => handOff({ computer, target, text, deliveryId }, { notifySender: false, bypassConductor: true }),
157
159
  send: sendPrompt,
160
+ delivery: (target, deliveryId) => agentHooks.deliveries.status(deliveryId, target),
161
+ inFlight: target => agentHooks.deliveries.holding(target),
162
+ held: (target, deliveryId) => agentHooks.deliveries.held(deliveryId, target),
163
+ ready: (target, pane) => takesPrompt(target.server, pane, target.session, promptGuards(agentHooks, target)),
158
164
  }) : undefined;
159
165
  // Moving a session to another agent (session-move.ts): its hand-off request
160
166
  // takes the hand_off path, and the new agent starts through the launch path.
@@ -172,6 +178,7 @@ export async function serve(version, options = {}) {
172
178
  launch: (server, data, options) => launches.run(() => launchSession(server, data, { trustFolder: true, ...options })),
173
179
  inventory: () => launchCheckOff() ? Promise.resolve(undefined) : harnessInventoryWithin(2_500),
174
180
  transcript: async (target) => transcriptTail(await targetTranscriptPath(target)),
181
+ copyConversation: async (target, home, check) => copyClaudeConversation(await targetTranscriptPath(target), home, process.env, check),
175
182
  paneAccount: (server, pane) => paneAccount(paneAccountKey(server, pane.pane_id), typeof pane.terminal_id === "string" ? pane.terminal_id : undefined)?.id,
176
183
  paneDispatch: async (server, pane) => {
177
184
  const dispatch = (await readTurn(server, String(pane.pane_id)))?.dispatch;