@phren/cli 0.3.15 → 0.3.17

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 (41) hide show
  1. package/dist/bridge/agent-hooks.d.ts +10 -0
  2. package/dist/bridge/agent-hooks.js +49 -10
  3. package/dist/bridge/claude-suggestion.d.ts +8 -0
  4. package/dist/bridge/claude-suggestion.js +71 -0
  5. package/dist/bridge/dispatch-returns.d.ts +6 -3
  6. package/dist/bridge/dispatch-returns.js +29 -17
  7. package/dist/bridge/job-registry.d.ts +144 -0
  8. package/dist/bridge/job-registry.js +247 -0
  9. package/dist/bridge/opencode-permissions.d.ts +17 -0
  10. package/dist/bridge/opencode-permissions.js +96 -0
  11. package/dist/bridge/protocol.d.ts +4 -0
  12. package/dist/bridge/protocol.js +3 -0
  13. package/dist/bridge/resources.d.ts +38 -5
  14. package/dist/bridge/resources.js +110 -19
  15. package/dist/bridge/server-launch.js +8 -0
  16. package/dist/bridge/server-routes.d.ts +1 -1
  17. package/dist/bridge/server-routes.js +8 -6
  18. package/dist/bridge/server-stream.js +11 -2
  19. package/dist/bridge/session-activity.d.ts +13 -0
  20. package/dist/bridge/session-activity.js +27 -2
  21. package/dist/bridge/settings-switch.d.ts +12 -2
  22. package/dist/bridge/settings-switch.js +13 -6
  23. package/dist/bridge/speech.d.ts +6 -4
  24. package/dist/bridge/speech.js +6 -4
  25. package/dist/bridge/terminal-tmux.d.ts +4 -2
  26. package/dist/bridge/terminal-tmux.js +13 -7
  27. package/dist/bridge/transcript-claude.d.ts +9 -1
  28. package/dist/bridge/transcript-claude.js +50 -1
  29. package/dist/bridge/transcript-codex.js +23 -3
  30. package/dist/bridge/transcripts.d.ts +5 -1
  31. package/dist/bridge/transcripts.js +21 -5
  32. package/dist/bridge-hook.mjs +1046 -530
  33. package/dist/computers/command.js +2 -1
  34. package/dist/fanout/opencode-serve.js +3 -2
  35. package/dist/hooks.d.ts +3 -0
  36. package/dist/hooks.js +41 -6
  37. package/dist/init/setup.js +6 -3
  38. package/dist/modules/registry.js +1 -1
  39. package/dist/tools/dispatch.js +3 -2
  40. package/package.json +1 -1
  41. package/plugins/opencode/phren-transcript.js +4 -4
@@ -11,6 +11,14 @@ export declare function claudeChildAgents(file: string, session: string): Promis
11
11
  * taken as finished: the parent records no end for it, and a session that
12
12
  * exited mid-skill leaves it without a final reply. */
13
13
  export declare const CLAUDE_SKILL_QUIET_MS: number;
14
+ /** State one newest-first pass over a Claude transcript keeps so a
15
+ * content-free `dequeue` can name the prompt turn it delivered: the queue key
16
+ * of that turn and whether the agent's own schedule (a cron, /loop or
17
+ * ScheduleWakeup fire, or an auto-continuation) injected it. */
18
+ export interface ClaudeQueueState {
19
+ key?: string;
20
+ scheduled?: boolean;
21
+ }
14
22
  export declare const harnessPreamble: (text: string) => boolean;
15
23
  export declare function unwrapPastedContent(text: string): string;
16
24
  /** A thinking block Claude marks as narration for the person watching: its
@@ -29,4 +37,4 @@ export declare function phrenHookContext(raw: Json, includeSidechain?: boolean):
29
37
  /** Claude Code rows the phone may see: user, assistant and system turns with
30
38
  * private reasoning redacted, queued phone messages, background task
31
39
  * notifications and compaction markers. */
32
- export declare function visibleClaudeEvent(raw: Json, includeSidechain?: boolean): Json | undefined;
40
+ export declare function visibleClaudeEvent(raw: Json, includeSidechain?: boolean, queue?: ClaudeQueueState): Json | undefined;
@@ -356,6 +356,26 @@ async function claudeChildBelongsTo(file, parent, agentId) {
356
356
  // it is what the phone's model chip shows as in effect. `permissionMode` on a
357
357
  // user row is the mode that turn ran in (the phone's permission chip).
358
358
  const CLAUDE_KEYS = new Set(["type", "uuid", "parentUuid", "timestamp", "message", "gitBranch", "cwd", "requestId", "isMeta", "isSidechain", "isCompactSummary", "phrenQueued", "phrenQueueKey", "phrenBackground", "phrenCompacted", "effort", "permissionMode"]);
359
+ /** The `phrenQueueKey` of the prompt turn a queued message was delivered as:
360
+ * the same SHA-256 of the unwrapped content the enqueue row exports. Undefined
361
+ * for a tool result, a harness envelope, or a turn that is not the person's. */
362
+ function queuePromptKey(raw) {
363
+ if (raw.type !== "user" || raw.isSidechain === true)
364
+ return undefined;
365
+ const content = object(raw.message).content;
366
+ const text = unwrapPastedContent(typeof content === "string" ? content
367
+ : objects(content).filter(block => block.type === "text").map(block => String(block.text ?? "")).join("\n"));
368
+ if (!text.trim() || text.trimStart().startsWith("<"))
369
+ return undefined;
370
+ return createHash("sha256").update(text).digest("hex");
371
+ }
372
+ /** A prompt the agent scheduled for itself, which Claude Code delivers as a
373
+ * hidden user turn (`isMeta`). Auto-continuation names its origin rather than
374
+ * a task id. */
375
+ function scheduledPromptTurn(raw) {
376
+ return raw.turnOrigin === "scheduled" || typeof raw.scheduledTaskId === "string"
377
+ || object(raw.origin).kind === "auto-continuation";
378
+ }
359
379
  export const harnessPreamble = (text) => /^<(?:environment_context>|user_instructions>|permission_profile|system-reminder>|turn_context>)/.test(text.trimStart());
360
380
  function taskNotification(content) {
361
381
  const envelope = /<task-notification>([\s\S]*?)<\/task-notification>/.exec(content)?.[1];
@@ -457,7 +477,7 @@ export function phrenHookContext(raw, includeSidechain = false) {
457
477
  /** Claude Code rows the phone may see: user, assistant and system turns with
458
478
  * private reasoning redacted, queued phone messages, background task
459
479
  * notifications and compaction markers. */
460
- export function visibleClaudeEvent(raw, includeSidechain = false) {
480
+ export function visibleClaudeEvent(raw, includeSidechain = false, queue) {
461
481
  // A follow-up the phone sent a Claude fan-out worker, written into its
462
482
  // event log by the Hook before the resumed run.
463
483
  if (raw.type === "phren/fanout-message" && typeof raw.text === "string") {
@@ -467,6 +487,26 @@ export function visibleClaudeEvent(raw, includeSidechain = false) {
467
487
  // digest so enqueue and remove keep matching keys.
468
488
  if (raw.type === "queue-operation" && typeof raw.content === "string")
469
489
  raw = { ...raw, content: unwrapPastedContent(raw.content) };
490
+ // A dequeue is the queue head handed to a turn. Unlike `remove` it carries
491
+ // no content, so its consumption is keyed by the prompt turn it delivered
492
+ // (a newest-first read sees that turn first) and flagged when the agent's
493
+ // own schedule fired it.
494
+ if (raw.type === "queue-operation" && raw.operation === "dequeue") {
495
+ const key = queue?.key, scheduled = queue?.scheduled;
496
+ // One prompt turn answers one dequeue: an older dequeue must not reuse
497
+ // this key and mark a different queued message consumed.
498
+ if (queue) {
499
+ queue.key = undefined;
500
+ queue.scheduled = undefined;
501
+ }
502
+ return { type: "phren_queue_consumed", ...(key ? { key } : {}), ...(key && scheduled ? { scheduled: true } : {}), timestamp: raw.timestamp };
503
+ }
504
+ // popAll pulls queued prompts back into the input: they were neither
505
+ // consumed nor scheduled, so the phone must not draw the leftovers as a
506
+ // "Scheduled check" after the next reply.
507
+ if (raw.type === "queue-operation" && raw.operation === "popAll" && typeof raw.content === "string") {
508
+ return { type: "phren_queue_returned", key: createHash("sha256").update(raw.content).digest("hex"), timestamp: raw.timestamp };
509
+ }
470
510
  if (raw.type === "queue-operation" && raw.operation === "remove" && typeof raw.content === "string") {
471
511
  return { type: "phren_queue_consumed", key: createHash("sha256").update(raw.content).digest("hex"), timestamp: raw.timestamp };
472
512
  }
@@ -529,6 +569,15 @@ export function visibleClaudeEvent(raw, includeSidechain = false) {
529
569
  if (raw.type === "permission-mode" && typeof raw.permissionMode === "string" && /^[A-Za-z]{1,30}$/.test(raw.permissionMode)) {
530
570
  return { type: "permission-mode", permissionMode: raw.permissionMode, ...(typeof raw.timestamp === "string" ? { timestamp: raw.timestamp } : {}) };
531
571
  }
572
+ // Remember the prompt turn a queued message was delivered as, so the
573
+ // content-free dequeue written before it can be keyed and flagged scheduled.
574
+ if (queue && raw.type === "user") {
575
+ const key = queuePromptKey(raw);
576
+ if (key !== undefined) {
577
+ queue.key = key;
578
+ queue.scheduled = scheduledPromptTurn(raw);
579
+ }
580
+ }
532
581
  if (raw.isMeta || (raw.isSidechain && !includeSidechain) || !["user", "assistant", "system"].includes(String(raw.type)))
533
582
  return undefined;
534
583
  raw = Object.fromEntries(Object.entries(raw).filter(([key]) => CLAUDE_KEYS.has(key)));
@@ -1,5 +1,5 @@
1
1
  import { createReadStream } from "node:fs";
2
- import { stat } from "node:fs/promises";
2
+ import { open, stat } from "node:fs/promises";
3
3
  import { object, objects, sessionId } from "./protocol.js";
4
4
  import { visibleCodexExecEvent } from "./fanouts.js";
5
5
  import { harnessPreamble } from "./transcript-claude.js";
@@ -24,6 +24,24 @@ function addChildRelation(line, found) {
24
24
  }
25
25
  catch { /* Ignore malformed/private rows. */ }
26
26
  }
27
+ const TAIL_CHECK = 256;
28
+ async function readAt(file, position, length) {
29
+ const handle = await open(file, "r");
30
+ try {
31
+ const buffer = Buffer.alloc(length);
32
+ const { bytesRead } = await handle.read(buffer, 0, length, position);
33
+ return buffer.subarray(0, bytesRead);
34
+ }
35
+ finally {
36
+ await handle.close();
37
+ }
38
+ }
39
+ /** Whether `file` still holds `expected` at `position`. */
40
+ async function sameBytes(file, position, expected) {
41
+ if (position < 0)
42
+ return false;
43
+ return (await readAt(file, position, expected.length).catch(() => Buffer.alloc(0))).equals(expected);
44
+ }
27
45
  export async function directChildAgents(file) {
28
46
  const metadata = await stat(file), cached = childRelationCache.get(file);
29
47
  if (cached && cached.dev === metadata.dev && cached.ino === metadata.ino
@@ -32,7 +50,8 @@ export async function directChildAgents(file) {
32
50
  // Codex rollouts are append-only. Keep the byte position of the last full
33
51
  // JSONL row so a live transcript only scans new rows as its chat advances.
34
52
  // A truncate, replacement, or in-place rewrite starts from zero.
35
- const append = cached && cached.dev === metadata.dev && cached.ino === metadata.ino && metadata.size > cached.fileSize;
53
+ const append = cached && cached.dev === metadata.dev && cached.ino === metadata.ino && metadata.size > cached.fileSize
54
+ && await sameBytes(file, cached.completeOffset - cached.tail.length, cached.tail);
36
55
  const start = append ? cached.completeOffset : 0;
37
56
  const found = append ? new Map(cached.relations) : new Map();
38
57
  let pending = Buffer.alloc(0), completeOffset = start;
@@ -46,8 +65,9 @@ export async function directChildAgents(file) {
46
65
  pending = pending.subarray(newline + 1);
47
66
  }
48
67
  }
68
+ const tail = completeOffset > 0 ? await readAt(file, Math.max(0, completeOffset - TAIL_CHECK), Math.min(TAIL_CHECK, completeOffset)) : Buffer.alloc(0);
49
69
  const entry = { dev: metadata.dev, ino: metadata.ino, fileSize: metadata.size, completeOffset,
50
- mtimeMs: metadata.mtimeMs, relations: found };
70
+ mtimeMs: metadata.mtimeMs, tail, relations: found };
51
71
  childRelationCache.set(file, entry);
52
72
  while (childRelationCache.size > 64)
53
73
  childRelationCache.delete(childRelationCache.keys().next().value);
@@ -1,6 +1,7 @@
1
1
  import { type AccountRef } from "./claude-accounts.js";
2
2
  import { type Json, type Provider, type Target } from "./protocol.js";
3
3
  import { type ChangeLookup } from "./changes.js";
4
+ import { type ClaudeQueueState } from "./transcript-claude.js";
4
5
  export { isNarration, unwrapPastedContent } from "./transcript-claude.js";
5
6
  export { codeToolCalls, projectCodexRow, type CodeToolCall } from "./transcript-codex.js";
6
7
  export interface Entry {
@@ -55,6 +56,9 @@ export declare function childAgentTree(source: Provider, session: string, depth?
55
56
  * from being returned if relation internals grow later. */
56
57
  export declare function publicChildAgents(tree: ChildAgentRelation[]): Json[];
57
58
  export declare function childAgent(tree: ChildAgentRelation[], id: string): LocalChildAgentRelation | undefined;
59
+ /** The running children of a child-agent tree, at any depth: the sub-agents,
60
+ * teammates, workflow agents and fan-out jobs a finished turn still waits on. */
61
+ export declare function runningChildAgents(tree: ChildAgentRelation[]): ChildAgentRelation[];
58
62
  /**
59
63
  * The phren store whose `.runtime/sessions` holds phren-agent event logs.
60
64
  * `PHREN_PATH` or the shared `~/.phren` root — the two resolutions the CLI's
@@ -78,7 +82,7 @@ export declare function transcriptPath(source: Provider, session: string, accoun
78
82
  * transcripts the agent writes itself. */
79
83
  export declare function refreshTranscript(file: string, source: Provider, session: string): Promise<void>;
80
84
  /** Public conversation/tool events and real usage only. Never export private reasoning. */
81
- export declare function visibleEvent(raw: Json, source: Provider, includeSidechain?: boolean, cwd?: string): Json | undefined;
85
+ export declare function visibleEvent(raw: Json, source: Provider, includeSidechain?: boolean, cwd?: string, queue?: ClaudeQueueState): Json | undefined;
82
86
  /** Parse only the requested page; shared byte indexes make reopening and
83
87
  * backward pagination independent of the amount of already-read history. */
84
88
  export declare class TranscriptReader {
@@ -70,6 +70,13 @@ export function childAgent(tree, id) {
70
70
  return nested;
71
71
  }
72
72
  }
73
+ /** The running children of a child-agent tree, at any depth: the sub-agents,
74
+ * teammates, workflow agents and fan-out jobs a finished turn still waits on. */
75
+ export function runningChildAgents(tree) {
76
+ return tree.flatMap(function visit(child) {
77
+ return [child, ...child.children.flatMap(visit)];
78
+ }).filter(child => child.state === "running");
79
+ }
73
80
  /** Preserve content positions and image types; original bytes stay in the
74
81
  * transcript for the separate image route. Only provider content blocks are
75
82
  * interpreted, never text strings or arbitrary tool arguments. */
@@ -241,13 +248,13 @@ export async function refreshTranscript(file, source, session) {
241
248
  await materializeCodexThread(session);
242
249
  }
243
250
  /** Public conversation/tool events and real usage only. Never export private reasoning. */
244
- export function visibleEvent(raw, source, includeSidechain = false, cwd) {
251
+ export function visibleEvent(raw, source, includeSidechain = false, cwd, queue) {
245
252
  if (source === "phren" || source === "opencode")
246
253
  return visibleOpencodeEvent(raw, source, cwd);
247
254
  if (source === "codex")
248
255
  return visibleCodexEvent(raw);
249
256
  if (source === "claude")
250
- return visibleClaudeEvent(raw, includeSidechain);
257
+ return visibleClaudeEvent(raw, includeSidechain, queue);
251
258
  return visibleCopilotEvent(raw);
252
259
  }
253
260
  /** Parse only the requested page; shared byte indexes make reopening and
@@ -299,11 +306,14 @@ export class TranscriptReader {
299
306
  const entryBudget = opening ? 60 : 200;
300
307
  const byteBudget = opening ? 1_048_576 : 4_194_304;
301
308
  let bytes = 0, cursor = end, held;
309
+ // Claude's queue pairing: the row scan is newest-first, so a prompt turn
310
+ // is seen before the content-free dequeue that delivered it.
311
+ const queue = {};
302
312
  for await (const row of index.rows(handle, end, lower, signal)) {
303
313
  signal?.throwIfAborted();
304
314
  let rows = [];
305
315
  try {
306
- let raw = row.bytes && visibleEvent(object(JSON.parse(row.bytes.toString())), this.source, this.includeSidechain, this.cwd);
316
+ let raw = row.bytes && visibleEvent(object(JSON.parse(row.bytes.toString())), this.source, this.includeSidechain, this.cwd, queue);
307
317
  // A child agent's transcript is the sidechain. Its rows are that
308
318
  // conversation's own turns, not something for the reader to skip.
309
319
  if (raw && this.includeSidechain && raw.isSidechain === true) {
@@ -372,8 +382,14 @@ export class TranscriptReader {
372
382
  // instead of silently merging two disjoint windows. A pending diff
373
383
  // holds its row for a later poll and is not a completed page.
374
384
  const skippedLiveLines = before === undefined && held === undefined && cursor > lower;
375
- return { entries: entries.reverse(), totalLines: index.lines, startLine: cursor, hasMore: cursor > 0,
376
- reset: (resuming && !pastEnd ? false : reset) || skippedLiveLines };
385
+ // The phone resumes after `totalLines - 1`, so a live page does not
386
+ // count a held row or what follows it: those are still owed. An older
387
+ // page is never a replacement. The history route reads with a fresh
388
+ // reader, and a reset there made the phone drop every recent row it
389
+ // held and keep only the older page.
390
+ return { entries: entries.reverse(), totalLines: held ?? index.lines,
391
+ startLine: cursor, hasMore: cursor > 0,
392
+ reset: before !== undefined ? false : (resuming && !pastEnd ? false : reset) || skippedLiveLines };
377
393
  }, signal);
378
394
  }
379
395
  }