@phren/cli 0.3.58 → 0.3.59

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 (75) hide show
  1. package/README.md +1 -1
  2. package/dist/bridge/account-add.d.ts +30 -0
  3. package/dist/bridge/account-add.js +125 -19
  4. package/dist/bridge/account-failover.d.ts +9 -2
  5. package/dist/bridge/account-failover.js +1 -1
  6. package/dist/bridge/account-policy.d.ts +44 -0
  7. package/dist/bridge/account-policy.js +103 -0
  8. package/dist/bridge/account-pools.d.ts +35 -0
  9. package/dist/bridge/account-pools.js +171 -0
  10. package/dist/bridge/account-usage.d.ts +18 -0
  11. package/dist/bridge/account-usage.js +57 -1
  12. package/dist/bridge/agent-hook-callback.d.ts +6 -0
  13. package/dist/bridge/agent-hook-callback.js +10 -2
  14. package/dist/bridge/agent-hook-stores.d.ts +3 -0
  15. package/dist/bridge/agent-hook-stores.js +13 -0
  16. package/dist/bridge/agent-hooks.d.ts +12 -2
  17. package/dist/bridge/agent-hooks.js +41 -4
  18. package/dist/bridge/claude-account-setup.d.ts +16 -0
  19. package/dist/bridge/claude-account-setup.js +46 -2
  20. package/dist/bridge/claude-accounts.d.ts +9 -0
  21. package/dist/bridge/claude-accounts.js +53 -15
  22. package/dist/bridge/claude-credits.d.ts +5 -1
  23. package/dist/bridge/claude-credits.js +37 -29
  24. package/dist/bridge/command.js +12 -3
  25. package/dist/bridge/dispatch-command.js +22 -0
  26. package/dist/bridge/dispatch-returns.d.ts +23 -0
  27. package/dist/bridge/dispatch-returns.js +57 -0
  28. package/dist/bridge/dispatch.d.ts +26 -4
  29. package/dist/bridge/dispatch.js +100 -11
  30. package/dist/bridge/git-host-gitlab.js +2 -1
  31. package/dist/bridge/hand-off-queue.d.ts +71 -0
  32. package/dist/bridge/hand-off-queue.js +38 -0
  33. package/dist/bridge/harnesses.d.ts +12 -0
  34. package/dist/bridge/harnesses.js +20 -4
  35. package/dist/bridge/helper.d.ts +54 -0
  36. package/dist/bridge/helper.js +186 -0
  37. package/dist/bridge/herdr.js +6 -2
  38. package/dist/bridge/hook-fast.d.ts +3 -0
  39. package/dist/bridge/hook-fast.js +10 -2
  40. package/dist/bridge/move-computers.d.ts +15 -1
  41. package/dist/bridge/move-computers.js +123 -26
  42. package/dist/bridge/prompt-deliveries.d.ts +29 -1
  43. package/dist/bridge/prompt-deliveries.js +146 -10
  44. package/dist/bridge/schedule-watch.js +17 -3
  45. package/dist/bridge/server-routes.d.ts +3 -0
  46. package/dist/bridge/server-routes.js +66 -6
  47. package/dist/bridge/server.js +2 -1
  48. package/dist/bridge/session-move.d.ts +59 -1
  49. package/dist/bridge/session-move.js +266 -18
  50. package/dist/bridge/simulators.d.ts +19 -0
  51. package/dist/bridge/simulators.js +93 -13
  52. package/dist/bridge/speech-live.js +132 -22
  53. package/dist/bridge/task-routes.d.ts +16 -16
  54. package/dist/bridge/terminal-herdr.js +6 -1
  55. package/dist/bridge/terminal-tmux.js +9 -5
  56. package/dist/bridge/terminal.d.ts +9 -2
  57. package/dist/bridge/transcript-claude.d.ts +3 -0
  58. package/dist/bridge/transcript-claude.js +175 -29
  59. package/dist/bridge/transcript-preview.d.ts +11 -2
  60. package/dist/bridge/transcript-preview.js +90 -8
  61. package/dist/bridge/turn-records.d.ts +19 -0
  62. package/dist/bridge/turn-records.js +78 -3
  63. package/dist/bridge-hook.mjs +11394 -9961
  64. package/dist/cli-registry.js +2 -2
  65. package/dist/content/citation.d.ts +4 -0
  66. package/dist/content/citation.js +21 -21
  67. package/dist/data/task-contract.d.ts +4 -4
  68. package/dist/governance/policy.js +5 -2
  69. package/dist/index.js +1 -1
  70. package/dist/modules/registry.js +3 -3
  71. package/dist/project-config.d.ts +14 -0
  72. package/dist/project-config.js +40 -1
  73. package/dist/tools/helper.d.ts +3 -0
  74. package/dist/tools/helper.js +44 -0
  75. package/package.json +1 -1
@@ -1,8 +1,9 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { readFileSync } from "node:fs";
3
- import { open } from "node:fs/promises";
3
+ import { open, stat } from "node:fs/promises";
4
4
  import { z } from "zod";
5
- import { atomicInPrivateDir, object, objects, provider } from "./protocol.js";
5
+ import { materializedPath } from "./codex-threads.js";
6
+ import { atomicInPrivateDir, BridgeError, object, objects, provider, sessionId } from "./protocol.js";
6
7
  import { transcriptPath, unwrapPastedContent } from "./transcripts.js";
7
8
  /** A delivery the agent's turn ended without: the reason the phone shows. */
8
9
  export const TURN_ENDED_WITHOUT_IT = "The agent finished its turn without taking the message.";
@@ -17,6 +18,8 @@ const MAX_RECORDS = 512;
17
18
  const LANDED_CHECK_MS = 3_000;
18
19
  /** 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. */
19
20
  const ENTRY_SLACK_MS = 5_000;
21
+ /** A transcript is read from its last this many bytes: older rows are out of sight. */
22
+ const TRANSCRIPT_TAIL_BYTES = 524_288;
20
23
  /** 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
24
  const HOOK_ROW_MS = 30_000;
22
25
  /** Typed text holds its pane (nothing more is typed there) at most this long when the pane sends no
@@ -51,6 +54,9 @@ const recordSchema = z.object({
51
54
  /** From a joined prompt (`settleJoined`): "part", a message settled inside it, claims no row of its own (the turn's
52
55
  * row carries other words); "turn", the joined words themselves, no message of anyone's, claims that row. */
53
56
  joined: z.enum(["part", "turn"]).optional(),
57
+ /** Codex: the transcript's size in bytes when the message was registered. Only a row at or past it is
58
+ * the message's own: position, not the clock, orders rows, and a row without a timestamp too. */
59
+ cursor: z.number().int().nonnegative().optional(),
54
60
  }).strict();
55
61
  /** One message per record, bound to the pane it was typed into (server, pane,
56
62
  * agent kind), not to the conversation: a Codex thread or a Claude /clear can
@@ -73,10 +79,16 @@ export class PromptDeliveries {
73
79
  static open(record) { return record.state === "typed" || record.state === "queued"; }
74
80
  /** Open, or failed with its own hook's claim still waiting for its row (a late delivery). */
75
81
  static claimable(record) { return PromptDeliveries.open(record) || (record.state === "failed" && !!record.hookClaim); }
76
- constructor(file, now = Date.now, landed = transcriptEntries) {
82
+ /** Codex messages whose `cursor` is still being read. */
83
+ cursors = new Map();
84
+ /** The size of a conversation's transcript: 0 before it has one, undefined when it cannot be read. */
85
+ size;
86
+ constructor(file, now = Date.now, landed = transcriptEntries, size) {
77
87
  this.file = file;
78
88
  this.now = now;
79
89
  this.landed = landed;
90
+ // A store reading other transcripts than the agents' own has no sizes for them.
91
+ this.size = size ?? (landed === transcriptEntries ? transcriptSize : async () => undefined);
80
92
  if (!file)
81
93
  return;
82
94
  try {
@@ -105,7 +117,7 @@ export class PromptDeliveries {
105
117
  if (!this.file)
106
118
  return;
107
119
  // 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.
108
- const rows = this.records.filter(record => record.id || record.entry !== undefined || record.joined === "turn").map(({ idleSince: _, checkedAt: __, hookClaim: ___, seenRow: ____, ...row }) => row);
120
+ const rows = this.records.filter(record => record.id || record.entry !== undefined || record.joined === "turn").map(({ idleSince: _, checkedAt: __, hookClaim: ___, seenRow: ____, awaitingRow: _____, ...row }) => row);
109
121
  const file = this.file;
110
122
  this.writing = this.writing.then(() => atomicInPrivateDir(file, { records: rows })).catch(() => undefined);
111
123
  }
@@ -126,6 +138,16 @@ export class PromptDeliveries {
126
138
  session: target.session, ...(typeof terminal === "string" ? { terminal } : {}), state: "typed", at: this.now() };
127
139
  this.records.push(record);
128
140
  this.save();
141
+ // Started before the caller types the message (a stat, against typing, then the agent's own write), so
142
+ // the row it makes lands past the cursor; a row stamped after registration counts too (`codexRowIsOwn`).
143
+ if (record.source === "codex") {
144
+ const session = record.session;
145
+ this.cursors.set(record, this.size(record).then(size => { if (size !== undefined && record.session === session) {
146
+ record.cursor = size;
147
+ this.save();
148
+ } }, () => undefined)
149
+ .finally(() => this.cursors.delete(record)));
150
+ }
129
151
  return new Promise(resolve => {
130
152
  const timer = setTimeout(() => this.release(record, "pending"), waitMs);
131
153
  timer.unref?.();
@@ -313,6 +335,13 @@ export class PromptDeliveries {
313
335
  }
314
336
  this.settle(record, entry, target.session, entry !== undefined ? true : undefined);
315
337
  this.save();
338
+ if (target.source === "codex") {
339
+ // Its row is its own from now on, so a later message with these words never takes it, even once the
340
+ // row has left the scanned tail. Codex writes the row after its hooks return, and this callback is one
341
+ // of them: not awaited (the agent waits on its answer), and claimed by the next ticks when the row appears.
342
+ record.awaitingRow = true;
343
+ void this.claimCodexRow(record).catch(() => undefined);
344
+ }
316
345
  }
317
346
  /** Claude submits the messages it held while busy as one turn, joined by newlines, so no single message's
318
347
  * hash matches the prompt. Each open message in the pane whose words are a run of whole lines of it settles,
@@ -367,6 +396,9 @@ export class PromptDeliveries {
367
396
  delete record.reason;
368
397
  delete record.hookClaim;
369
398
  delete record.seenRow;
399
+ // A cursor is a position in one conversation's transcript.
400
+ if (session && session !== record.session)
401
+ delete record.cursor;
370
402
  if (session)
371
403
  record.session = session;
372
404
  if (entry !== undefined)
@@ -383,9 +415,8 @@ export class PromptDeliveries {
383
415
  * (`working` false) a user row settles too, for a hook that never came. Of several identical open
384
416
  * messages the oldest take the entries. `pass` carries the entries still unclaimed within one observe. */
385
417
  async taken(record, pass, working = false) {
386
- // Only Claude's transcript says which entry a message settled with; Codex keeps the any-match check.
387
418
  if (record.source !== "claude")
388
- return (await this.landed(record).catch(() => [])).length > 0;
419
+ return this.takenCodex(record);
389
420
  const same = (other) => other.hash === record.hash && other.server === record.server && other.pane === record.pane && other.session === record.session;
390
421
  const open = this.records.filter(other => same(other) && PromptDeliveries.claimable(other)).sort((a, b) => a.at - b.at);
391
422
  if (open[0] !== record)
@@ -442,6 +473,77 @@ export class PromptDeliveries {
442
473
  record.entryHook = entry.hook;
443
474
  return true;
444
475
  }
476
+ /** Whether a Codex transcript row can be `record`'s own: written after it was registered. A row at or past
477
+ * its cursor was; one before it only if stamped after registration (written while the cursor was read),
478
+ * which a row without a timestamp, such as a materialized Codex 0.155 thread's, never is. The scan itself
479
+ * drops rows stamped more than `ENTRY_SLACK_MS` before registration. */
480
+ static codexRowIsOwn(record, row) {
481
+ return (record.cursor !== undefined && row.offset >= record.cursor) || (row.at !== undefined && row.at >= record.at);
482
+ }
483
+ /** Rows of `record`'s words in its conversation, oldest first, and where the scan of them began: rows
484
+ * before `start` are out of sight, so whether they exist cannot be told. */
485
+ async codexRows(record) {
486
+ await this.cursors.get(record);
487
+ const rows = [...await this.landed(record).catch(() => [])].sort((a, b) => a.offset - b.offset);
488
+ // Read after the scan: a transcript that grew meanwhile puts `start` later than the scan's, never earlier.
489
+ const size = await this.size(record).catch(() => undefined);
490
+ return { rows, ...(size !== undefined ? { start: Math.max(0, size - TRANSCRIPT_TAIL_BYTES) } : {}) };
491
+ }
492
+ /** Rows with `record`'s words in its conversation claimed by other messages. */
493
+ codexClaimed(record) {
494
+ return new Set(this.records.filter(other => other !== record && other.hash === record.hash && this.samePane(other, record)
495
+ && other.session === record.session && other.entry !== undefined).map(other => other.entry));
496
+ }
497
+ /** A Codex message its hook settled takes the first free row written after it was registered. */
498
+ async claimCodexRow(record) {
499
+ const { rows, start } = await this.codexRows(record);
500
+ if (!record.awaitingRow || record.entry !== undefined)
501
+ return;
502
+ // Rows written after it have left the scanned tail: its own may be one of them, so it takes none of those left.
503
+ if (record.cursor !== undefined && start !== undefined && record.cursor < start) {
504
+ delete record.awaitingRow;
505
+ return;
506
+ }
507
+ const used = this.codexClaimed(record);
508
+ const row = rows.find(row => !used.has(row.offset) && PromptDeliveries.codexRowIsOwn(record, row));
509
+ if (!row)
510
+ return;
511
+ record.entry = row.offset;
512
+ record.entryHook = row.hook;
513
+ delete record.awaitingRow;
514
+ this.save();
515
+ }
516
+ /** Whether Codex took `record`'s message: a row written after it was registered (`codexRowIsOwn`) that no
517
+ * other message with these words claimed. An earlier message its hook settled whose row was not yet
518
+ * claimed holds the first such row of its own first, but only when everything written after it is still
519
+ * in the scanned tail: otherwise its row may be gone, and the row that is left is this message's. */
520
+ async takenCodex(record) {
521
+ const { rows, start } = await this.codexRows(record);
522
+ const used = this.codexClaimed(record);
523
+ let claimed = false;
524
+ for (const other of this.records.filter(other => other !== record && other.hash === record.hash && this.samePane(other, record) && other.session === record.session
525
+ && other.awaitingRow && other.entry === undefined && other.at < record.at).sort((a, b) => a.at - b.at)) {
526
+ if (other.cursor === undefined || start === undefined || other.cursor < start)
527
+ continue;
528
+ const row = rows.find(row => !used.has(row.offset) && PromptDeliveries.codexRowIsOwn(other, row));
529
+ if (!row)
530
+ continue;
531
+ other.entry = row.offset;
532
+ other.entryHook = row.hook;
533
+ delete other.awaitingRow;
534
+ used.add(row.offset);
535
+ claimed = true;
536
+ }
537
+ if (claimed)
538
+ this.save();
539
+ const entry = rows.find(row => !used.has(row.offset) && PromptDeliveries.codexRowIsOwn(record, row));
540
+ // The record may have settled (its hook came) while the transcript was read.
541
+ if (!entry || !PromptDeliveries.claimable(record))
542
+ return false;
543
+ record.entry = entry.offset;
544
+ record.entryHook = entry.hook;
545
+ return true;
546
+ }
445
547
  /** A turn in `target`'s pane ended: the agent now takes held input or never will. */
446
548
  stopped(target) {
447
549
  const at = this.now();
@@ -468,6 +570,16 @@ export class PromptDeliveries {
468
570
  for (const record of this.records) {
469
571
  if (record.server !== server)
470
572
  continue;
573
+ // A Codex message its hook settled claims its row once written, before a later identical one is checked.
574
+ if (record.awaitingRow) {
575
+ if (now - (record.settledAt ?? record.at) > HOOK_ROW_MS)
576
+ delete record.awaitingRow;
577
+ else if (record.checkedAt === undefined || now - record.checkedAt >= LANDED_CHECK_MS) {
578
+ record.checkedAt = now;
579
+ await this.claimCodexRow(record);
580
+ }
581
+ continue;
582
+ }
471
583
  // A failed message whose own hook came late, before its row: settled when the row appears.
472
584
  if (record.state === "failed" && record.hookClaim) {
473
585
  if (record.source === "claude" && (record.checkedAt === undefined || now - record.checkedAt >= LANDED_CHECK_MS)) {
@@ -535,7 +647,10 @@ export class PromptDeliveries {
535
647
  /** The byte offsets (in the file, `start` being the buffer's own offset) of the rows in `buffer`
536
648
  * whose user text has `record`'s words, newest first. One offset per row. */
537
649
  export function matchingOffsets(buffer, start, record) {
538
- const entries = [];
650
+ const entries = [], items = [];
651
+ // A Codex rollout writes each user turn twice, as a `user_message` event and a user `response_item`:
652
+ // the event alone is the turn. Only a thread materialized from Codex 0.155's history has items without events.
653
+ let events = false;
539
654
  const lines = buffer.toString("utf8").split("\n");
540
655
  let offset = start + buffer.length;
541
656
  for (let index = lines.length - 1; index >= 0; index--) {
@@ -554,19 +669,40 @@ export function matchingOffsets(buffer, start, record) {
554
669
  // Rows are not in time order: Claude writes a queued message's attachment rows, stamped when it was
555
670
  // typed, after the queue removal that took it. An older row is skipped, never the end of the scan,
556
671
  // or a message typed after an earlier queued one is never found (seen 2026-10-17: taken, reported failed).
672
+ const payload = object(row.payload), item = row.type === "response_item" && payload.type === "message";
673
+ if (row.type === "event_msg" && payload.type === "user_message")
674
+ events = true;
557
675
  const stamp = Date.parse(String(row.timestamp ?? ""));
558
676
  if (Number.isFinite(stamp) && stamp < record.at - 5_000)
559
677
  continue;
560
678
  // One entry per row, even when its content repeats the words.
561
679
  if (userTexts(row).some(text => promptHash(text) === record.hash))
562
- entries.push({ offset, hook: row.type === "user", ...(Number.isFinite(stamp) ? { at: stamp } : {}) });
680
+ (item ? items : entries).push({ offset, hook: row.type === "user", ...(Number.isFinite(stamp) ? { at: stamp } : {}) });
681
+ }
682
+ return events ? entries : [...entries, ...items].sort((a, b) => b.offset - a.offset);
683
+ }
684
+ export async function transcriptSize(record) {
685
+ // A Codex 0.155 thread's copy is read as it stands: finding the transcript first appends what the thread store
686
+ // holds now, which may already be this message, and a failed append must not read as an empty conversation.
687
+ const copy = record.source === "codex" && sessionId.safeParse(record.session).success
688
+ ? await stat(materializedPath(record.session)).catch(() => undefined) : undefined;
689
+ if (copy)
690
+ return copy.size;
691
+ try {
692
+ const file = await transcriptPath(record.source, record.session);
693
+ // Its copy made just now holds both older messages and maybe this one: no position tells them apart,
694
+ // and only a timestamped row (none in a copy) can confirm it.
695
+ return file === materializedPath(record.session) ? undefined : (await stat(file)).size;
696
+ }
697
+ catch (error) {
698
+ // A conversation not written yet (a new Codex thread) has nothing before its first row.
699
+ return error instanceof BridgeError && object(error.details).code === "transcript-unavailable" ? 0 : undefined;
563
700
  }
564
- return entries;
565
701
  }
566
702
  async function transcriptEntries(record) {
567
703
  const file = await open(await transcriptPath(record.source, record.session), "r");
568
704
  try {
569
- const size = (await file.stat()).size, start = Math.max(0, size - 524_288), buffer = Buffer.alloc(size - start);
705
+ const size = (await file.stat()).size, start = Math.max(0, size - TRANSCRIPT_TAIL_BYTES), buffer = Buffer.alloc(size - start);
570
706
  await file.read(buffer, 0, buffer.length, start);
571
707
  return matchingOffsets(buffer, start, record);
572
708
  }
@@ -222,7 +222,7 @@ export function finalTurnFromLines(lines, source) {
222
222
  completed = false;
223
223
  continue;
224
224
  }
225
- const userTurn = source === "claude" ? raw.type === "user" && !raw.isMeta && typeof object(raw.message).content === "string"
225
+ const userTurn = source === "claude" ? raw.type === "user" && !raw.isMeta && claudeUserText(raw) !== undefined
226
226
  : source === "codex" ? raw.type === "response_item" && payload.type === "message" && payload.role === "user"
227
227
  : source === "copilot" ? raw.type === "user.message"
228
228
  : raw.type === "user/message";
@@ -267,12 +267,26 @@ export function finalTurnFromLines(lines, source) {
267
267
  /** A prompt the owner (or a dispatcher) typed, not a task's notification or
268
268
  * a teammate's message waking the session. */
269
269
  function ownerPrompt(raw) {
270
- const content = object(raw.message).content;
271
- if (raw.type !== "user" || raw.isMeta || typeof content !== "string")
270
+ // Claude files "[Request interrupted by user]" as a user row too: that is a stop, not the owner moving on.
271
+ const content = raw.type === "user" && !raw.isMeta && !turnInterrupted(raw, "claude") ? claudeUserText(raw) : undefined;
272
+ if (content === undefined)
272
273
  return false;
273
274
  const text = content.trimStart();
274
275
  return !text.startsWith("<task-notification>") && !text.startsWith("<teammate-message");
275
276
  }
277
+ /** A Claude user row's text when it is a message someone typed: a string, or blocks of text and images (a
278
+ * prompt with a pasted screenshot). A tool's result, which Claude also files as a user row, is not one. */
279
+ function claudeUserText(raw) {
280
+ const content = object(raw.message).content;
281
+ if (typeof content === "string")
282
+ return content;
283
+ if (!Array.isArray(content) || !content.length)
284
+ return undefined;
285
+ const blocks = content.map(object);
286
+ if (!blocks.every(block => block.type === "text" || block.type === "image"))
287
+ return undefined;
288
+ return blocks.filter(block => block.type === "text" && typeof block.text === "string").map(block => String(block.text)).join("\n");
289
+ }
276
290
  /** The final turn of a conversation, read from the tail of its transcript. */
277
291
  export async function readFinalTurn(source, sessionId) {
278
292
  if (!sessionId)
@@ -118,6 +118,8 @@ export declare const capabilities: {
118
118
  approvalPush: string;
119
119
  simulators: boolean;
120
120
  simulatorStream: boolean;
121
+ simulatorDevices: boolean;
122
+ simulatorDrag: boolean;
121
123
  code: boolean;
122
124
  codeFiles: boolean;
123
125
  overviewStream: boolean;
@@ -147,6 +149,7 @@ export declare const capabilities: {
147
149
  moveConductorToComputer: boolean;
148
150
  moveResume: boolean;
149
151
  claudeAccountAdd: boolean;
152
+ accountPools: boolean;
150
153
  workerRelocation: number;
151
154
  projectMemory: boolean;
152
155
  fileWrite: boolean;
@@ -3,7 +3,9 @@ import { peerFingerprint } from "./dispatch-hosts.js";
3
3
  import { redactPeerHandoff } from "./peer-handoff.js";
4
4
  import { relocationSupport } from "./worker-relocation.js";
5
5
  import { continuationIntent, continuationLaunchSchema, continuationPlacement, launchContinuation } from "./continuation-launch.js";
6
- import { addClaudeAccount } from "./account-add.js";
6
+ import { addClaudeAccount, signInClaudeAccount } from "./account-add.js";
7
+ import { ACCOUNT_ROLES, isAccountRole, setAccountSettings, setComputerAllowedPools } from "./account-pools.js";
8
+ import { claudeHome } from "./claude-accounts.js";
7
9
  import { localMoveAvailability, moveComputers } from "./move-computers.js";
8
10
  import { ownerRequest, requestPeer } from "./request-origin.js";
9
11
  import { listMoves, moveSessionFields, readMove } from "./session-move.js";
@@ -43,7 +45,7 @@ import { locateProject } from "./locate.js";
43
45
  import { gitStatus } from "./git.js";
44
46
  import { gitRoot, launchDirectory, repositoryBranch, webServers, withGitReadDeadline } from "./projects.js";
45
47
  import { approvalDecisions, BridgeError, bridgeRoot, MAX_FRAME, object, objects, PROTOCOL, provider, serverName, targetFromURL, targetSchema } from "./protocol.js";
46
- import { bootedSimulators, simulatorAct, simulatorApps, simulatorScreenshot } from "./simulators.js";
48
+ import { bootedSimulators, simulatorAct, simulatorApps, simulatorDevices, simulatorScreenshot } from "./simulators.js";
47
49
  import { childAgentTree, historicalImage, publicChildAgents, refreshTranscript, runningChildAgents, targetTranscriptPath } from "./transcripts.js";
48
50
  import { listUploads, removeUpload, saveUpload, uploadImage } from "./uploads.js";
49
51
  import { currentModel, currentStep } from "./steps.js";
@@ -89,7 +91,7 @@ async function childActivity(source, session) {
89
91
  export const capabilities = { transcript: true, progress: true, images: true, prompt: true, stop: true,
90
92
  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
93
  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", simulatorStream: 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 };
94
+ 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", simulatorStream: process.platform === "darwin", simulatorDevices: process.platform === "darwin", simulatorDrag: 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, accountPools: true, workerRelocation: 1, projectMemory: true, fileWrite: true, fileSearch: true, gitReview: true, memoryStoreBatch: true, gitHosts: true, projectHostToken: true };
93
95
  export function capabilitiesForModules(snapshot) {
94
96
  const allowed = new Set(snapshot.modules.flatMap(module => module.capabilities));
95
97
  const result = Object.fromEntries(Object.entries(capabilities).filter(([name]) => allowed.has(name)));
@@ -604,8 +606,9 @@ export function createRouteHandler(ctx) {
604
606
  case "/v1/web-servers":
605
607
  result = { servers: await webServers() };
606
608
  break;
609
+ // `all=1` (capability simulatorDevices): every available device with its state, for the phone's picker.
607
610
  case "/v1/simulators":
608
- result = { simulators: await bootedSimulators() };
611
+ result = { simulators: url.searchParams.get("all") === "1" ? await simulatorDevices() : await bootedSimulators() };
609
612
  break;
610
613
  case "/v1/simulators/screenshot": {
611
614
  const bytes = await simulatorScreenshot(String(url.searchParams.get("udid") ?? ""));
@@ -947,6 +950,30 @@ export function createRouteHandler(ctx) {
947
950
  harness: note.target && "harness" in note.target ? note.target.harness : "codex", prompt, label: `Code note: ${note.symbol}`.slice(0, 200) });
948
951
  } : undefined);
949
952
  }
953
+ else if (url.pathname === "/v1/sessions/move" && data.interrupt === true) {
954
+ // "Stop <agent> and hand off now": Escape only while the move's hand-off request is still held.
955
+ if (!ownerRequest(request, data))
956
+ throw new BridgeError(403, "Only the owner can interrupt a move's agent.");
957
+ if (!ctx.mover)
958
+ throw new BridgeError(503, "Session moves are unavailable.");
959
+ const { id } = z.object({ id: z.string().uuid(), interrupt: z.literal(true), origin: z.unknown().optional() }).strict().parse(data);
960
+ // Esc as /v1/keys sends it: a served OpenCode pane or a Codex pane on the Hook's own app-server stops
961
+ // its turn over its API; otherwise the key goes to the pane. A question the Hook holds is declined
962
+ // first, and the turn is still stopped: a declined question alone lets the turn carry on.
963
+ const escape = async (target) => {
964
+ if (await agentHooks.servedKeys(target, ["Escape"], "working", { abortTurn: true }))
965
+ return;
966
+ agentHooks.cancelHeldQuestion(target);
967
+ const { codexServers } = await import("./codex-servers.js");
968
+ const owned = codexServers.forTarget(target);
969
+ if (owned && await codexServers.interrupt(owned).catch(() => false)) {
970
+ agentHooks.clearTerminalPrompt(target);
971
+ return;
972
+ }
973
+ await terminalProvider().sendKeys(target.server, target.pane, ["esc"]);
974
+ };
975
+ result = { ok: true, ...await ctx.mover.interrupt(id, ctx.handOffs, escape) };
976
+ }
950
977
  else if (url.pathname === "/v1/sessions/move") {
951
978
  // Answers once the move is checked and recorded; the hand-off and relaunch run on, and GET says where it is.
952
979
  if (!ctx.mover)
@@ -990,7 +1017,31 @@ export function createRouteHandler(ctx) {
990
1017
  else if (url.pathname === "/v1/accounts/claude/add") {
991
1018
  if (!ownerRequest(request, data))
992
1019
  throw new BridgeError(403, "Only the owner can add a Claude account.");
993
- result = await launches.run(() => addClaudeAccount(data, selectedServer(url)));
1020
+ // `mode`: sign in a slot that exists but is signed out, or ask whether it is signed in yet.
1021
+ result = data.mode === undefined ? await launches.run(() => addClaudeAccount(data, selectedServer(url)))
1022
+ : data.mode === "sign-in-status" ? await signInClaudeAccount(data, selectedServer(url))
1023
+ : await launches.run(() => signInClaudeAccount(data, selectedServer(url)));
1024
+ }
1025
+ else if (url.pathname === "/v1/accounts/claude/settings") {
1026
+ // An account's pool and role (account-pools.ts): a field left out stays, null clears it.
1027
+ if (!ownerRequest(request, data))
1028
+ throw new BridgeError(403, "Only the owner can change an account's pool or role.");
1029
+ const input = z.object({ slug: z.string().max(64), pool: z.string().max(64).nullable().optional(), role: z.string().max(32).nullable().optional(), origin: z.unknown().optional() }).strict().parse(data);
1030
+ if (!claudeHome(input.slug))
1031
+ throw new BridgeError(404, `There is no Claude account "${input.slug}" on this computer.`);
1032
+ if (input.role !== undefined && input.role !== null && !isAccountRole(input.role))
1033
+ throw new BridgeError(400, `A role is ${ACCOUNT_ROLES.join(", ")}.`);
1034
+ const settings = await setAccountSettings(input.slug, { pool: input.pool, role: input.role })
1035
+ .catch((error) => { throw new BridgeError(400, error.message); });
1036
+ result = { ok: true, slug: input.slug, ...settings };
1037
+ }
1038
+ else if (url.pathname === "/v1/accounts/allowed-pools") {
1039
+ // The pools this computer's accounts may do work for; null clears the list (any pool).
1040
+ if (!ownerRequest(request, data))
1041
+ throw new BridgeError(403, "Only the owner can change this computer's allowed pools.");
1042
+ const input = z.object({ allowedPools: z.array(z.string().max(64)).max(64).nullable(), origin: z.unknown().optional() }).strict().parse(data);
1043
+ const allowedPools = await setComputerAllowedPools(input.allowedPools).catch((error) => { throw new BridgeError(400, error.message); });
1044
+ result = { ok: true, ...(allowedPools ? { allowedPools } : {}) };
994
1045
  }
995
1046
  else if (url.pathname === "/v1/sessions/rename") {
996
1047
  result = await renameSession(selectedServer(url), data);
@@ -1056,6 +1107,13 @@ export function createRouteHandler(ctx) {
1056
1107
  else if (url.pathname === "/v1/dispatch/workers") {
1057
1108
  result = await hookWorkers(agentHooks)(data);
1058
1109
  }
1110
+ else if (url.pathname === "/v1/dispatch/returns" && url.searchParams.get("peek") === "1") {
1111
+ // The unread returns, left unread: a watcher (`phren dispatch returns --watch`) beside an agent
1112
+ // conductor, which still takes them. Read here, never forwarded to a successor, which would take them.
1113
+ if (request.headers?.["x-phren-origin"] === "peer")
1114
+ throw new BridgeError(403, "Peer conductor operations require the authenticated generation-scoped routes.");
1115
+ result = { returns: await ctx.returns.take(false) };
1116
+ }
1059
1117
  else if (url.pathname === "/v1/dispatch/returns") {
1060
1118
  result = await conductorCall("returns", {}, data.origin, async () => ({ returns: await ctx.returns.take() }));
1061
1119
  }
@@ -1150,7 +1208,9 @@ export function createRouteHandler(ctx) {
1150
1208
  result = await launches.run(async () => enrollProject(z.object({ directory: z.string().max(4096).optional(), cloneUrl: z.string().max(512).optional(), project: z.string().max(100).optional(), store: z.string().max(200).optional() }).parse(data)));
1151
1209
  }
1152
1210
  else if (url.pathname === "/v1/simulators/action") {
1153
- result = await simulatorAct(z.string().parse(data.udid), z.object({ action: z.string(), bundleId: z.string().optional(), url: z.string().optional(), x: z.number().optional(), y: z.number().optional(), text: z.string().optional(), submit: z.boolean().optional() }).parse(data));
1211
+ result = await simulatorAct(z.string().parse(data.udid), z.object({ action: z.string(), bundleId: z.string().optional(), url: z.string().optional(), x: z.number().optional(), y: z.number().optional(),
1212
+ x1: z.number().optional(), y1: z.number().optional(), x2: z.number().optional(), y2: z.number().optional(), durationMs: z.number().optional(),
1213
+ text: z.string().optional(), submit: z.boolean().optional() }).parse(data));
1154
1214
  }
1155
1215
  else {
1156
1216
  if (url.pathname === "/v1/workspaces/launch") {
@@ -114,7 +114,7 @@ export async function serve(version, options = {}) {
114
114
  localComputer: { id: computerID, name: hostname() },
115
115
  forward: (origin, text, deliveryId) => succession?.forward(origin, text, deliveryId) ?? Promise.resolve(undefined),
116
116
  // Continue on another signed-in account when a Claude worker stops at its usage limit: opt-in, `phren config account-failover on`.
117
- failover: new AccountFailover({ rooms: () => dispatches.claudeRooms(), dispatch: (input, origin, continues) => succession ? succession.automatic("dispatch", { ...input, continues }, origin, () => dispatches.dispatch(input, origin, continues)) : dispatches.dispatch(input, origin, continues) }),
117
+ failover: new AccountFailover({ rooms: context => dispatches.claudeRooms(context), dispatch: (input, origin, continues) => succession ? succession.automatic("dispatch", { ...input, continues }, origin, () => dispatches.dispatch(input, origin, continues)) : dispatches.dispatch(input, origin, continues) }),
118
118
  localWorkers: hookWorkers(agentHooks),
119
119
  close: async (receipt, verifiedPeer) => {
120
120
  const data = { target: receipt.target, dispatch: receipt.moves?.slice().reverse().find(move => move.to.computer)?.id ?? receipt.id, turn: receipt.closePending.turn };
@@ -175,6 +175,7 @@ export async function serve(version, options = {}) {
175
175
  identity: (server, pane) => paneIdentity(server, pane, true),
176
176
  terminal: terminalProvider(),
177
177
  deliver: (target, text, deliveryId) => handOffs ? handOffs.enqueue({ target, text, deliveryId }) : sendPrompt(target, text, deliveryId, async () => { }),
178
+ withdraw: async (target, deliveryId, reason) => handOffs?.withdraw(deliveryId, target, reason),
178
179
  // The new agent starts in the folder an agent already ran in, so it is trusted for the new harness too.
179
180
  launch: (server, data, options) => launches.run(() => launchSession(server, data, { trustFolder: true, ...options })),
180
181
  inventory: () => launchCheckOff() ? Promise.resolve(undefined) : harnessInventoryWithin(2_500),
@@ -5,6 +5,7 @@ import { moveToSchema } from "./dispatch.js";
5
5
  import { type HarnessInventory } from "./harnesses.js";
6
6
  import { type Json, type Provider, type StartingTarget, type Target } from "./protocol.js";
7
7
  import type { TerminalProvider } from "./terminal.js";
8
+ import type { HandOffQueue } from "./hand-off-queue.js";
8
9
  export { moveToSchema };
9
10
  export type MoveTo = z.infer<typeof moveToSchema>;
10
11
  export declare const moveRequestSchema: z.ZodObject<{
@@ -48,6 +49,7 @@ export declare const moveRequestSchema: z.ZodObject<{
48
49
  continuation: z.ZodDefault<z.ZodEnum<{
49
50
  handoff: "handoff";
50
51
  resume: "resume";
52
+ "summary-by-target": "summary-by-target";
51
53
  }>>;
52
54
  id: z.ZodOptional<z.ZodString>;
53
55
  handoffTimeoutMs: z.ZodOptional<z.ZodNumber>;
@@ -110,7 +112,10 @@ declare const moveRecordSchema: z.ZodObject<{
110
112
  "new-chat": "new-chat";
111
113
  replace: "replace";
112
114
  }>>;
113
- continuation: z.ZodOptional<z.ZodLiteral<"resume">>;
115
+ continuation: z.ZodOptional<z.ZodEnum<{
116
+ resume: "resume";
117
+ "summary-by-target": "summary-by-target";
118
+ }>>;
114
119
  modeForced: z.ZodOptional<z.ZodLiteral<"conductor">>;
115
120
  handedOffTo: z.ZodOptional<z.ZodObject<{
116
121
  computer: z.ZodOptional<z.ZodString>;
@@ -247,6 +252,17 @@ export interface MovedWorker {
247
252
  to: MoveTo;
248
253
  target: Target | StartingTarget;
249
254
  }
255
+ /** What "stop and hand off now" did: interrupted the step, or why not. `idle`: the agent is on no step,
256
+ * so its request goes in without one; `typed`: the request is being or was typed; `writing`: the agent took
257
+ * it and writes its hand-off; `finished`: the move is past its hand-off, or its request can no longer be
258
+ * delivered (the move then builds a hand-off itself); `replaced`: the pane now runs another agent or
259
+ * conversation than the one the move asked, which is never interrupted for it. */
260
+ export type MoveInterrupt = {
261
+ interrupted: true;
262
+ } | {
263
+ interrupted: false;
264
+ state: "idle" | "typed" | "writing" | "finished" | "replaced";
265
+ };
250
266
  export declare function movesRoot(): string;
251
267
  /** The hand-off sits beside the new agent's brief, in a folder Claude is given read access to. */
252
268
  export declare const handoffPath: (id: string) => string;
@@ -312,6 +328,25 @@ export declare function fallbackHandoff(input: {
312
328
  dispatch?: string;
313
329
  label?: string;
314
330
  }): string;
331
+ /** Whether a Claude conversation's last turn ended on its subscription's usage limit (Claude's own
332
+ * rate-limit row): its agent cannot answer a hand-off request. */
333
+ export declare function sourceOutOfUsage(lines: readonly string[], source: Provider): boolean;
334
+ /**
335
+ * The hand-off for a source that does not write one (its account is out of usage, or the owner asked), for a
336
+ * fresh agent on the target computer to build itself: what happened, then as much of the conversation as fits
337
+ * in `room` characters, newest messages kept, oldest first. The target agent writes its own summary from it first.
338
+ */
339
+ export declare function targetSummaryBody(input: {
340
+ from: string;
341
+ exhausted: boolean;
342
+ entries: readonly TailEntry[];
343
+ room: number;
344
+ original?: string;
345
+ dispatch?: string;
346
+ label?: string;
347
+ /** Each message as it will be sent (paths replaced, credentials redacted), so it is measured at its sent size. */
348
+ prepare?: (text: string) => string;
349
+ }): string;
315
350
  /** The hand-off file: who moved where and when, the body, then what Phren saw. */
316
351
  export declare function handoffDocument(record: MoveRecord, body: string, observed: string, at: string, conductor?: boolean): string;
317
352
  /** The new agent's first prompt: the whole hand-off when it fits the brief, else where to read it. */
@@ -324,6 +359,8 @@ export interface MoverDeps {
324
359
  terminal: Pick<TerminalProvider, "prompt" | "sendKeys" | "processes" | "closePane">;
325
360
  /** The `hand_off` delivery path: queued while the agent is busy. */
326
361
  deliver: (target: Target, text: string, deliveryId: string) => Promise<Json>;
362
+ /** Takes back a message `deliver` queued while it is still untyped (`HandOffQueue.withdraw`). */
363
+ withdraw?: (target: Target, deliveryId: string, reason: string) => Promise<unknown>;
327
364
  /** Starts the new agent (`startSession`), in `into` when given. */
328
365
  launch: (server: string, data: Json, options: {
329
366
  into?: {
@@ -366,9 +403,17 @@ export interface MoverDeps {
366
403
  export declare class SessionMover {
367
404
  private readonly deps;
368
405
  private readonly cancelled;
406
+ /** Moves this process is waiting on: their hand-off request was handed to the queue, and the wait for the
407
+ * agent's answer is not over (it answered, the wait ran out, or the owner aborted). Only these are interrupted:
408
+ * a move whose request was never sent (summary-by-target, or not yet), or one this process no longer runs
409
+ * (the Hook restarted), has no request an Escape would let in. */
410
+ private readonly asking;
411
+ /** Per move, the hand-off's end and an interrupt's check-and-send, one at a time. */
412
+ private readonly lifecycles;
369
413
  private readonly admissions;
370
414
  private readonly running;
371
415
  constructor(deps: MoverDeps);
416
+ private lifecycle;
372
417
  private get now();
373
418
  private sleep;
374
419
  private get poll();
@@ -381,7 +426,20 @@ export declare class SessionMover {
381
426
  settled(server: string, pane: string): Promise<void> | undefined;
382
427
  private update;
383
428
  private run;
429
+ /**
430
+ * "Stop <agent> and hand off now": Escape to the old agent only while the move's hand-off request is
431
+ * still held for it (queued behind the step it is on, not yet typed), so the step stops and the request
432
+ * goes in, and never into the hand-off the agent is writing. Checked and sent under the hand-off queue's
433
+ * lock (`whileQueued`), which is what types the request, and under the move's own lifecycle lock, which is
434
+ * what ends the hand-off wait: the move cannot go on to exit or launch between the check and the key.
435
+ * `state` says why it did not: the request is being or was typed (`typed`), the agent is writing its
436
+ * hand-off (`writing`), the move is past it, or the pane runs another agent now (`replaced`).
437
+ */
438
+ interrupt(id: string, queue?: Pick<HandOffQueue, "whileQueued">, escape?: (target: Target) => Promise<void>): Promise<MoveInterrupt>;
384
439
  abort(id: string): Promise<MoveRecord>;
440
+ /** Takes the move's hand-off request back while it is still queued. Outside the move's lifecycle lock: an
441
+ * interrupt holds the queue's lock while it waits for that one, so this must not wait the other way round. */
442
+ private withdrawRequest;
385
443
  private assertNotAborted;
386
444
  private continueOnPeer;
387
445
  /** Startup and tick recovery reuse the receiving Hook's durable move id.