@phren/cli 0.3.59 → 0.3.61

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.
@@ -22,6 +22,8 @@ const ENTRY_SLACK_MS = 5_000;
22
22
  const TRANSCRIPT_TAIL_BYTES = 524_288;
23
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. */
24
24
  const HOOK_ROW_MS = 30_000;
25
+ /** How long after a phone message settled its row's line is still looked for. */
26
+ const LOCATE_FOR_MS = 5 * 60_000;
25
27
  /** Typed text holds its pane (nothing more is typed there) at most this long when the pane sends no
26
28
  * UserPromptSubmit or Stop to settle it: a message such an agent took or dropped never settles. */
27
29
  export const IN_FLIGHT_MS = 45_000;
@@ -58,6 +60,9 @@ const recordSchema = z.object({
58
60
  * the message's own: position, not the clock, orders rows, and a row without a timestamp too. */
59
61
  cursor: z.number().int().nonnegative().optional(),
60
62
  }).strict();
63
+ const landedFile = (file) => `${file}.landed.json`;
64
+ const landedSchema = z.object({ line: z.number().int().nonnegative().optional(), uuid: z.string().min(1).max(100).optional(),
65
+ shown: z.number().int().nonnegative().optional(), late: z.literal(true).optional() }).strict();
61
66
  /** One message per record, bound to the pane it was typed into (server, pane,
62
67
  * agent kind), not to the conversation: a Codex thread or a Claude /clear can
63
68
  * replace the conversation while the agent still holds the typed text, and
@@ -83,12 +88,16 @@ export class PromptDeliveries {
83
88
  cursors = new Map();
84
89
  /** The size of a conversation's transcript: 0 before it has one, undefined when it cannot be read. */
85
90
  size;
86
- constructor(file, now = Date.now, landed = transcriptEntries, size) {
91
+ /** The line (0-based) of the row at a byte offset in a conversation's transcript, when one still starts there
92
+ * (and carries `uuid`, when given). */
93
+ lineOf;
94
+ constructor(file, now = Date.now, landed = transcriptEntries, size, lineOf) {
87
95
  this.file = file;
88
96
  this.now = now;
89
97
  this.landed = landed;
90
- // A store reading other transcripts than the agents' own has no sizes for them.
98
+ // A store reading other transcripts than the agents' own has no sizes or lines for them.
91
99
  this.size = size ?? (landed === transcriptEntries ? transcriptSize : async () => undefined);
100
+ this.lineOf = lineOf ?? (landed === transcriptEntries ? transcriptLine : async () => undefined);
92
101
  if (!file)
93
102
  return;
94
103
  try {
@@ -101,6 +110,22 @@ export class PromptDeliveries {
101
110
  }
102
111
  }
103
112
  catch { /* No file yet, or an unreadable one: start empty. */ }
113
+ try {
114
+ for (const [id, row] of Object.entries(object(JSON.parse(readFileSync(landedFile(file), "utf8"))))) {
115
+ const parsed = landedSchema.safeParse(row), record = this.byId(id);
116
+ if (!parsed.success || !record || record.entry === undefined)
117
+ continue;
118
+ if (parsed.data.line !== undefined)
119
+ record.entryLine = parsed.data.line;
120
+ if (parsed.data.uuid)
121
+ record.entryUuid = parsed.data.uuid;
122
+ if (parsed.data.shown !== undefined)
123
+ record.entryShown = parsed.data.shown;
124
+ if (parsed.data.late)
125
+ record.entryLate = true;
126
+ }
127
+ }
128
+ catch { /* None yet: rows found before this version, or none. */ }
104
129
  this.prune();
105
130
  }
106
131
  samePane(record, target) {
@@ -117,9 +142,17 @@ export class PromptDeliveries {
117
142
  if (!this.file)
118
143
  return;
119
144
  // 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.
120
- const rows = this.records.filter(record => record.id || record.entry !== undefined || record.joined === "turn").map(({ idleSince: _, checkedAt: __, hookClaim: ___, seenRow: ____, awaitingRow: _____, ...row }) => row);
145
+ const kept = this.records.filter(record => record.id || record.entry !== undefined || record.joined === "turn");
146
+ const rows = kept.map(({ idleSince: _, checkedAt: __, hookClaim: ___, seenRow: ____, awaitingRow: _____, entryLate: _a, entryLine: _b, entryUuid: _c, entryShown: _d, ...row }) => row);
147
+ // The rows phone messages landed as, apart from the records an older Hook reads strictly.
148
+ const landed = {};
149
+ for (const record of kept)
150
+ if (record.id && record.entry !== undefined && (record.entryLine !== undefined || record.entryUuid || record.entryShown !== undefined || record.entryLate)) {
151
+ landed[record.id] = { ...(record.entryLine !== undefined ? { line: record.entryLine } : {}), ...(record.entryUuid ? { uuid: record.entryUuid } : {}),
152
+ ...(record.entryShown !== undefined ? { shown: record.entryShown } : {}), ...(record.entryLate ? { late: true } : {}) };
153
+ }
121
154
  const file = this.file;
122
- this.writing = this.writing.then(() => atomicInPrivateDir(file, { records: rows })).catch(() => undefined);
155
+ this.writing = this.writing.then(async () => { await atomicInPrivateDir(file, { records: rows }); await atomicInPrivateDir(landedFile(file), landed); }).catch(() => undefined);
123
156
  }
124
157
  /** Settled writes, for tests and an orderly shutdown. */
125
158
  flush() { return this.writing; }
@@ -259,7 +292,10 @@ export class PromptDeliveries {
259
292
  const record = this.find(id, target);
260
293
  if (!record || record.state === "typed")
261
294
  return { state: "unknown" };
262
- return { state: record.state, ...(record.reason && record.state === "failed" ? { reason: record.reason } : {}), session: record.session };
295
+ // Once delivered and its row is known: the transcript row it landed as, to match a pending send by.
296
+ const landed = record.state === "delivered" && record.entryLine !== undefined
297
+ ? { line: record.entryLine, ...(record.entryUuid ? { uuid: record.entryUuid } : {}) } : undefined;
298
+ return { state: record.state, ...(record.reason && record.state === "failed" ? { reason: record.reason } : {}), session: record.session, ...(landed ? { landed } : {}) };
263
299
  }
264
300
  /** Every known phone message in `target`'s pane, for its conversation's stream. */
265
301
  forPane(target) {
@@ -311,7 +347,11 @@ export class PromptDeliveries {
311
347
  return;
312
348
  // Claims are per conversation: another conversation's rows can sit at the same byte offset.
313
349
  // Only user rows count: a mid-turn queue removal never had a hook, so it says nothing about this callback.
314
- 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));
350
+ const claimers = this.records.filter(other => other.hash === hash && this.samePane(other, target) && other.session === target.session && other.entry !== undefined && other.entryHook !== false);
351
+ const claimed = new Set(claimers.map(other => other.entry));
352
+ // A row an earlier message took only to name it in its receipt (`entryLate`) is never offered again, but it
353
+ // says nothing about this callback: that message's hook already came, so this one is not it, late.
354
+ const waitedOn = claimers.filter(other => !other.entryLate).length;
315
355
  const free = rows?.filter(row => !claimed.has(row.offset)).sort((a, b) => a.offset - b.offset)[0];
316
356
  // Claude writes the submitted row only after its UserPromptSubmit hooks return, and this callback is one
317
357
  // of them: the row for this submission is never readable yet. So no free row (or a transcript that cannot
@@ -319,8 +359,11 @@ export class PromptDeliveries {
319
359
  // writes next stays this message's (`taken` counts hook-settled messages first). Only when a message
320
360
  // with these words already claimed a row in this conversation may the callback be that message's, late:
321
361
  // then it waits for a row of its own, looked for in the conversation that made the claim.
322
- if (!free && !claimed.size) {
323
- this.settle(record, undefined, target.session);
362
+ if (!free && !waitedOn) {
363
+ this.settle(record, target.session);
364
+ // A phone message claims the row Claude writes next, so its receipt can name it (`claimClaudeRow`).
365
+ if (record.id)
366
+ record.awaitingRow = true;
324
367
  this.save();
325
368
  return;
326
369
  }
@@ -331,9 +374,11 @@ export class PromptDeliveries {
331
374
  }
332
375
  return;
333
376
  }
334
- entry = free.offset;
377
+ entry = free;
335
378
  }
336
- this.settle(record, entry, target.session, entry !== undefined ? true : undefined);
379
+ this.settle(record, target.session);
380
+ if (entry)
381
+ this.claim(record, entry, true);
337
382
  this.save();
338
383
  if (target.source === "codex") {
339
384
  // Its row is its own from now on, so a later message with these words never takes it, even once the
@@ -381,7 +426,7 @@ export class PromptDeliveries {
381
426
  return false;
382
427
  for (const record of matched) {
383
428
  record.joined = "part";
384
- this.settle(record, undefined, target.session);
429
+ this.settle(record, target.session);
385
430
  }
386
431
  // The turn's row carries the joined words: a hook-settled record of them (no phone id) claims it as
387
432
  // `taken` lets any hook-settled message, so a later message with the same words cannot take it.
@@ -389,8 +434,50 @@ export class PromptDeliveries {
389
434
  state: "delivered", at: this.now(), settledAt: this.now(), joined: "turn" });
390
435
  return true;
391
436
  }
392
- /** Marks `record` delivered, with the transcript entry that settled it when known. */
393
- settle(record, entry, session, hook) {
437
+ /** `record` takes transcript row `row` as its own: the entry no other message with these words may take, and,
438
+ * for a phone message, the row its receipt names (`landed`), whose line is counted in the background. */
439
+ claim(record, row, hook = row.hook, late = false) {
440
+ record.entry = row.offset;
441
+ record.entryHook = hook;
442
+ delete record.entryLine;
443
+ if (late)
444
+ record.entryLate = true;
445
+ else
446
+ delete record.entryLate;
447
+ if (row.uuid)
448
+ record.entryUuid = row.uuid;
449
+ else
450
+ delete record.entryUuid;
451
+ if (row.shown !== undefined)
452
+ record.entryShown = row.shown;
453
+ else
454
+ delete record.entryShown;
455
+ if (record.id)
456
+ void this.locate(record).catch(() => undefined);
457
+ }
458
+ /** Phone messages whose row's line is being counted. */
459
+ locating = new Set();
460
+ /** Counts the line of the row the stream shows for a phone message's claimed entry, once, and keeps it.
461
+ * In the background: a long transcript is read from its start. */
462
+ async locate(record) {
463
+ const entry = record.entry, session = record.session;
464
+ if (entry === undefined || record.entryLine !== undefined || this.locating.has(record))
465
+ return;
466
+ this.locating.add(record);
467
+ try {
468
+ const line = await this.lineOf(record, record.entryShown ?? entry, record.entryUuid);
469
+ // Claimed again, or moved to another conversation, while the transcript was read: that answer is not this row's.
470
+ if (line === undefined || record.entry !== entry || record.session !== session)
471
+ return;
472
+ record.entryLine = line;
473
+ this.save();
474
+ }
475
+ finally {
476
+ this.locating.delete(record);
477
+ }
478
+ }
479
+ /** Marks `record` delivered, in `session` when given. */
480
+ settle(record, session) {
394
481
  record.state = "delivered";
395
482
  record.settledAt = this.now();
396
483
  delete record.reason;
@@ -401,10 +488,6 @@ export class PromptDeliveries {
401
488
  delete record.cursor;
402
489
  if (session)
403
490
  record.session = session;
404
- if (entry !== undefined)
405
- record.entry = entry;
406
- if (hook !== undefined)
407
- record.entryHook = hook;
408
491
  this.release(record, "delivered");
409
492
  }
410
493
  /** Whether the transcript shows the agent took `record`'s message, claiming the entry it settled with.
@@ -441,8 +524,7 @@ export class PromptDeliveries {
441
524
  && (entry.at === undefined || (entry.at >= other.at - ENTRY_SLACK_MS && entry.at <= (other.settledAt ?? other.at) + HOOK_ROW_MS)));
442
525
  if (!row)
443
526
  continue;
444
- other.entry = row.offset;
445
- other.entryHook = true;
527
+ this.claim(other, row, true);
446
528
  used.add(row.offset);
447
529
  claimedRows = true;
448
530
  }
@@ -469,14 +551,16 @@ export class PromptDeliveries {
469
551
  pass.set(key, free);
470
552
  if (entry === undefined)
471
553
  return false;
472
- record.entry = entry.offset;
473
- record.entryHook = entry.hook;
554
+ this.claim(record, entry);
474
555
  return true;
475
556
  }
476
557
  /** Whether a Codex transcript row can be `record`'s own: written after it was registered. A row at or past
477
558
  * 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. */
559
+ * which a row without a timestamp never is. A materialized Codex 0.155 thread's copy is append-only, so a row
560
+ * past the cursor was copied after registration, but not necessarily created after it: an older item the copy
561
+ * had not reached yet lands there too. Its rows are stamped with when the item was created (codex-threads.ts),
562
+ * and the scan drops any row stamped more than `ENTRY_SLACK_MS` before registration, which is what keeps an
563
+ * earlier identical message from being taken for this one. */
480
564
  static codexRowIsOwn(record, row) {
481
565
  return (record.cursor !== undefined && row.offset >= record.cursor) || (row.at !== undefined && row.at >= record.at);
482
566
  }
@@ -494,6 +578,29 @@ export class PromptDeliveries {
494
578
  return new Set(this.records.filter(other => other !== record && other.hash === record.hash && this.samePane(other, record)
495
579
  && other.session === record.session && other.entry !== undefined).map(other => other.entry));
496
580
  }
581
+ /** A Claude phone message its hook settled before its row was written takes the row once it appears: the first
582
+ * unclaimed user row with its words stamped from when it was typed to `HOOK_ROW_MS` after its hook, the rule
583
+ * `taken` applies to hook-settled messages. Only the receipt's `landed` depends on it. */
584
+ async claimClaudeRow(record) {
585
+ const session = record.session;
586
+ const rows = (await this.landed(record).catch(() => [])).filter(row => row.hook).sort((a, b) => a.offset - b.offset);
587
+ // Another path (`taken` for an identical message) may have given it its row meanwhile.
588
+ if (record.entry !== undefined) {
589
+ delete record.awaitingRow;
590
+ return;
591
+ }
592
+ if (!record.awaitingRow || record.session !== session)
593
+ return;
594
+ const used = new Set(this.records.filter(other => other !== record && other.hash === record.hash && this.samePane(other, record)
595
+ && other.session === record.session && other.entry !== undefined).map(other => other.entry));
596
+ const row = rows.find(row => !used.has(row.offset)
597
+ && (row.at === undefined || (row.at >= record.at - ENTRY_SLACK_MS && row.at <= (record.settledAt ?? record.at) + HOOK_ROW_MS)));
598
+ if (!row)
599
+ return;
600
+ this.claim(record, row, true, true);
601
+ delete record.awaitingRow;
602
+ this.save();
603
+ }
497
604
  /** A Codex message its hook settled takes the first free row written after it was registered. */
498
605
  async claimCodexRow(record) {
499
606
  const { rows, start } = await this.codexRows(record);
@@ -508,8 +615,7 @@ export class PromptDeliveries {
508
615
  const row = rows.find(row => !used.has(row.offset) && PromptDeliveries.codexRowIsOwn(record, row));
509
616
  if (!row)
510
617
  return;
511
- record.entry = row.offset;
512
- record.entryHook = row.hook;
618
+ this.claim(record, row);
513
619
  delete record.awaitingRow;
514
620
  this.save();
515
621
  }
@@ -528,8 +634,7 @@ export class PromptDeliveries {
528
634
  const row = rows.find(row => !used.has(row.offset) && PromptDeliveries.codexRowIsOwn(other, row));
529
635
  if (!row)
530
636
  continue;
531
- other.entry = row.offset;
532
- other.entryHook = row.hook;
637
+ this.claim(other, row);
533
638
  delete other.awaitingRow;
534
639
  used.add(row.offset);
535
640
  claimed = true;
@@ -540,8 +645,7 @@ export class PromptDeliveries {
540
645
  // The record may have settled (its hook came) while the transcript was read.
541
646
  if (!entry || !PromptDeliveries.claimable(record))
542
647
  return false;
543
- record.entry = entry.offset;
544
- record.entryHook = entry.hook;
648
+ this.claim(record, entry);
545
649
  return true;
546
650
  }
547
651
  /** A turn in `target`'s pane ended: the agent now takes held input or never will. */
@@ -570,13 +674,24 @@ export class PromptDeliveries {
570
674
  for (const record of this.records) {
571
675
  if (record.server !== server)
572
676
  continue;
573
- // A Codex message its hook settled claims its row once written, before a later identical one is checked.
677
+ // A message its hook settled claims its row once written (a Codex one before a later identical one is
678
+ // checked; a Claude phone message for its receipt's `landed`).
574
679
  if (record.awaitingRow) {
575
680
  if (now - (record.settledAt ?? record.at) > HOOK_ROW_MS)
576
681
  delete record.awaitingRow;
577
682
  else if (record.checkedAt === undefined || now - record.checkedAt >= LANDED_CHECK_MS) {
578
683
  record.checkedAt = now;
579
- await this.claimCodexRow(record);
684
+ await (record.source === "claude" ? this.claimClaudeRow(record) : this.claimCodexRow(record));
685
+ }
686
+ continue;
687
+ }
688
+ // A phone message's row whose line could not be counted yet (a Hook restart, a transcript being rewritten)
689
+ // is counted again for a few minutes after it settled.
690
+ if (record.id && record.state === "delivered" && record.entry !== undefined && record.entryLine === undefined
691
+ && now - (record.settledAt ?? record.at) <= LOCATE_FOR_MS) {
692
+ if (record.checkedAt === undefined || now - record.checkedAt >= LANDED_CHECK_MS) {
693
+ record.checkedAt = now;
694
+ void this.locate(record).catch(() => undefined);
580
695
  }
581
696
  continue;
582
697
  }
@@ -653,9 +768,22 @@ export function matchingOffsets(buffer, start, record) {
653
768
  let events = false;
654
769
  const lines = buffer.toString("utf8").split("\n");
655
770
  let offset = start + buffer.length;
771
+ // A materialized Codex thread writes input the agent holds in its queue as a `phrenQueued` row, and a content-free
772
+ // `phren_queue_consumed` row with the same key once the agent takes it. The scan runs newest first, so a queued
773
+ // row's marker, written after it, is seen before it: only a queued row whose marker came counts as taken.
774
+ const consumed = new Set();
656
775
  for (let index = lines.length - 1; index >= 0; index--) {
657
776
  const line = lines[index];
658
777
  offset -= Buffer.byteLength(line) + (index < lines.length - 1 ? 1 : 0);
778
+ if (line.includes('"phren_queue_consumed"')) {
779
+ try {
780
+ const marker = object(JSON.parse(line));
781
+ if (marker.type === "phren_queue_consumed" && typeof marker.key === "string")
782
+ consumed.add(marker.key);
783
+ }
784
+ catch { /* a cut line */ }
785
+ continue;
786
+ }
659
787
  // Only a row that can carry user text is parsed: the scan reads the whole tail now, not just its newest rows.
660
788
  if (!line.includes('"user') && !line.includes("queue-operation"))
661
789
  continue;
@@ -666,6 +794,8 @@ export function matchingOffsets(buffer, start, record) {
666
794
  catch {
667
795
  continue;
668
796
  }
797
+ if (row.phrenQueued === true && row.type === "response_item" && !(typeof row.phrenQueueKey === "string" && consumed.has(row.phrenQueueKey)))
798
+ continue;
669
799
  // Rows are not in time order: Claude writes a queued message's attachment rows, stamped when it was
670
800
  // typed, after the queue removal that took it. An older row is skipped, never the end of the scan,
671
801
  // or a message typed after an earlier queued one is never found (seen 2026-10-17: taken, reported failed).
@@ -677,9 +807,21 @@ export function matchingOffsets(buffer, start, record) {
677
807
  continue;
678
808
  // One entry per row, even when its content repeats the words.
679
809
  if (userTexts(row).some(text => promptHash(text) === record.hash))
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);
810
+ (item ? items : entries).push({ offset, hook: row.type === "user", ...(Number.isFinite(stamp) ? { at: stamp } : {}),
811
+ ...(typeof row.uuid === "string" && row.uuid && row.uuid.length <= 100 ? { uuid: row.uuid } : {}) });
812
+ }
813
+ if (!events)
814
+ return [...entries, ...items].sort((a, b) => b.offset - a.offset);
815
+ // The event is the turn, but the conversation stream shows the user item Codex wrote just before it (the event is
816
+ // not shown): each event names, as `shown`, the nearest earlier item with these words no later event took.
817
+ const taken = new Set();
818
+ return entries.map(entry => {
819
+ const item = items.filter(candidate => candidate.offset < entry.offset && !taken.has(candidate.offset)).sort((a, b) => b.offset - a.offset)[0];
820
+ if (!item)
821
+ return entry;
822
+ taken.add(item.offset);
823
+ return { ...entry, shown: item.offset };
824
+ });
683
825
  }
684
826
  export async function transcriptSize(record) {
685
827
  // A Codex 0.155 thread's copy is read as it stands: finding the transcript first appends what the thread store
@@ -691,7 +833,7 @@ export async function transcriptSize(record) {
691
833
  try {
692
834
  const file = await transcriptPath(record.source, record.session);
693
835
  // 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.
836
+ // so only a row stamped after registration (a user row with its creation time) can confirm it.
695
837
  return file === materializedPath(record.session) ? undefined : (await stat(file)).size;
696
838
  }
697
839
  catch (error) {
@@ -699,6 +841,42 @@ export async function transcriptSize(record) {
699
841
  return error instanceof BridgeError && object(error.details).code === "transcript-unavailable" ? 0 : undefined;
700
842
  }
701
843
  }
844
+ /** The 0-based line of the row starting at byte `offset`: the newlines before it, as the transcript index counts
845
+ * rows (transcript-index.ts), so it is the `line` the conversation stream gives that row. */
846
+ export async function transcriptLine(record, offset, uuid) {
847
+ const file = await open(await transcriptPath(record.source, record.session), "r");
848
+ try {
849
+ if ((await file.stat()).size <= offset)
850
+ return undefined;
851
+ // The file may have been replaced since the row was claimed (a copy made again): a row must still start at the
852
+ // offset, and be the claimed one when its id is known, or the count would name some other row.
853
+ const head = Buffer.alloc(Math.min(4_096, offset + 1));
854
+ const { bytesRead } = await file.read(head, 0, head.length, offset + 1 - head.length);
855
+ if (offset > 0 && head[bytesRead - 2] !== 10)
856
+ return undefined;
857
+ if (uuid) {
858
+ // Claude writes `uuid` after `message`, so the row is read whole, within a bound no typed message reaches.
859
+ const row = Buffer.alloc(2 * 1024 * 1024), read = (await file.read(row, 0, row.length, offset)).bytesRead;
860
+ const text = row.subarray(0, read).toString("utf8"), end = text.indexOf("\n");
861
+ if (!(end < 0 ? text : text.slice(0, end)).includes(`"uuid":"${uuid}"`))
862
+ return undefined;
863
+ }
864
+ const buffer = Buffer.alloc(65_536);
865
+ let line = 0, position = 0;
866
+ while (position < offset) {
867
+ const { bytesRead } = await file.read(buffer, 0, Math.min(buffer.length, offset - position), position);
868
+ if (!bytesRead)
869
+ return undefined;
870
+ for (let index = buffer.indexOf(10); index >= 0 && index < bytesRead; index = buffer.indexOf(10, index + 1))
871
+ line++;
872
+ position += bytesRead;
873
+ }
874
+ return line;
875
+ }
876
+ finally {
877
+ await file.close();
878
+ }
879
+ }
702
880
  async function transcriptEntries(record) {
703
881
  const file = await open(await transcriptPath(record.source, record.session), "r");
704
882
  try {
@@ -148,6 +148,8 @@ export declare const capabilities: {
148
148
  moveToComputer: boolean;
149
149
  moveConductorToComputer: boolean;
150
150
  moveResume: boolean;
151
+ moveSummaryByTarget: boolean;
152
+ moveConversationCopy: boolean;
151
153
  claudeAccountAdd: boolean;
152
154
  accountPools: boolean;
153
155
  workerRelocation: number;
@@ -158,6 +160,7 @@ export declare const capabilities: {
158
160
  memoryStoreBatch: boolean;
159
161
  gitHosts: boolean;
160
162
  projectHostToken: boolean;
163
+ gitRemoteIdentity: boolean;
161
164
  };
162
165
  export declare function capabilitiesForModules(snapshot: ModuleSnapshot): Record<string, unknown>;
163
166
  export declare function requireRoute(snapshot: ModuleSnapshot, method: string, route: string): void;
@@ -2,7 +2,7 @@ import { terminalProvider } from "./terminal.js";
2
2
  import { peerFingerprint } from "./dispatch-hosts.js";
3
3
  import { redactPeerHandoff } from "./peer-handoff.js";
4
4
  import { relocationSupport } from "./worker-relocation.js";
5
- import { continuationIntent, continuationLaunchSchema, continuationPlacement, launchContinuation } from "./continuation-launch.js";
5
+ import { CONVERSATION_FILE, CONVERSATION_MARKER, continuationConversationPage, continuationIntent, continuationLaunchSchema, continuationPlacement, fetchContinuationConversation, launchContinuation, withConversationPointer } from "./continuation-launch.js";
6
6
  import { addClaudeAccount, signInClaudeAccount } from "./account-add.js";
7
7
  import { ACCOUNT_ROLES, isAccountRole, setAccountSettings, setComputerAllowedPools } from "./account-pools.js";
8
8
  import { claudeHome } from "./claude-accounts.js";
@@ -16,6 +16,7 @@ import { reportWorker, readIntegrator, setIntegrator } from "./worker-reports.js
16
16
  import { sessionStalls } from "./stalls.js";
17
17
  import { harnessInventoryWithin, launchCheckOff } from "./harnesses.js";
18
18
  import path from "node:path";
19
+ import { stat } from "node:fs/promises";
19
20
  import { z } from "zod";
20
21
  import { sudoAnswer } from "./sudo.js";
21
22
  import { saveCodeNote } from "./code-note.js";
@@ -26,7 +27,7 @@ import { resolveCodeStore, CodeRoutes } from "./code-routes.js";
26
27
  import { dispatchProjectDirectory, dispatchStatus, originPaneSchema } from "./dispatch.js";
27
28
  import { hookWorkers } from "./dispatch-returns.js";
28
29
  import { remoteChildren } from "./dispatch-tree.js";
29
- import { briefArrival, briefId, readLaunchBrief } from "./launch-brief.js";
30
+ import { briefArrival, briefId, briefRoot, launchesWithBrief, readLaunchBrief } from "./launch-brief.js";
30
31
  import { listApprovalRules, changeApprovalRule } from "./approval-rules.js";
31
32
  import { addGrant, listGrants, listNamedGrants, removeGrant } from "./grants.js";
32
33
  import { clearProjectAuthority, confirmAuthority, listConfirmations, projectAuthority, readAuthority, setProjectAuthority } from "./authority.js";
@@ -44,7 +45,7 @@ import { paneAccountField, paneChatState, panes, rpc, servers, snapshot, validat
44
45
  import { locateProject } from "./locate.js";
45
46
  import { gitStatus } from "./git.js";
46
47
  import { gitRoot, launchDirectory, repositoryBranch, webServers, withGitReadDeadline } from "./projects.js";
47
- import { approvalDecisions, BridgeError, bridgeRoot, MAX_FRAME, object, objects, PROTOCOL, provider, serverName, targetFromURL, targetSchema } from "./protocol.js";
48
+ import { approvalDecisions, atomicInPrivateDir, BridgeError, bridgeRoot, MAX_FRAME, object, objects, PROTOCOL, provider, serverName, targetFromURL, targetSchema } from "./protocol.js";
48
49
  import { bootedSimulators, simulatorAct, simulatorApps, simulatorDevices, simulatorScreenshot } from "./simulators.js";
49
50
  import { childAgentTree, historicalImage, publicChildAgents, refreshTranscript, runningChildAgents, targetTranscriptPath } from "./transcripts.js";
50
51
  import { listUploads, removeUpload, saveUpload, uploadImage } from "./uploads.js";
@@ -91,7 +92,7 @@ async function childActivity(source, session) {
91
92
  export const capabilities = { transcript: true, progress: true, images: true, prompt: true, stop: true,
92
93
  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,
93
94
  approvals: true, questions: false, accountUsage: true, providers: ["codex", "claude", "copilot", "opencode"],
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 };
95
+ 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, moveSummaryByTarget: true, moveConversationCopy: true, claudeAccountAdd: true, accountPools: true, workerRelocation: 1, projectMemory: true, fileWrite: true, fileSearch: true, gitReview: true, memoryStoreBatch: true, gitHosts: true, projectHostToken: true, gitRemoteIdentity: true };
95
96
  export function capabilitiesForModules(snapshot) {
96
97
  const allowed = new Set(snapshot.modules.flatMap(module => module.capabilities));
97
98
  const result = Object.fromEntries(Object.entries(capabilities).filter(([name]) => allowed.has(name)));
@@ -331,11 +332,13 @@ async function moveDestination(move, caller) {
331
332
  if (!peer || object((await peerRequest(peer, "/v1/health", undefined, 5_000)).computer).id !== move.computerId)
332
333
  throw new BridgeError(403, "The move destination's enrollment changed.");
333
334
  }
334
- async function peerContinuationIntent(caller, id) {
335
+ /** Destinations whose enrollment was checked for a move's conversation pages, until when. */
336
+ const verifiedPages = new Map();
337
+ async function peerContinuationIntent(caller, id, conversation) {
335
338
  const candidates = (await hookPeers()).filter(peer => peerFingerprint(peer) === caller.fingerprint && (!caller.name || caller.name === peer.name));
336
339
  if (candidates.length !== 1)
337
340
  throw new BridgeError(403, "The launch origin is not uniquely verified.");
338
- return peerRequest(candidates[0], `/v1/sessions/move/intent?id=${z.string().uuid().parse(id)}`, undefined, 5_000);
341
+ return peerRequest(candidates[0], `/v1/sessions/move/intent?id=${z.string().uuid().parse(id)}${conversation === undefined ? "" : `&conversation=${conversation}`}`, undefined, 5_000);
339
342
  }
340
343
  export function createRouteHandler(ctx) {
341
344
  const { version, modules, info, computerID, scheduleStore, scheduler, dispatches, agentHooks, journal, modelCatalog, accountUsage, resources, launches, locatedDirectories, fanoutMessages, canary } = ctx;
@@ -469,8 +472,19 @@ export function createRouteHandler(ctx) {
469
472
  const caller = requestPeer(request), move = await readMove(id);
470
473
  if (!move || move.state === "failed")
471
474
  throw new BridgeError(403, "This continuation intent is no longer authorized.");
472
- await moveDestination(move, caller);
473
- result = await continuationIntent(id);
475
+ // `conversation=<offset>`: a page of the conversation a summary-by-target move copies (continuation-launch.ts).
476
+ // The destination's enrollment is checked again (one SSH call back to it) at most once a minute while it pages.
477
+ const page = url.searchParams.get("conversation");
478
+ const verifiedKey = JSON.stringify([id, caller?.fingerprint, caller?.name, caller?.id]);
479
+ if (page === null || (verifiedPages.get(verifiedKey) ?? 0) <= Date.now()) {
480
+ await moveDestination(move, caller);
481
+ if (page !== null) {
482
+ verifiedPages.set(verifiedKey, Date.now() + 60_000);
483
+ if (verifiedPages.size > 64)
484
+ verifiedPages.delete(verifiedPages.keys().next().value);
485
+ }
486
+ }
487
+ result = page === null ? await continuationIntent(id) : await continuationConversationPage(id, z.coerce.number().int().nonnegative().parse(page));
474
488
  break;
475
489
  }
476
490
  case "/v1/sessions/move/launch": {
@@ -1008,7 +1022,17 @@ export function createRouteHandler(ctx) {
1008
1022
  const role = await (await import("./conductor-role.js")).readRoleState();
1009
1023
  const prepared = role?.succession?.side === "successor" && role.succession.id === input.brief.id && role.succession.phase !== "aborted";
1010
1024
  const cwd = prepared ? defaultPhrenPath() : await dispatchProjectDirectory(input.project);
1011
- return launchSession(selectedServer(url), { cwd, kind: input.to.harness, account: input.to.account, model: input.to.model, effort: input.to.effort, label: `move-${input.brief.id}`, brief: input.brief }, { trustFolder: true, onPlaced: async (target) => {
1025
+ // A summary-by-target move's whole conversation, from the source Hook that admitted it; none from an older one.
1026
+ // Asked for only for those moves (the brief is the source's own, checked against its intent above), and only
1027
+ // for a harness launched with a brief file: its folder is where the copy goes and the brief carries the line.
1028
+ const wantsCopy = !!caller && input.brief.text.includes(CONVERSATION_MARKER) && launchesWithBrief(input.to.harness);
1029
+ const conversation = wantsCopy ? await fetchContinuationConversation(offset => peerContinuationIntent(caller, input.brief.id, offset), redactPeerHandoff) : undefined;
1030
+ const copied = conversation ? path.join(briefRoot(), input.brief.id, CONVERSATION_FILE) : undefined;
1031
+ const brief = copied ? { ...input.brief, text: withConversationPointer(input.brief.text, copied) } : input.brief;
1032
+ return launchSession(selectedServer(url), { cwd, kind: input.to.harness, account: input.to.account, model: input.to.model, effort: input.to.effort, label: `move-${input.brief.id}`, brief }, { trustFolder: true, onPlaced: async (target) => {
1033
+ // Into the brief folder, which the new agent may read (Claude's --add-dir), as soon as it exists.
1034
+ if (copied && conversation && await stat(path.dirname(copied)).catch(() => undefined))
1035
+ await atomicInPrivateDir(copied, conversation).catch(() => undefined);
1012
1036
  await onPlaced(target);
1013
1037
  await terminalProvider().renamePane(selectedServer(url), z.string().parse(target.pane), input.label).catch(() => undefined);
1014
1038
  } });
@@ -221,11 +221,13 @@ export function transcriptStreams(ctx) {
221
221
  if (deliveryFrames) {
222
222
  // Every message typed into this pane, also those sent while an
223
223
  // earlier conversation was showing there.
224
- for (const { deliveryId, state, reason } of agentHooks.deliveries.forPane(target)) {
225
- if (sentDelivery.get(deliveryId) === state)
224
+ // A delivered message is sent again once the row it landed as is known (`landed`).
225
+ for (const { deliveryId, state, reason, landed } of agentHooks.deliveries.forPane(target)) {
226
+ const key = landed ? `${state}:${landed.line}` : state;
227
+ if (sentDelivery.get(deliveryId) === key)
226
228
  continue;
227
- sentDelivery.set(deliveryId, state);
228
- send(client, { type: "delivery", ...conversation, deliveryId, state, ...(reason ? { reason } : {}) });
229
+ sentDelivery.set(deliveryId, key);
230
+ send(client, { type: "delivery", ...conversation, deliveryId, state, ...(reason ? { reason } : {}), ...(landed ? { landed } : {}) });
229
231
  }
230
232
  }
231
233
  first = false;
@@ -331,6 +331,12 @@ export declare function fallbackHandoff(input: {
331
331
  /** Whether a Claude conversation's last turn ended on its subscription's usage limit (Claude's own
332
332
  * rate-limit row): its agent cannot answer a hand-off request. */
333
333
  export declare function sourceOutOfUsage(lines: readonly string[], source: Provider): boolean;
334
+ /**
335
+ * The whole conversation a summary-by-target move copies to the other computer: every prompt and reply, oldest
336
+ * first, each as it is sent (`prepare`: paths replaced, credentials redacted), within `CONVERSATION_LIMIT`.
337
+ * A longer one keeps its newest messages and says how many it left out.
338
+ */
339
+ export declare function conversationCopy(entries: readonly TailEntry[], prepare: (text: string) => string, limit?: number, complete?: boolean): string;
334
340
  /**
335
341
  * The hand-off for a source that does not write one (its account is out of usage, or the owner asked), for a
336
342
  * fresh agent on the target computer to build itself: what happened, then as much of the conversation as fits
@@ -374,6 +380,11 @@ export interface MoverDeps {
374
380
  inventory: () => Promise<HarnessInventory | undefined>;
375
381
  /** The conversation's transcript lines, its tail is enough. */
376
382
  transcript: (target: Target) => Promise<string[]>;
383
+ /** The whole transcript for a summary-by-target move's copy, and whether all of it was read. */
384
+ conversation?: (target: Target) => Promise<{
385
+ lines: string[];
386
+ complete: boolean;
387
+ }>;
377
388
  /** Copies a Claude conversation into another account's home (`copyClaudeConversation` over its transcript).
378
389
  * With `check`, only resolves and validates both ends, so a move is refused before the old agent exits. */
379
390
  copyConversation?: (target: Target, to: ClaudeHome, check?: boolean) => Promise<string>;