@phren/cli 0.3.67 → 0.3.69

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 (83) hide show
  1. package/dist/bridge/agent-hook-callback.js +11 -2
  2. package/dist/bridge/agent-hooks.d.ts +11 -1
  3. package/dist/bridge/agent-hooks.js +259 -40
  4. package/dist/bridge/changes.d.ts +2 -2
  5. package/dist/bridge/changes.js +11 -9
  6. package/dist/bridge/checkpoints.d.ts +24 -0
  7. package/dist/bridge/checkpoints.js +423 -0
  8. package/dist/bridge/claude-input-state.d.ts +14 -0
  9. package/dist/bridge/claude-input-state.js +58 -0
  10. package/dist/bridge/claude-queue.js +5 -2
  11. package/dist/bridge/claude-suggestion.d.ts +3 -0
  12. package/dist/bridge/claude-suggestion.js +10 -0
  13. package/dist/bridge/codex-threads.d.ts +7 -1
  14. package/dist/bridge/codex-threads.js +185 -56
  15. package/dist/bridge/conversation-search.d.ts +20 -0
  16. package/dist/bridge/conversation-search.js +928 -0
  17. package/dist/bridge/git-watch.d.ts +46 -0
  18. package/dist/bridge/git-watch.js +351 -0
  19. package/dist/bridge/git-worktree-remove.d.ts +44 -0
  20. package/dist/bridge/git-worktree-remove.js +140 -0
  21. package/dist/bridge/git-worktrees.d.ts +14 -0
  22. package/dist/bridge/git-worktrees.js +7 -3
  23. package/dist/bridge/git-write-policy.js +1 -1
  24. package/dist/bridge/gitboy-webhooks.d.ts +3 -1
  25. package/dist/bridge/gitboy-webhooks.js +26 -2
  26. package/dist/bridge/herdr.d.ts +6 -1
  27. package/dist/bridge/herdr.js +56 -10
  28. package/dist/bridge/hook-fast.js +13 -1
  29. package/dist/bridge/input-classification.d.ts +33 -0
  30. package/dist/bridge/input-classification.js +84 -0
  31. package/dist/bridge/pane-status.d.ts +3 -3
  32. package/dist/bridge/pane-status.js +16 -8
  33. package/dist/bridge/prompt-deliveries.d.ts +30 -4
  34. package/dist/bridge/prompt-deliveries.js +365 -13
  35. package/dist/bridge/prompt-identity.d.ts +8 -0
  36. package/dist/bridge/prompt-identity.js +15 -0
  37. package/dist/bridge/request-origin.js +2 -1
  38. package/dist/bridge/schedule-events.d.ts +17 -0
  39. package/dist/bridge/schedule-events.js +53 -0
  40. package/dist/bridge/schedule-format.d.ts +22 -2
  41. package/dist/bridge/schedule-format.js +40 -5
  42. package/dist/bridge/schedule-update.js +2 -1
  43. package/dist/bridge/schedule-watch.js +15 -5
  44. package/dist/bridge/schedules.d.ts +9 -0
  45. package/dist/bridge/schedules.js +120 -7
  46. package/dist/bridge/server-pane-routes.d.ts +7 -8
  47. package/dist/bridge/server-pane-routes.js +186 -82
  48. package/dist/bridge/server-routes.d.ts +26 -2
  49. package/dist/bridge/server-routes.js +180 -56
  50. package/dist/bridge/server-stream.js +66 -15
  51. package/dist/bridge/server.js +25 -7
  52. package/dist/bridge/session-activity.d.ts +49 -4
  53. package/dist/bridge/session-activity.js +47 -0
  54. package/dist/bridge/session-evidence.d.ts +18 -0
  55. package/dist/bridge/session-evidence.js +72 -0
  56. package/dist/bridge/session-seen.d.ts +23 -0
  57. package/dist/bridge/session-seen.js +69 -0
  58. package/dist/bridge/tab-activity.d.ts +26 -1
  59. package/dist/bridge/tab-activity.js +64 -9
  60. package/dist/bridge/terminal-resolve.d.ts +20 -0
  61. package/dist/bridge/terminal-resolve.js +145 -0
  62. package/dist/bridge/terminal-tmux.d.ts +8 -3
  63. package/dist/bridge/terminal-tmux.js +59 -7
  64. package/dist/bridge/transcript-claude.d.ts +12 -2
  65. package/dist/bridge/transcript-claude.js +91 -13
  66. package/dist/bridge/transcript-index.d.ts +4 -2
  67. package/dist/bridge/transcript-index.js +6 -5
  68. package/dist/bridge/transcript-preview.d.ts +16 -1
  69. package/dist/bridge/transcript-preview.js +171 -27
  70. package/dist/bridge/transcripts.d.ts +41 -1
  71. package/dist/bridge/transcripts.js +181 -23
  72. package/dist/bridge/turn-queue-pane.d.ts +6 -0
  73. package/dist/bridge/turn-queue-pane.js +30 -0
  74. package/dist/bridge/turn-queue.d.ts +86 -0
  75. package/dist/bridge/turn-queue.js +280 -0
  76. package/dist/bridge/turn-records.d.ts +18 -0
  77. package/dist/bridge/turn-records.js +77 -5
  78. package/dist/bridge-hook.mjs +7074 -3173
  79. package/dist/cli/config-shared.js +2 -1
  80. package/dist/cli/schedules.js +6 -1
  81. package/dist/content/secrets.js +1 -1
  82. package/dist/modules/registry.js +12 -11
  83. package/package.json +1 -1
@@ -56,13 +56,18 @@ const recordSchema = z.object({
56
56
  /** From a joined prompt (`settleJoined`): "part", a message settled inside it, claims no row of its own (the turn's
57
57
  * row carries other words); "turn", the joined words themselves, no message of anyone's, claims that row. */
58
58
  joined: z.enum(["part", "turn"]).optional(),
59
- /** Codex: the transcript's size in bytes when the message was registered. Only a row at or past it is
59
+ /** Claude/Codex: the transcript's size in bytes when the message was registered. Only a row at or past it is
60
60
  * the message's own: position, not the clock, orders rows, and a row without a timestamp too. */
61
61
  cursor: z.number().int().nonnegative().optional(),
62
62
  }).strict();
63
63
  const landedFile = (file) => `${file}.landed.json`;
64
64
  const landedSchema = z.object({ line: z.number().int().nonnegative().optional(), uuid: z.string().min(1).max(100).optional(),
65
65
  shown: z.number().int().nonnegative().optional(), late: z.literal(true).optional() }).strict();
66
+ const queueBindingsFile = (file) => `${file}.queue.json`;
67
+ const queueBindingSchema = z.object({ offset: z.number().int().nonnegative().optional(), at: z.number().optional(),
68
+ key: z.string().regex(/^[0-9a-f]{64}$/).optional(), end: z.enum(["consumed", "returned"]).optional(),
69
+ remove: z.number().int().nonnegative().optional(), user: z.number().int().nonnegative().optional(),
70
+ dequeue: z.number().int().nonnegative().optional() }).strict();
66
71
  /** One message per record, bound to the pane it was typed into (server, pane,
67
72
  * agent kind), not to the conversation: a Codex thread or a Claude /clear can
68
73
  * replace the conversation while the agent still holds the typed text, and
@@ -84,7 +89,9 @@ export class PromptDeliveries {
84
89
  static open(record) { return record.state === "typed" || record.state === "queued"; }
85
90
  /** Open, or failed with its own hook's claim still waiting for its row (a late delivery). */
86
91
  static claimable(record) { return PromptDeliveries.open(record) || (record.state === "failed" && !!record.hookClaim); }
87
- /** Codex messages whose `cursor` is still being read. */
92
+ /** The queue bindings last read from each Claude conversation, and the transcript revision they describe. */
93
+ queueCache = new Map();
94
+ /** Messages whose `cursor` is still being read. */
88
95
  cursors = new Map();
89
96
  /** The size of a conversation's transcript: 0 before it has one, undefined when it cannot be read. */
90
97
  size;
@@ -126,6 +133,30 @@ export class PromptDeliveries {
126
133
  }
127
134
  }
128
135
  catch { /* None yet: rows found before this version, or none. */ }
136
+ try {
137
+ // The queue occurrence each phone message was bound to, apart from the records an older Hook
138
+ // reads strictly. Keyed by phone id, so a record it no longer keeps is simply not found.
139
+ for (const [id, row] of Object.entries(object(JSON.parse(readFileSync(queueBindingsFile(file), "utf8"))))) {
140
+ const parsed = queueBindingSchema.safeParse(row), record = this.byId(id);
141
+ if (!parsed.success || !record)
142
+ continue;
143
+ if (parsed.data.offset !== undefined)
144
+ record.queueOffset = parsed.data.offset;
145
+ if (parsed.data.at !== undefined)
146
+ record.queueAt = parsed.data.at;
147
+ if (parsed.data.key !== undefined)
148
+ record.queueKey = parsed.data.key;
149
+ if (parsed.data.end !== undefined)
150
+ record.queueEnd = parsed.data.end;
151
+ if (parsed.data.remove !== undefined)
152
+ record.queueRemoveOffset = parsed.data.remove;
153
+ if (parsed.data.user !== undefined)
154
+ record.queueUserOffset = parsed.data.user;
155
+ if (parsed.data.dequeue !== undefined)
156
+ record.queueDequeueOffset = parsed.data.dequeue;
157
+ }
158
+ }
159
+ catch { /* None yet: no message of this Hook's has been bound to a queue row. */ }
129
160
  this.prune();
130
161
  }
131
162
  samePane(record, target) {
@@ -137,13 +168,15 @@ export class PromptDeliveries {
137
168
  this.records = this.records.filter(record => record.at >= cutoff || this.waiters.has(record));
138
169
  while (this.records.length > MAX_RECORDS)
139
170
  this.records.shift();
171
+ while (this.queueCache.size > 64)
172
+ this.queueCache.delete(this.queueCache.keys().next().value);
140
173
  }
141
174
  save() {
142
175
  if (!this.file)
143
176
  return;
144
177
  // 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.
145
178
  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);
179
+ const rows = kept.map(({ idleSince: _, checkedAt: __, hookClaim: ___, seenRow: ____, awaitingRow: _____, entryLate: _a, entryLine: _b, entryUuid: _c, entryShown: _d, queueOffset: _e, queueAt: _f, queueRemoveOffset: _g, queueUserOffset: _h, queueDequeueOffset: _i, queueKey: _j, queueEnd: _k, ...row }) => row);
147
180
  // The rows phone messages landed as, apart from the records an older Hook reads strictly.
148
181
  const landed = {};
149
182
  for (const record of kept)
@@ -151,8 +184,22 @@ export class PromptDeliveries {
151
184
  landed[record.id] = { ...(record.entryLine !== undefined ? { line: record.entryLine } : {}), ...(record.entryUuid ? { uuid: record.entryUuid } : {}),
152
185
  ...(record.entryShown !== undefined ? { shown: record.entryShown } : {}), ...(record.entryLate ? { late: true } : {}) };
153
186
  }
187
+ // The Claude queue occurrence each phone message was typed as, beside the records for the same reason.
188
+ const queue = {};
189
+ for (const record of kept)
190
+ if (record.id && (record.queueOffset !== undefined || record.queueRemoveOffset !== undefined)) {
191
+ queue[record.id] = { ...(record.queueOffset !== undefined ? { offset: record.queueOffset } : {}), ...(record.queueAt !== undefined ? { at: record.queueAt } : {}),
192
+ ...(record.queueKey !== undefined ? { key: record.queueKey } : {}), ...(record.queueEnd !== undefined ? { end: record.queueEnd } : {}),
193
+ ...(record.queueRemoveOffset !== undefined ? { remove: record.queueRemoveOffset } : {}),
194
+ ...(record.queueUserOffset !== undefined ? { user: record.queueUserOffset } : {}),
195
+ ...(record.queueDequeueOffset !== undefined ? { dequeue: record.queueDequeueOffset } : {}) };
196
+ }
154
197
  const file = this.file;
155
- this.writing = this.writing.then(async () => { await atomicInPrivateDir(file, { records: rows }); await atomicInPrivateDir(landedFile(file), landed); }).catch(() => undefined);
198
+ this.writing = this.writing.then(async () => {
199
+ await atomicInPrivateDir(file, { records: rows });
200
+ await atomicInPrivateDir(landedFile(file), landed);
201
+ await atomicInPrivateDir(queueBindingsFile(file), queue);
202
+ }).catch(() => undefined);
156
203
  }
157
204
  /** Settled writes, for tests and an orderly shutdown. */
158
205
  flush() { return this.writing; }
@@ -173,7 +220,10 @@ export class PromptDeliveries {
173
220
  this.save();
174
221
  // Started before the caller types the message (a stat, against typing, then the agent's own write), so
175
222
  // the row it makes lands past the cursor; a row stamped after registration counts too (`codexRowIsOwn`).
176
- if (record.source === "codex") {
223
+ if (record.source === "codex" || record.source === "claude") {
224
+ // The cursor is this conversation's size before anything is typed. A queued row (an
225
+ // enqueue, or a removal whose enqueue scrolled out of the tail) must start at or past
226
+ // it to be this message's; an identical row already there is an earlier turn's.
177
227
  const session = record.session;
178
228
  this.cursors.set(record, this.size(record).then(size => { if (size !== undefined && record.session === session) {
179
229
  record.cursor = size;
@@ -211,13 +261,19 @@ export class PromptDeliveries {
211
261
  return this.records.find(record => record.hash === hash && this.samePane(record, target) && (record.state === "typed" || record.state === "queued"));
212
262
  }
213
263
  /** A message Phren typed into `target`'s pane that no conversation there has submitted yet. */
214
- pending(target, text) { return !!this.open(target, text); }
264
+ pending(target, text, id) {
265
+ if (!id)
266
+ return !!this.open(target, text);
267
+ const record = this.find(id, target);
268
+ return !!record && PromptDeliveries.open(record) && record.session === target.session && record.hash === promptHash(text);
269
+ }
215
270
  /** Whether `record` still holds its pane: open, and either young or in a pane whose hooks will settle it. */
216
271
  inFlight(record) {
217
272
  return PromptDeliveries.open(record) && (this.now() - record.at < IN_FLIGHT_MS || this.hookPanes.has(this.paneKey(record)));
218
273
  }
219
- /** Whether any message typed into `target`'s pane is still waiting to be taken or refused. */
220
- holding(target) { return this.records.some(record => this.samePane(record, target) && this.inFlight(record)); }
274
+ /** Whether any message typed into `target`'s pane is still waiting to be taken or refused.
275
+ * A pre-typing guard can exclude only its own freshly registered reservation by id. */
276
+ holding(target, exceptId) { return this.records.some(record => (exceptId === undefined || record.id !== exceptId) && this.samePane(record, target) && this.inFlight(record)); }
221
277
  /** Whether phone message `id` may still be taken: held by the agent, and in flight as `holding` counts it. */
222
278
  held(id, target) { const record = this.find(id, target); return !!record && this.inFlight(record); }
223
279
  /** Wait again for a message `expect` reported pending, after a second Enter. */
@@ -302,6 +358,233 @@ export class PromptDeliveries {
302
358
  return this.records.filter(record => record.id && this.samePane(record, target)).map(record => ({ deliveryId: record.id, ...this.status(record.id, target) }))
303
359
  .filter(item => item.state !== "unknown");
304
360
  }
361
+ /** The phone delivery each of a Claude conversation's queue rows belongs to, by byte offset: the
362
+ * enqueue a message was typed as, the `remove`/`popAll` that took it back, the prompt turn that
363
+ * delivered it, and the `dequeue` that handed it to the model. Reads the transcript tail, binds
364
+ * any occurrence not bound yet, and keeps the binding in `<file>.queue.json`, so a reopened chat,
365
+ * a reconnect snapshot or a Hook restart gives the same row the same phone id. */
366
+ async claudeQueueBindings(target, file) {
367
+ if (target.source !== "claude")
368
+ return undefined;
369
+ const signature = () => this.records.filter(record => record.id && this.samePane(record, target) && record.session === target.session)
370
+ .map(record => `${record.id}:${record.queueKey ?? ""}:${record.queueEnd ?? ""}:${record.cursor ?? ""}:${record.entry ?? ""}:${record.queueOffset ?? ""}:${record.queueRemoveOffset ?? ""}:${record.queueUserOffset ?? ""}:${record.queueDequeueOffset ?? ""}`).join(",");
371
+ if (!signature())
372
+ return undefined;
373
+ let info;
374
+ try {
375
+ info = await stat(file);
376
+ }
377
+ catch {
378
+ return undefined;
379
+ }
380
+ const key = `${this.paneKey(target)}\0${target.session}\0${file}`, before = signature();
381
+ const cached = this.queueCache.get(key);
382
+ if (cached && cached.size === info.size && cached.mtimeMs === info.mtimeMs && cached.signature === before)
383
+ return cached.bindings;
384
+ const rows = await claudeQueueRows(file);
385
+ const bindings = await this.bindClaudeQueueRows(target, rows);
386
+ this.queueCache.set(key, { signature: signature(), size: info.size, mtimeMs: info.mtimeMs, bindings });
387
+ return bindings;
388
+ }
389
+ /** Bind parsed Claude queue rows (with their byte offsets) to the phone messages tracked in
390
+ * `target`, oldest occurrence first, per pane and conversation. A message binds at most one
391
+ * enqueue, one removal, one submitted turn and one dequeue; a repeated identical enqueue takes
392
+ * the next unbound message, never the same occurrence twice. Only rows after the cursor captured
393
+ * before the send was typed can be its own, so an earlier identical turn keeps its own identity.
394
+ * Only bindings are recorded here: an enqueue is still held, never taken, and a cancellation or
395
+ * `popAll` is not a delivery. */
396
+ async bindClaudeQueueRows(target, rows) {
397
+ const bindings = new Map();
398
+ const relevant = this.records.filter(record => record.id && this.samePane(record, target) && record.session === target.session);
399
+ if (target.source !== "claude" || !relevant.length)
400
+ return bindings;
401
+ // A Claude cursor is this conversation's size when the message was registered. Wait for it
402
+ // before deciding which occurrence is new: a row already in the transcript is an earlier turn's.
403
+ await Promise.all(relevant.map(record => this.cursors.get(record)).filter((promise) => !!promise));
404
+ let changed = false;
405
+ const ordered = [...rows].sort((a, b) => a.offset - b.offset);
406
+ const byOffset = new Map(ordered.map(({ offset, raw }) => [offset, raw]));
407
+ const queueKey = (content) => createHash("sha256").update(unwrapPastedContent(content)).digest("hex");
408
+ const consumed = (row) => row.operation === "remove" && (row.reason === "absorbed_mid_turn" || row.reason === "delivered_to_agent");
409
+ const canReplace = (record, offset) => (record.queueEnd !== "returned" && (record.queueRemoveOffset === undefined || record.queueEnd === "consumed"))
410
+ || (record.entryHook === true && record.entry === offset);
411
+ const eligible = (row) => row === undefined || (row.isSidechain !== true && row.isMeta !== true
412
+ && (typeof row.sessionId !== "string" || row.sessionId === target.session));
413
+ const exclusive = (record, offset) => !this.records.some(other => other !== record && this.samePane(other, target)
414
+ && other.session === target.session && (other.queueUserOffset === offset || other.entry === offset));
415
+ // Reconstruct every association already recorded, validating a row still at that offset and,
416
+ // for the submitted turn, that it follows the enqueue. An append or restart must not lose it.
417
+ for (const record of relevant) {
418
+ if (record.queueOffset !== undefined) {
419
+ const row = byOffset.get(record.queueOffset);
420
+ const still = eligible(row) && (row === undefined || (row.type === "queue-operation" && row.operation === "enqueue"
421
+ && typeof row.content === "string" && promptHash(row.content) === record.hash
422
+ && (record.queueKey === undefined || queueKey(row.content) === record.queueKey)
423
+ && (record.cursor === undefined || record.queueOffset >= record.cursor)));
424
+ if (still) {
425
+ bindings.set(record.queueOffset, record.id);
426
+ if (row && record.queueKey === undefined) {
427
+ record.queueKey = queueKey(String(row.content));
428
+ changed = true;
429
+ }
430
+ }
431
+ else {
432
+ delete record.queueOffset;
433
+ delete record.queueAt;
434
+ delete record.queueKey;
435
+ delete record.queueEnd;
436
+ delete record.queueRemoveOffset;
437
+ delete record.queueUserOffset;
438
+ delete record.queueDequeueOffset;
439
+ changed = true;
440
+ }
441
+ }
442
+ if (record.queueRemoveOffset !== undefined) {
443
+ const row = byOffset.get(record.queueRemoveOffset);
444
+ const still = eligible(row) && (row === undefined || (row.type === "queue-operation" && (row.operation === "remove" || row.operation === "popAll")
445
+ && typeof row.content === "string" && (record.queueKey === undefined || queueKey(row.content) === record.queueKey)
446
+ && (record.cursor === undefined || record.queueRemoveOffset >= record.cursor)));
447
+ if (still) {
448
+ bindings.set(record.queueRemoveOffset, record.id);
449
+ if (row) {
450
+ const end = consumed(row) ? "consumed" : "returned";
451
+ if (record.queueEnd !== end) {
452
+ record.queueEnd = end;
453
+ changed = true;
454
+ }
455
+ }
456
+ }
457
+ else {
458
+ delete record.queueRemoveOffset;
459
+ if (record.queueDequeueOffset === undefined)
460
+ delete record.queueEnd;
461
+ changed = true;
462
+ }
463
+ }
464
+ if (record.queueUserOffset !== undefined) {
465
+ const row = byOffset.get(record.queueUserOffset);
466
+ const text = row === undefined ? undefined : claudeUserText(row);
467
+ const still = eligible(row) && canReplace(record, record.queueUserOffset) && exclusive(record, record.queueUserOffset)
468
+ && (!record.entryHook || record.entry === undefined || record.entry === record.queueUserOffset)
469
+ && (row === undefined || (text !== undefined && promptHash(text) === record.hash
470
+ && record.queueOffset !== undefined && record.queueUserOffset > record.queueOffset));
471
+ if (still)
472
+ bindings.set(record.queueUserOffset, record.id);
473
+ else {
474
+ delete record.queueUserOffset;
475
+ changed = true;
476
+ }
477
+ }
478
+ if (record.queueDequeueOffset !== undefined) {
479
+ const row = byOffset.get(record.queueDequeueOffset);
480
+ const still = eligible(row) && (row === undefined || (row.type === "queue-operation" && row.operation === "dequeue" && row.isSidechain !== true));
481
+ if (still)
482
+ bindings.set(record.queueDequeueOffset, record.id);
483
+ else {
484
+ delete record.queueDequeueOffset;
485
+ changed = true;
486
+ }
487
+ }
488
+ }
489
+ // Replay every occurrence, including unowned messages: an ordinary queue head must
490
+ // consume its own dequeue rather than handing it to a later phone send.
491
+ const pending = [];
492
+ for (const { offset, raw } of ordered) {
493
+ if (raw.isSidechain === true || (typeof raw.sessionId === "string" && raw.sessionId !== target.session))
494
+ continue;
495
+ if (raw.type === "queue-operation" && raw.isSidechain !== true) {
496
+ // A content-free dequeue is the queue head handed to a turn. Its own line names the
497
+ // occurrence even when a page does not also carry the prompt turn it delivered.
498
+ if (raw.operation === "dequeue") {
499
+ const head = pending.shift();
500
+ const record = head && relevant.find(candidate => candidate.queueOffset === head.offset);
501
+ if (record && record.queueDequeueOffset === undefined && !bindings.has(offset)) {
502
+ record.queueDequeueOffset = offset;
503
+ record.queueEnd = "consumed";
504
+ bindings.set(offset, record.id);
505
+ changed = true;
506
+ }
507
+ continue;
508
+ }
509
+ if (typeof raw.content !== "string")
510
+ continue;
511
+ const hash = promptHash(raw.content), key = queueKey(raw.content);
512
+ // Private harness entries still occupy the queue. Count them for FIFO without
513
+ // ever binding their payload to a phone message.
514
+ if (raw.operation === "enqueue")
515
+ pending.push({ offset, key });
516
+ const index = raw.operation === "remove" || raw.operation === "popAll" ? pending.findIndex(item => item.key === key) : -1;
517
+ const occurrence = index < 0 ? undefined : pending.splice(index, 1)[0];
518
+ const unwrapped = unwrapPastedContent(raw.content);
519
+ if (raw.isMeta === true || !unwrapped.trim() || unwrapped.trimStart().startsWith("<"))
520
+ continue;
521
+ if (raw.operation === "enqueue") {
522
+ if (bindings.has(offset))
523
+ continue;
524
+ const at = Date.parse(String(raw.timestamp ?? "")), rowAt = Number.isFinite(at) ? at : undefined;
525
+ const record = relevant.filter(candidate => candidate.id && candidate.hash === hash && candidate.queueOffset === undefined
526
+ && candidate.cursor !== undefined && offset >= candidate.cursor
527
+ && (!candidate.entryHook || candidate.entry === undefined || candidate.entry > offset)
528
+ && (rowAt === undefined || candidate.at <= rowAt + ENTRY_SLACK_MS)
529
+ && (rowAt === undefined || rowAt >= candidate.at - ENTRY_SLACK_MS))
530
+ .sort((a, b) => a.at - b.at)[0];
531
+ if (!record)
532
+ continue;
533
+ record.queueOffset = offset;
534
+ record.queueKey = key;
535
+ if (rowAt !== undefined)
536
+ record.queueAt = rowAt;
537
+ if (record.state === "typed")
538
+ record.state = "queued";
539
+ bindings.set(offset, record.id);
540
+ changed = true;
541
+ continue;
542
+ }
543
+ if (raw.operation === "remove" || raw.operation === "popAll") {
544
+ if (bindings.has(offset))
545
+ continue;
546
+ // Removal uses the exact unwrapped queue content, not the phone's normalized
547
+ // words. A persisted key also identifies an enqueue outside the read tail.
548
+ const record = relevant.filter(candidate => candidate.id && candidate.queueOffset !== undefined
549
+ && candidate.cursor !== undefined && offset >= candidate.cursor
550
+ && (occurrence ? candidate.queueOffset === occurrence.offset : candidate.queueKey === key)
551
+ && candidate.queueDequeueOffset === undefined
552
+ && candidate.queueOffset < offset && (candidate.queueRemoveOffset === undefined || candidate.queueRemoveOffset === offset))
553
+ .sort((a, b) => a.queueOffset - b.queueOffset)[0];
554
+ if (!record)
555
+ continue;
556
+ if (record.queueRemoveOffset === undefined) {
557
+ record.queueRemoveOffset = offset;
558
+ changed = true;
559
+ }
560
+ record.queueEnd = consumed(raw) ? "consumed" : "returned";
561
+ bindings.set(offset, record.id);
562
+ }
563
+ continue;
564
+ }
565
+ const text = claudeUserText(raw);
566
+ if (text === undefined || bindings.has(offset))
567
+ continue;
568
+ const hash = promptHash(text);
569
+ const at = Date.parse(String(raw.timestamp ?? "")), rowAt = Number.isFinite(at) ? at : undefined;
570
+ // A submitted turn replaces the enqueue only when it follows it, and never when another
571
+ // message already landed as that row. The delivery's own landed reference wins.
572
+ const record = relevant.filter(candidate => candidate.id && candidate.hash === hash && candidate.queueOffset !== undefined
573
+ && canReplace(candidate, offset) && candidate.queueUserOffset === undefined && (candidate.cursor === undefined || offset >= candidate.cursor)
574
+ && offset > candidate.queueOffset
575
+ && (!candidate.entryHook || candidate.entry === undefined || candidate.entry === offset)
576
+ && (rowAt === undefined || rowAt >= candidate.at - ENTRY_SLACK_MS) && exclusive(candidate, offset))
577
+ .sort((a, b) => (a.entry === offset ? 0 : 1) - (b.entry === offset ? 0 : 1) || a.queueOffset - b.queueOffset)[0];
578
+ if (!record)
579
+ continue;
580
+ record.queueUserOffset = offset;
581
+ bindings.set(offset, record.id);
582
+ changed = true;
583
+ }
584
+ if (changed)
585
+ this.save();
586
+ return bindings;
587
+ }
305
588
  /** Conversation `target` just submitted `prompt`. Its own record wins, then
306
589
  * the oldest open one in the same pane: the agent kept the text across a
307
590
  * conversation change, and the conversation now in the pane is where it
@@ -312,13 +595,14 @@ export class PromptDeliveries {
312
595
  * callback for a row already claimed (the idle check settled it, the hook
313
596
  * came late) settles nothing more. */
314
597
  async submitted(target, prompt) {
598
+ await this.refreshClaudeQueue(target);
315
599
  const hash = promptHash(prompt);
316
600
  this.hookPanes.add(this.paneKey(target));
317
601
  // A failed message stays matchable for a late take only until the pane's next Stop: a turn that ended
318
602
  // without it means a later identical prompt is a new one.
319
603
  const stop = this.lastStop.get(this.paneKey(target)) ?? -Infinity;
320
604
  const pick = () => {
321
- const open = this.records.filter(record => record.hash === hash && this.samePane(record, target) && record.state !== "delivered"
605
+ const open = this.records.filter(record => record.hash === hash && this.samePane(record, target) && record.state !== "delivered" && record.queueEnd !== "returned"
322
606
  && (record.state !== "failed" || (record.settledAt ?? record.at) >= stop));
323
607
  return open.find(entry => entry.session === target.session) ?? open[0];
324
608
  };
@@ -395,7 +679,7 @@ export class PromptDeliveries {
395
679
  * (typed or queued) are matched: a failed one could take the lines of messages that are held, and a late
396
680
  * take of a failed message stays its own hook's to report. */
397
681
  settleJoined(target, prompt) {
398
- const candidates = this.records.filter(record => this.samePane(record, target) && PromptDeliveries.open(record))
682
+ const candidates = this.records.filter(record => this.samePane(record, target) && record.queueEnd !== "returned" && PromptDeliveries.open(record))
399
683
  .sort((a, b) => a.at - b.at).slice(0, JOINED_MAX_OPEN);
400
684
  if (!candidates.length)
401
685
  return false;
@@ -490,6 +774,16 @@ export class PromptDeliveries {
490
774
  record.session = session;
491
775
  this.release(record, "delivered");
492
776
  }
777
+ /** Settlement needs the same occurrence ownership as a transcript read, even if no
778
+ * client has opened that conversation. Custom transcript readers supply their own bindings. */
779
+ async refreshClaudeQueue(target) {
780
+ if (target.source !== "claude" || this.landed !== transcriptEntries)
781
+ return;
782
+ try {
783
+ await this.claudeQueueBindings(target, await transcriptPath("claude", target.session));
784
+ }
785
+ catch { /* Transcript not readable yet. */ }
786
+ }
493
787
  /** Whether the transcript shows the agent took `record`'s message, claiming the entry it settled with.
494
788
  * An entry settles one message: the table of records' `entry` offsets (per conversation) is the only
495
789
  * state, so neither this path nor the hook's can settle two messages with one turn. A user row is a
@@ -500,9 +794,12 @@ export class PromptDeliveries {
500
794
  async taken(record, pass, working = false) {
501
795
  if (record.source !== "claude")
502
796
  return this.takenCodex(record);
797
+ await this.refreshClaudeQueue(record);
798
+ if (record.queueEnd === "returned")
799
+ return false;
503
800
  const same = (other) => other.hash === record.hash && other.server === record.server && other.pane === record.pane && other.session === record.session;
504
- const open = this.records.filter(other => same(other) && PromptDeliveries.claimable(other)).sort((a, b) => a.at - b.at);
505
- if (open[0] !== record)
801
+ const open = this.records.filter(other => same(other) && other.queueEnd !== "returned" && PromptDeliveries.claimable(other)).sort((a, b) => a.at - b.at);
802
+ if (open[0] !== record && record.queueOffset === undefined && record.queueRemoveOffset === undefined)
506
803
  return false;
507
804
  const key = [record.hash, record.server, record.pane, record.session, working].join("|");
508
805
  let free = pass.get(key);
@@ -547,7 +844,16 @@ export class PromptDeliveries {
547
844
  // The record may have settled (its hook claimed a row) while the transcript was read.
548
845
  if (!PromptDeliveries.claimable(record))
549
846
  return false;
550
- const entry = free.shift();
847
+ const index = free.findIndex(row => {
848
+ const owner = this.records.find(other => this.samePane(other, record) && other.session === record.session
849
+ && (row.hook ? other.queueUserOffset === row.offset : other.queueRemoveOffset === row.offset));
850
+ if (owner && owner !== record)
851
+ return false;
852
+ if (record.queueOffset === undefined && record.queueRemoveOffset === undefined)
853
+ return true;
854
+ return row.hook ? record.queueUserOffset === row.offset : record.queueRemoveOffset === row.offset;
855
+ });
856
+ const entry = index < 0 ? undefined : free.splice(index, 1)[0];
551
857
  pass.set(key, free);
552
858
  if (entry === undefined)
553
859
  return false;
@@ -877,6 +1183,52 @@ export async function transcriptLine(record, offset, uuid) {
877
1183
  await file.close();
878
1184
  }
879
1185
  }
1186
+ /** The last `TRANSCRIPT_TAIL_BYTES` of a Claude transcript, parsed into the queue and user rows a
1187
+ * phone message's identity can be read from, each with the byte offset it starts at. */
1188
+ async function claudeQueueRows(file) {
1189
+ const handle = await open(file, "r");
1190
+ try {
1191
+ const size = (await handle.stat()).size, start = Math.max(0, size - TRANSCRIPT_TAIL_BYTES);
1192
+ if (size === start)
1193
+ return [];
1194
+ const buffer = Buffer.alloc(size - start);
1195
+ await handle.read(buffer, 0, buffer.length, start);
1196
+ let base = start, text = buffer.toString("utf8");
1197
+ // Read from the first whole line: a byte split would decode as another character.
1198
+ if (start > 0) {
1199
+ const newline = buffer.indexOf(10);
1200
+ if (newline < 0)
1201
+ return [];
1202
+ base = start + newline + 1;
1203
+ text = buffer.subarray(newline + 1).toString("utf8");
1204
+ }
1205
+ const rows = [];
1206
+ let offset = base;
1207
+ for (const line of text.split("\n")) {
1208
+ const bytes = Buffer.byteLength(line);
1209
+ if (line && (line.includes('"queue-operation"') || line.includes('"user"'))) {
1210
+ try {
1211
+ rows.push({ offset, raw: object(JSON.parse(line)) });
1212
+ }
1213
+ catch { /* malformed or cut row */ }
1214
+ }
1215
+ offset += bytes + 1;
1216
+ }
1217
+ return rows;
1218
+ }
1219
+ finally {
1220
+ await handle.close();
1221
+ }
1222
+ }
1223
+ /** The words of a user turn: what a phone message submitted as that turn matches by. */
1224
+ function claudeUserText(raw) {
1225
+ if (raw.type !== "user" || raw.isMeta === true || raw.isSidechain === true)
1226
+ return undefined;
1227
+ const content = object(raw.message).content;
1228
+ const text = typeof content === "string" ? content
1229
+ : objects(content).filter(block => block.type === "text" && typeof block.text === "string").map(block => String(block.text)).join("\n");
1230
+ return promptKey(text) ? text : undefined;
1231
+ }
880
1232
  async function transcriptEntries(record) {
881
1233
  const file = await open(await transcriptPath(record.source, record.session), "r");
882
1234
  try {
@@ -0,0 +1,8 @@
1
+ /** Harness-native prompt identities, normalized once for both the lifecycle
2
+ * callback and the transcript reader. Claude is the only harness with a
3
+ * prompt-specific identity today; other harnesses leave the field absent. */
4
+ /** A bounded, opaque Claude prompt id. Absent, malformed or oversized ids stay
5
+ * unavailable rather than being inferred from text, time or transcript order. */
6
+ export declare function claudePromptEntryId(value: unknown): string | undefined;
7
+ /** Validate an already-normalized wire value (the Hook's callback body). */
8
+ export declare function normalizedPromptEntryId(value: unknown): string | undefined;
@@ -0,0 +1,15 @@
1
+ /** Harness-native prompt identities, normalized once for both the lifecycle
2
+ * callback and the transcript reader. Claude is the only harness with a
3
+ * prompt-specific identity today; other harnesses leave the field absent. */
4
+ /** A bounded, opaque Claude prompt id. Absent, malformed or oversized ids stay
5
+ * unavailable rather than being inferred from text, time or transcript order. */
6
+ export function claudePromptEntryId(value) {
7
+ if (typeof value !== "string" || !/^[A-Za-z0-9._:-]{1,192}$/.test(value))
8
+ return undefined;
9
+ const id = `claude:prompt:${value}`;
10
+ return id.length <= 256 ? id : undefined;
11
+ }
12
+ /** Validate an already-normalized wire value (the Hook's callback body). */
13
+ export function normalizedPromptEntryId(value) {
14
+ return typeof value === "string" && value.length <= 256 && /^claude:prompt:[A-Za-z0-9._:-]{1,192}$/.test(value) ? value : undefined;
15
+ }
@@ -12,7 +12,8 @@ export function requestPeer(request) {
12
12
  return undefined;
13
13
  try {
14
14
  const value = JSON.parse(Buffer.from(encoded, "base64url").toString("utf8"));
15
- if (!/^[a-f0-9]{64}$/.test(value.fingerprint) || value.id !== undefined && !/^[a-f0-9-]{36}$/i.test(value.id))
15
+ if (typeof value.fingerprint !== "string" || !/^[a-f0-9]{64}$/.test(value.fingerprint)
16
+ || value.id !== undefined && (typeof value.id !== "string" || !/^[a-f0-9-]{36}$/i.test(value.id)))
16
17
  return undefined;
17
18
  if (value.name !== undefined && (typeof value.name !== "string" || !/^[A-Za-z0-9_.-]{1,253}$/.test(value.name)))
18
19
  return undefined;
@@ -0,0 +1,17 @@
1
+ import { z } from "zod";
2
+ import { type Schedule } from "./schedule-format.js";
3
+ export declare const SCHEDULE_EVENT_BODY_CAP: number;
4
+ declare const eventSchema: z.ZodObject<{
5
+ event: z.ZodString;
6
+ deliveryId: z.ZodString;
7
+ payload: z.ZodRecord<z.ZodString, z.ZodUnknown>;
8
+ }, z.core.$strict>;
9
+ export type ScheduleEvent = z.infer<typeof eventSchema>;
10
+ export declare function parseScheduleEvent(body: unknown): ScheduleEvent;
11
+ /** One replacement pass; substituted values are never parsed as templates. */
12
+ export declare function scheduleEventPrompt(schedule: Schedule, event: ScheduleEvent): {
13
+ prompt: string;
14
+ fields: Record<string, string>;
15
+ matches: boolean;
16
+ };
17
+ export {};
@@ -0,0 +1,53 @@
1
+ import { z } from "zod";
2
+ import { redactSecretsForLog } from "../content/secrets.js";
3
+ import { BridgeError } from "./protocol.js";
4
+ import { eventNameSchema, payloadPathSchema } from "./schedule-format.js";
5
+ export const SCHEDULE_EVENT_BODY_CAP = 256 * 1024;
6
+ const eventSchema = z.object({ event: eventNameSchema,
7
+ deliveryId: z.string().regex(/^[A-Za-z0-9_.:-]{1,200}$/),
8
+ payload: z.record(z.string(), z.unknown()),
9
+ }).strict();
10
+ export function parseScheduleEvent(body) {
11
+ try {
12
+ if (Buffer.byteLength(JSON.stringify(body) ?? "") > SCHEDULE_EVENT_BODY_CAP)
13
+ throw new BridgeError(413, "Schedule event is too large.");
14
+ return eventSchema.parse(body);
15
+ }
16
+ catch (error) {
17
+ if (error instanceof BridgeError)
18
+ throw error;
19
+ throw new BridgeError(400, "Invalid schedule event: expected { event, deliveryId, payload }.");
20
+ }
21
+ }
22
+ function field(payload, path) {
23
+ if (!payloadPathSchema.safeParse(path).success)
24
+ return undefined;
25
+ let current = payload;
26
+ for (const part of path.split(".")) {
27
+ if (!current || typeof current !== "object" || !Object.hasOwn(current, part))
28
+ return undefined;
29
+ current = current[part];
30
+ }
31
+ return current;
32
+ }
33
+ /** One replacement pass; substituted values are never parsed as templates. */
34
+ export function scheduleEventPrompt(schedule, event) {
35
+ const fields = Object.create(null);
36
+ const text = (path) => {
37
+ if (!payloadPathSchema.safeParse(path).success)
38
+ return "";
39
+ const value = field(event.payload, path);
40
+ const scalar = typeof value === "string" || typeof value === "number" || typeof value === "boolean";
41
+ // Detect credentials before truncation: a truncated credential could evade detection.
42
+ const safe = scalar ? redactSecretsForLog(String(value)).slice(0, 1024).replace(/[\x00-\x08\x0b-\x1f\x7f]/g, "") : "";
43
+ if (Object.keys(fields).length < 64 || Object.hasOwn(fields, path))
44
+ fields[path] = safe;
45
+ return safe;
46
+ };
47
+ const matches = (schedule.filters ?? []).map(filter => {
48
+ text(filter.path);
49
+ return field(event.payload, filter.path) === filter.equals;
50
+ }).every(Boolean);
51
+ const prompt = schedule.prompt.replace(/\{\{payload\.([^{}]+)\}\}/g, (_match, path) => text(path)).slice(0, 8000);
52
+ return { prompt, fields, matches };
53
+ }