@phren/cli 0.3.58 → 0.3.59

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/README.md +1 -1
  2. package/dist/bridge/account-add.d.ts +30 -0
  3. package/dist/bridge/account-add.js +125 -19
  4. package/dist/bridge/account-failover.d.ts +9 -2
  5. package/dist/bridge/account-failover.js +1 -1
  6. package/dist/bridge/account-policy.d.ts +44 -0
  7. package/dist/bridge/account-policy.js +103 -0
  8. package/dist/bridge/account-pools.d.ts +35 -0
  9. package/dist/bridge/account-pools.js +171 -0
  10. package/dist/bridge/account-usage.d.ts +18 -0
  11. package/dist/bridge/account-usage.js +57 -1
  12. package/dist/bridge/agent-hook-callback.d.ts +6 -0
  13. package/dist/bridge/agent-hook-callback.js +10 -2
  14. package/dist/bridge/agent-hook-stores.d.ts +3 -0
  15. package/dist/bridge/agent-hook-stores.js +13 -0
  16. package/dist/bridge/agent-hooks.d.ts +12 -2
  17. package/dist/bridge/agent-hooks.js +41 -4
  18. package/dist/bridge/claude-account-setup.d.ts +16 -0
  19. package/dist/bridge/claude-account-setup.js +46 -2
  20. package/dist/bridge/claude-accounts.d.ts +9 -0
  21. package/dist/bridge/claude-accounts.js +53 -15
  22. package/dist/bridge/claude-credits.d.ts +5 -1
  23. package/dist/bridge/claude-credits.js +37 -29
  24. package/dist/bridge/command.js +12 -3
  25. package/dist/bridge/dispatch-command.js +22 -0
  26. package/dist/bridge/dispatch-returns.d.ts +23 -0
  27. package/dist/bridge/dispatch-returns.js +57 -0
  28. package/dist/bridge/dispatch.d.ts +26 -4
  29. package/dist/bridge/dispatch.js +100 -11
  30. package/dist/bridge/git-host-gitlab.js +2 -1
  31. package/dist/bridge/hand-off-queue.d.ts +71 -0
  32. package/dist/bridge/hand-off-queue.js +38 -0
  33. package/dist/bridge/harnesses.d.ts +12 -0
  34. package/dist/bridge/harnesses.js +20 -4
  35. package/dist/bridge/helper.d.ts +54 -0
  36. package/dist/bridge/helper.js +186 -0
  37. package/dist/bridge/herdr.js +6 -2
  38. package/dist/bridge/hook-fast.d.ts +3 -0
  39. package/dist/bridge/hook-fast.js +10 -2
  40. package/dist/bridge/move-computers.d.ts +15 -1
  41. package/dist/bridge/move-computers.js +123 -26
  42. package/dist/bridge/prompt-deliveries.d.ts +29 -1
  43. package/dist/bridge/prompt-deliveries.js +146 -10
  44. package/dist/bridge/schedule-watch.js +17 -3
  45. package/dist/bridge/server-routes.d.ts +3 -0
  46. package/dist/bridge/server-routes.js +66 -6
  47. package/dist/bridge/server.js +2 -1
  48. package/dist/bridge/session-move.d.ts +59 -1
  49. package/dist/bridge/session-move.js +266 -18
  50. package/dist/bridge/simulators.d.ts +19 -0
  51. package/dist/bridge/simulators.js +93 -13
  52. package/dist/bridge/speech-live.js +132 -22
  53. package/dist/bridge/task-routes.d.ts +16 -16
  54. package/dist/bridge/terminal-herdr.js +6 -1
  55. package/dist/bridge/terminal-tmux.js +9 -5
  56. package/dist/bridge/terminal.d.ts +9 -2
  57. package/dist/bridge/transcript-claude.d.ts +3 -0
  58. package/dist/bridge/transcript-claude.js +175 -29
  59. package/dist/bridge/transcript-preview.d.ts +11 -2
  60. package/dist/bridge/transcript-preview.js +90 -8
  61. package/dist/bridge/turn-records.d.ts +19 -0
  62. package/dist/bridge/turn-records.js +78 -3
  63. package/dist/bridge-hook.mjs +11394 -9961
  64. package/dist/cli-registry.js +2 -2
  65. package/dist/content/citation.d.ts +4 -0
  66. package/dist/content/citation.js +21 -21
  67. package/dist/data/task-contract.d.ts +4 -4
  68. package/dist/governance/policy.js +5 -2
  69. package/dist/index.js +1 -1
  70. package/dist/modules/registry.js +3 -3
  71. package/dist/project-config.d.ts +14 -0
  72. package/dist/project-config.js +40 -1
  73. package/dist/tools/helper.d.ts +3 -0
  74. package/dist/tools/helper.js +44 -0
  75. package/package.json +1 -1
@@ -4,10 +4,12 @@ import { createInterface } from "node:readline";
4
4
  import { createHash } from "node:crypto";
5
5
  import path from "node:path";
6
6
  import { object, objects } from "./protocol.js";
7
+ import { latestStopTasks } from "./turn-records.js";
7
8
  const claudeRelationCache = new Map();
8
9
  const copyRows = (rows) => ({ launches: new Map([...rows.launches].map(([id, launch]) => [id, { ...launch }])),
9
10
  skills: new Set(rows.skills), workflows: new Map([...rows.workflows].map(([id, workflow]) => [id, { ...workflow }])),
10
- teammates: new Map([...rows.teammates].map(([name, launch]) => [name, { ...launch }])) });
11
+ teammates: new Map([...rows.teammates].map(([name, launch]) => [name, { ...launch }])),
12
+ foreground: new Map(rows.foreground), unidentified: new Map(rows.unidentified) });
11
13
  const claudeChildModelCache = new Map();
12
14
  function cacheClaudeChildModel(file, entry) {
13
15
  claudeChildModelCache.set(file, entry);
@@ -85,17 +87,24 @@ async function withClaudeChildModels(relations) {
85
87
  return model === undefined ? relation : { ...relation, model };
86
88
  }));
87
89
  }
90
+ /** How long after a Stop its list of running background agents is believed: a session that exits leaves its
91
+ * last Stop behind, and an agent of it that never finished must not run forever. */
92
+ export const CLAUDE_STOP_TRUST_MS = 4 * 60 * 60 * 1000;
88
93
  export async function claudeChildAgents(file, session) {
89
- const metadata = await stat(file), signature = `${metadata.dev}:${metadata.ino}:${metadata.size}:${metadata.mtimeMs}`;
94
+ const metadata = await stat(file), parent = `${metadata.dev}:${metadata.ino}:${metadata.size}:${metadata.mtimeMs}`;
95
+ // The parent's latest Stop lists its background tasks as Claude itself counts them.
96
+ const listed = await latestStopTasks("claude", session).catch(() => undefined);
97
+ const stop = listed && Date.now() - Date.parse(listed.at) < CLAUDE_STOP_TRUST_MS ? listed : undefined;
98
+ const signature = `${parent}:${stop ? `${stop.seq}@${stop.at}` : "-"}`;
90
99
  const cached = claudeRelationCache.get(file);
91
100
  if (cached?.signature === signature && !(cached.recheckAt !== undefined && Date.now() >= cached.recheckAt)) {
92
101
  cached.relations = await withClaudeChildModels(cached.relations);
93
102
  return cached.relations;
94
103
  }
95
104
  // A recheck of an unchanged parent (a launch whose transcript was not there
96
- // yet, a background skill or workflow still running) reads only the children.
97
- const rows = cached?.signature === signature && cached.rows ? cached.rows : await claudeParentRows(file);
98
- return claudeChildRelations(file, session, signature, rows);
105
+ // yet, a background skill or workflow still running, a new Stop) reads only the children.
106
+ const rows = cached?.signature.startsWith(`${parent}:`) && cached.rows ? cached.rows : await claudeParentRows(file);
107
+ return claudeChildRelations(file, session, signature, rows, stop);
99
108
  }
100
109
  async function claudeParentRows(file) {
101
110
  const launches = new Map();
@@ -111,21 +120,38 @@ async function claudeParentRows(file) {
111
120
  // teammate-message instead, and may be woken again later. Their file is
112
121
  // `agent-a<name>-<hex>.jsonl` beside the Task sidechains.
113
122
  const teammates = new Map();
123
+ // Agent calls by tool_use id: the parent waits on a foreground one until its tool_result; a background one
124
+ // waits here for its launch result, which names its agent (or, when it names none, stays here).
125
+ const foreground = new Map(), background = new Map(), unidentified = new Map();
114
126
  const lines = createInterface({ input: createReadStream(file, { encoding: "utf8" }), crlfDelay: Infinity });
115
127
  for await (const line of lines) {
116
128
  try {
117
129
  const raw = object(JSON.parse(line)), result = object(raw.toolUseResult);
118
130
  const blocks = objects(object(raw.message).content);
119
- const agentId = String(result.agentId ?? ""), status = String(result.status ?? "");
120
- if (/^[A-Za-z0-9._-]{1,128}$/.test(agentId) && ["async_launched", "running"].includes(status)) {
121
- const callId = String(blocks.find(b => b.type === "tool_result")?.tool_use_id ?? "");
122
- if (callId)
123
- launches.set(agentId, { path: String(result.description || result.name || "Agent").slice(0, 200), callId, state: "running" });
131
+ const status = String(result.status ?? "");
132
+ // The agent id under the key Claude Code uses, or the one an older or newer version does.
133
+ const agentId = String([result.agentId, result.agent_id, result.taskType === "local_workflow" ? undefined : result.taskId, result.task_id]
134
+ .find(value => typeof value === "string" && /^[A-Za-z0-9._-]{1,128}$/.test(value)) ?? "");
135
+ // A launch that runs on: async by its own word, or by any status that is not an end.
136
+ const launched = result.taskType !== "local_workflow" && !/^(completed|failed|error|killed|cancell?ed|stopped|done)$/.test(status)
137
+ && (result.isAsync === true || /^(async_)?(launched|running|started|queued|pending|spawned)$/.test(status));
138
+ const resultCall = String(blocks.find(b => b.type === "tool_result")?.tool_use_id ?? "");
139
+ if (launched && agentId && resultCall) {
140
+ launches.set(agentId, { path: String(result.description || result.name || "Agent").slice(0, 200), callId: resultCall, state: "running" });
141
+ }
142
+ else if (launched && resultCall && !agentId && background.has(resultCall)) {
143
+ const call = background.get(resultCall);
144
+ // Timed from the call itself: its agent can start before the launch result is stamped.
145
+ unidentified.set(resultCall, { path: String(result.description || call?.path || "Agent").slice(0, 200), callId: resultCall, prompt: call?.prompt ?? "",
146
+ ...(call?.at ? { at: call.at } : typeof raw.timestamp === "string" ? { at: raw.timestamp } : {}) });
124
147
  }
125
148
  // SendMessage to a finished agent resumes it until its next final notification.
126
149
  const resumed = typeof result.resumedAgentId === "string" ? launches.get(result.resumedAgentId) : undefined;
127
- if (resumed && typeof result.message === "string" && /^Resuming agent\b/i.test(result.message))
150
+ if (resumed && typeof result.message === "string" && /^Resuming agent\b/i.test(result.message)) {
128
151
  resumed.state = "running";
152
+ if (typeof raw.timestamp === "string")
153
+ resumed.resumedAt = raw.timestamp;
154
+ }
129
155
  if (result.taskType === "local_workflow" && status === "async_launched" && typeof result.taskId === "string"
130
156
  && typeof result.runId === "string" && /^wf_[A-Za-z0-9-]{1,64}$/.test(result.runId)) {
131
157
  const callId = String(blocks.find(b => b.type === "tool_result")?.tool_use_id ?? "");
@@ -146,14 +172,28 @@ async function claudeParentRows(file) {
146
172
  if (block.name === "TaskStop" && typeof block.id === "string" && typeof object(block.input).task_id === "string") {
147
173
  stops.set(block.id, String(object(block.input).task_id));
148
174
  }
149
- if (block.name !== "Agent")
175
+ if (block.name !== "Agent" && block.name !== "Task")
150
176
  continue;
151
177
  const input = object(block.input), name = String(input.name ?? "");
152
- if (!/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(name) || typeof block.id !== "string")
178
+ if (typeof block.id !== "string")
179
+ continue;
180
+ if (block.name === "Agent" && /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(name)) {
181
+ teammates.set(name, { path: String(input.description || name).slice(0, 200), callId: block.id.slice(0, 200), state: "running" });
153
182
  continue;
154
- teammates.set(name, { path: String(input.description || name).slice(0, 200), callId: block.id.slice(0, 200), state: "running" });
183
+ }
184
+ const call = { path: String(input.description || input.subagent_type || "Agent").slice(0, 200), callId: block.id.slice(0, 200),
185
+ prompt: typeof input.prompt === "string" ? input.prompt : "", ...(typeof raw.timestamp === "string" ? { at: raw.timestamp } : {}) };
186
+ (input.run_in_background === true ? background : foreground).set(call.callId, call);
155
187
  }
156
188
  }
189
+ // A call's result ends the parent's wait on it: the foreground agent finished, failed or was interrupted.
190
+ if (raw.type === "user")
191
+ for (const block of blocks) {
192
+ if (block.type !== "tool_result" || typeof block.tool_use_id !== "string")
193
+ continue;
194
+ foreground.delete(block.tool_use_id);
195
+ background.delete(block.tool_use_id);
196
+ }
157
197
  // A stop request alone proves nothing. Its successful, matching result
158
198
  // ends the child even when no later task notification is recorded.
159
199
  if (raw.type === "user") {
@@ -198,12 +238,23 @@ async function claudeParentRows(file) {
198
238
  }
199
239
  catch { /* Ignore unrelated/malformed rows. */ }
200
240
  }
201
- return { launches, skills, workflows, teammates };
241
+ return { launches, skills, workflows, teammates, foreground, unidentified };
202
242
  }
203
- async function claudeChildRelations(file, session, signature, rows) {
243
+ async function claudeChildRelations(file, session, signature, rows, stop) {
204
244
  // Kept as the parent wrote them: what follows marks finished children.
205
245
  const kept = copyRows(rows);
206
246
  const { launches, workflows, teammates } = copyRows(rows);
247
+ /** Whether a child the parent recorded no end for has ended: the latest Stop's word when it lists the
248
+ * child (running, or finished unless SendMessage resumed it since), else its own transcript (a finished
249
+ * reply, or quiet past the limit), counting only what it wrote after SendMessage last resumed it. */
250
+ const ended = async (agentId, childFile, launch) => {
251
+ if (stop?.running.includes(agentId))
252
+ return false;
253
+ const resumedSince = launch.resumedAt !== undefined && Date.parse(launch.resumedAt) > Date.parse(stop?.at ?? "");
254
+ if (stop?.finished.includes(agentId) && !resumedSince)
255
+ return true;
256
+ return claudeSkillFinished(childFile, launch.resumedAt).catch(() => false);
257
+ };
207
258
  const relations = [];
208
259
  // Claude Code records the launch in the parent before the child's own
209
260
  // file exists. A launch without a transcript yet is looked for again
@@ -220,9 +271,9 @@ async function claudeChildRelations(file, session, signature, rows) {
220
271
  continue;
221
272
  }
222
273
  // A skill never gets a notification, and any child loses its own when the
223
- // session that ran it was restarted or continued: its transcript decides.
274
+ // session that ran it was restarted or continued: the Stop, else its transcript, decides.
224
275
  if (launch.state === "running") {
225
- if (await claudeSkillFinished(childFile).catch(() => false))
276
+ if (await ended(agentId, childFile, launch))
226
277
  launch.state = "completed";
227
278
  else
228
279
  live = true;
@@ -260,7 +311,7 @@ async function claudeChildRelations(file, session, signature, rows) {
260
311
  // A teammate that never said it was idle or shut down (its session was
261
312
  // restarted or continued) ends the same way: a finished reply, or quiet.
262
313
  if (launch.state === "running") {
263
- if (await claudeSkillFinished(childFile).catch(() => false))
314
+ if (await ended(agentId, childFile, launch))
264
315
  launch.state = "completed";
265
316
  else
266
317
  live = true;
@@ -275,8 +326,13 @@ async function claudeChildRelations(file, session, signature, rows) {
275
326
  }
276
327
  if (workflows.size && root) {
277
328
  const seen = new Set(relations.map(relation => relation.session));
278
- for (const workflow of workflows.values()) {
279
- for (const child of await claudeWorkflowAgents(root, session, workflow)) {
329
+ for (const [taskId, workflow] of workflows) {
330
+ // A finished run whose notification never reached the parent: the Stop's word ends its agents.
331
+ if (workflow.state === "running" && stop?.finished.includes(taskId))
332
+ workflow.state = "completed";
333
+ // Once that Stop is gone (four hours on, or a newer Stop leaves the run out) a quiet agent ends,
334
+ // as a launched one does; a run the Stop lists as running keeps its quiet agents.
335
+ for (const child of await claudeWorkflowAgents(root, session, workflow, !stop?.running.includes(taskId))) {
280
336
  if (seen.has(child.session))
281
337
  continue;
282
338
  seen.add(child.session);
@@ -286,6 +342,50 @@ async function claudeChildRelations(file, session, signature, rows) {
286
342
  }
287
343
  }
288
344
  }
345
+ // A foreground call runs until its tool_result, which the parent writes when it ends: while the parent
346
+ // waits on it. A Stop after the call means the turn ended without one (the session went down mid-call).
347
+ // A background launch whose result named no agent is found the same way, by the prompt it sent.
348
+ if (rows.foreground.size || rows.unidentified.size) {
349
+ const claimed = new Set(relations.map(relation => relation.session));
350
+ const candidates = root ? await claudeSidechains(root, session, claimed) : [];
351
+ const parentQuiet = Date.now() - (await stat(file)).mtimeMs >= CLAUDE_SKILL_QUIET_MS;
352
+ const pastLimit = (at) => at !== undefined && Date.now() - Date.parse(at) >= CLAUDE_SKILL_QUIET_MS;
353
+ /** Its own transcript: of the unclaimed ones that began with its prompt, the first to start once it was
354
+ * made. An earlier call with the same prompt started before it; a later one, after its own. */
355
+ const ownOf = (call) => {
356
+ const since = call.at === undefined ? NaN : Date.parse(call.at) - CALL_START_SLACK_MS;
357
+ const own = call.prompt ? candidates.filter(candidate => candidate.prompt === call.prompt && !claimed.has(candidate.agentId)
358
+ && !(Number.isFinite(since) && candidate.startedMs < since)).sort((a, b) => a.startedMs - b.startedMs)[0] : undefined;
359
+ if (own)
360
+ claimed.add(own.agentId);
361
+ return own;
362
+ };
363
+ const push = async (call, own) => {
364
+ const model = own ? await claudeChildModel(own.file).catch(() => undefined) : undefined;
365
+ relations.push({ id: createHash("sha256").update(`claude\0${session}\0${own?.agentId ?? `call:${call.callId}`}`).digest("hex").slice(0, 32),
366
+ ...(own ? { session: own.agentId, transcript: own.file } : {}), provider: "claude", path: call.path, callId: call.callId, state: "running",
367
+ ...(model !== undefined ? { model } : {}), children: [] });
368
+ live = true;
369
+ if (!own)
370
+ awaiting = true;
371
+ };
372
+ for (const call of rows.foreground.values()) {
373
+ if (stop && call.at !== undefined && Date.parse(stop.at) > Date.parse(call.at))
374
+ continue;
375
+ const own = ownOf(call);
376
+ // A session gone mid-call leaves the call without a result: quiet past the limit, it has ended.
377
+ if (own ? Date.now() - own.mtimeMs >= CLAUDE_SKILL_QUIET_MS : parentQuiet)
378
+ continue;
379
+ await push(call, own);
380
+ }
381
+ for (const call of rows.unidentified.values()) {
382
+ const own = ownOf(call);
383
+ // With its transcript it ends as any launch does: the Stop's word, else a finished reply or quiet.
384
+ if (own ? await ended(own.agentId, own.file, { path: call.path, callId: call.callId, state: "running" }) : pastLimit(call.at))
385
+ continue;
386
+ await push(call, own);
387
+ }
388
+ }
289
389
  claudeRelationCache.set(file, { signature, relations, ...(awaiting || live ? { recheckAt: Date.now() + (awaiting ? 2_000 : 5_000), rows: kept } : {}) });
290
390
  while (claudeRelationCache.size > 64)
291
391
  claudeRelationCache.delete(claudeRelationCache.keys().next().value);
@@ -297,10 +397,12 @@ async function claudeChildRelations(file, session, signature, rows) {
297
397
  export const CLAUDE_SKILL_QUIET_MS = 30 * 60 * 1000;
298
398
  /** A background child (a skill, or a sub-agent or teammate whose end the
299
399
  * parent never recorded) is done once its transcript ends on a finished
300
- * reply, or has not changed for CLAUDE_SKILL_QUIET_MS. */
301
- async function claudeSkillFinished(file, now = Date.now()) {
302
- const metadata = await stat(file);
303
- if (now - metadata.mtimeMs >= CLAUDE_SKILL_QUIET_MS)
400
+ * reply, or has not changed for CLAUDE_SKILL_QUIET_MS. For a child resumed at
401
+ * `since`, the reply must be written after it and the quiet counts from it:
402
+ * the end_turn it finished on before the resume says nothing yet. */
403
+ async function claudeSkillFinished(file, since, now = Date.now()) {
404
+ const metadata = await stat(file), resumed = since === undefined ? NaN : Date.parse(since);
405
+ if (now - Math.max(metadata.mtimeMs, Number.isFinite(resumed) ? resumed : -Infinity) >= CLAUDE_SKILL_QUIET_MS)
304
406
  return true;
305
407
  const start = Math.max(0, metadata.size - 65_536), chunks = [];
306
408
  for await (const chunk of createReadStream(file, { start }))
@@ -308,12 +410,53 @@ async function claudeSkillFinished(file, now = Date.now()) {
308
410
  const last = Buffer.concat(chunks).toString("utf8").split("\n").filter(line => line.trim()).at(-1);
309
411
  try {
310
412
  const raw = object(JSON.parse(last ?? ""));
311
- return raw.type === "assistant" && object(raw.message).stop_reason === "end_turn";
413
+ if (raw.type !== "assistant" || object(raw.message).stop_reason !== "end_turn")
414
+ return false;
415
+ return !Number.isFinite(resumed) || (typeof raw.timestamp === "string" && Date.parse(raw.timestamp) > resumed);
312
416
  }
313
417
  catch {
314
418
  return false;
315
419
  }
316
420
  }
421
+ /** At most this many of a session's newest sub-agent transcripts are read to place a foreground call. */
422
+ const SIDECHAIN_SCAN = 64;
423
+ /** A call's transcript may be stamped this much before the parent's row for the call. */
424
+ const CALL_START_SLACK_MS = 2_000;
425
+ /** The session's sub-agent transcripts no relation claims yet, newest first, with the first message each
426
+ * was given: a foreground Agent call is found by the prompt it sent. */
427
+ async function claudeSidechains(root, session, claimed) {
428
+ const entries = (await readdir(root).catch(() => [])).filter(name => /^agent-[A-Za-z0-9._-]{1,128}\.jsonl$/.test(name));
429
+ const files = await Promise.all(entries.map(async (name) => {
430
+ const agentId = name.slice("agent-".length, -".jsonl".length);
431
+ if (claimed.has(agentId))
432
+ return undefined;
433
+ const file = await realpath(path.join(root, name)).catch(() => undefined);
434
+ const info = file?.startsWith(root + path.sep) ? await stat(file).catch(() => undefined) : undefined;
435
+ return file && info?.isFile() ? { agentId, file, mtimeMs: info.mtimeMs } : undefined;
436
+ }));
437
+ const newest = files.filter((entry) => !!entry).sort((a, b) => b.mtimeMs - a.mtimeMs).slice(0, SIDECHAIN_SCAN);
438
+ const read = [];
439
+ for (const entry of newest) {
440
+ if (!await claudeChildBelongsTo(entry.file, session, entry.agentId))
441
+ continue;
442
+ const input = createInterface({ input: createReadStream(entry.file, { start: 0, end: 1_048_575 }), crlfDelay: Infinity });
443
+ let prompt = "", startedMs = NaN;
444
+ for await (const line of input) {
445
+ try {
446
+ const row = object(JSON.parse(line)), content = object(row.message).content;
447
+ prompt = typeof content === "string" ? content : objects(content).filter(b => b.type === "text").map(b => String(b.text ?? "")).join("\n");
448
+ if (typeof row.timestamp === "string")
449
+ startedMs = Date.parse(row.timestamp);
450
+ }
451
+ catch { /* not a message row */ }
452
+ break;
453
+ }
454
+ input.close();
455
+ // When it started: its first row's stamp, else (an older file with none) its last write.
456
+ read.push({ ...entry, prompt, startedMs: Number.isFinite(startedMs) ? startedMs : entry.mtimeMs });
457
+ }
458
+ return read;
459
+ }
317
460
  /** Sub-agent files by the name their `.meta.json` gives them. */
318
461
  async function claudeChildNames(root, entries) {
319
462
  const names = new Map();
@@ -327,8 +470,9 @@ async function claudeChildNames(root, entries) {
327
470
  return names;
328
471
  }
329
472
  /** A Workflow run's agents from its journal: each `started` agent runs until
330
- * the journal records another row for it or the run itself finishes. */
331
- async function claudeWorkflowAgents(root, session, workflow) {
473
+ * the journal records another row for it or the run itself finishes, or, with
474
+ * `quietEnds`, its transcript sits unchanged for CLAUDE_SKILL_QUIET_MS. */
475
+ async function claudeWorkflowAgents(root, session, workflow, quietEnds = true, now = Date.now()) {
332
476
  const directory = await realpath(path.join(root, "workflows", workflow.runId)).catch(() => undefined);
333
477
  if (!directory || !directory.startsWith(root + path.sep))
334
478
  return [];
@@ -354,10 +498,12 @@ async function claudeWorkflowAgents(root, session, workflow) {
354
498
  const meta = await readFile(childFile.slice(0, -".jsonl".length) + ".meta.json", "utf8").then(v => object(JSON.parse(v))).catch(() => ({}));
355
499
  const model = await claudeChildModel(childFile).catch(() => undefined);
356
500
  const checkout = await claudeChildCheckout(childFile).catch(() => ({}));
501
+ const quiet = quietEnds && !done && workflow.state === "running"
502
+ && now - ((await stat(childFile).catch(() => undefined))?.mtimeMs ?? now) >= CLAUDE_SKILL_QUIET_MS;
357
503
  relations.push({ id: createHash("sha256").update(`claude\0${session}\0${agentId}`).digest("hex").slice(0, 32),
358
504
  session: agentId, transcript: childFile, provider: "claude",
359
505
  path: String(meta.description || workflow.name).slice(0, 200), callId: workflow.callId || `workflow:${workflow.runId}`,
360
- state: done || workflow.state === "completed" ? "completed" : "running",
506
+ state: done || quiet || workflow.state === "completed" ? "completed" : "running",
361
507
  ...(model !== undefined ? { model } : {}), ...checkout, children: [] });
362
508
  }
363
509
  return relations;
@@ -14,8 +14,10 @@ export interface TranscriptPreview {
14
14
  }
15
15
  export declare const PREVIEW_INTERVAL_MS = 500;
16
16
  /** Only the last Claude reply after the current prompt is eligible. A missing
17
- * prompt anchor is deliberately silent: scrollback could belong to an old turn. */
18
- export declare function claudePanePreview(rendered: string, prompt: string, previous?: string): string;
17
+ * prompt anchor is deliberately silent: scrollback could belong to an old turn,
18
+ * unless `inTurn` (the turn already landed an entry, so the screen is its own
19
+ * output and the prompt scrolled off above it). */
20
+ export declare function claudePanePreview(rendered: string, prompt: string, previous?: string, inTurn?: boolean): string;
19
21
  /** An unbulleted tool-group summary line, e.g. " Read 1 file, ran 1 shell command". */
20
22
  export declare function claudeToolSummary(line: string): boolean;
21
23
  /**
@@ -86,7 +88,11 @@ export declare class TranscriptPreviewStream {
86
88
  private readonly delta;
87
89
  private startedAt?;
88
90
  private prompt;
91
+ /** Claude: the turn landed an entry (a reply block, a tool call or result). */
89
92
  private landed;
93
+ /** Claude: the turn's reply text blocks that landed as entries, compared by their words. The pane keeps
94
+ * showing a landed block until a newer one is drawn, so only a block not among these is previewed. */
95
+ private readonly landedTexts;
90
96
  private ended;
91
97
  /** Claude's own spinner word for the running turn, sent beside frames as
92
98
  * `activityVerb` for older phones. */
@@ -106,6 +112,9 @@ export declare class TranscriptPreviewStream {
106
112
  private readonly rollout;
107
113
  constructor(target: Target, pane?: () => Promise<string>, delta?: (file?: string) => Promise<TranscriptPreview | null>);
108
114
  observe(entries: Entry[], reset?: boolean): void;
115
+ /** Whether pane text is a reply block that already landed: its words agree with the block's as far as
116
+ * both go (drawsLanded), so a block still drawing the same opening as a landed one waits until the two part. */
117
+ private hasLanded;
109
118
  update(status: unknown, file?: string, now?: number): Promise<{
110
119
  preview: TranscriptPreview | null;
111
120
  } | undefined>;
@@ -12,8 +12,10 @@ const MAX_TEXT = 32_768;
12
12
  // A JSON-escaped UTF-16 code unit takes at most six bytes, plus metadata.
13
13
  const MAX_PREVIEW_BYTES = MAX_TEXT * 6 + 1_024;
14
14
  /** Only the last Claude reply after the current prompt is eligible. A missing
15
- * prompt anchor is deliberately silent: scrollback could belong to an old turn. */
16
- export function claudePanePreview(rendered, prompt, previous = "") {
15
+ * prompt anchor is deliberately silent: scrollback could belong to an old turn,
16
+ * unless `inTurn` (the turn already landed an entry, so the screen is its own
17
+ * output and the prompt scrolled off above it). */
18
+ export function claudePanePreview(rendered, prompt, previous = "", inTurn = false) {
17
19
  const screen = rendered.split("\n");
18
20
  const raw = screen.map(stripTerminal);
19
21
  // What the phone shows: the line with Claude's bold as Markdown. Detection
@@ -38,11 +40,29 @@ export function claudePanePreview(rendered, prompt, previous = "") {
38
40
  }
39
41
  // Once anchored, a reply can scroll its prompt off screen. Extend only
40
42
  // through a matching text overlap; unrelated terminal lines cannot replace it.
43
+ // In the turn but not anchored (its prompt scrolled off, or drawn otherwise than written, as "/review" or a
44
+ // pasted-text placeholder): the newest prompt row with turn output under it (a block, the spinner, thinking)
45
+ // is this turn's, and everything above it is an older turn. The composer and a permission dialog's
46
+ // options have none under them.
47
+ if (start < 0 && inTurn && !previous) {
48
+ const output = (line) => /^\s*[⏺●✻✽✶✢✳✦·∴⠁-⣿]/u.test(line) || !!parseClaudeSpinnerLine(line);
49
+ for (let i = lines.length - 1; i >= 0; i--) {
50
+ if (!/^\s*[❯>]\s*\S/.test(lines[i]) || !lines.slice(i + 1).some(output))
51
+ continue;
52
+ // Nothing written under this turn's prompt yet: no reply to show.
53
+ if (!lines.slice(i + 1).some(line => /^\s*[⏺●]/.test(line)))
54
+ return "";
55
+ start = i + 1;
56
+ break;
57
+ }
58
+ }
41
59
  const scrolled = start < 0;
42
- if (scrolled && !previous)
60
+ if (scrolled && !previous && !inTurn)
43
61
  return "";
44
62
  const reply = [], shown = [];
45
- let writing = scrolled;
63
+ // Scrolled past its ⏺, a reply already previewed continues from the top; without one, the top of the
64
+ // screen may be tool output, so only a ⏺ text block starts a reply.
65
+ let writing = scrolled && !!previous;
46
66
  const body = lines.slice(Math.max(0, start)), rawBody = raw.slice(Math.max(0, start)), markedBody = marked.slice(Math.max(0, start));
47
67
  // A "⏺" block whose next line is a "⎿" result is a tool call, collapsed
48
68
  // ("⏺ Running 1 shell command…") or not; it lands as its own entry.
@@ -384,6 +404,44 @@ export async function readDeltaPreview(target, file, rollout) {
384
404
  return null;
385
405
  }
386
406
  }
407
+ /** A landed block shorter than this many letters and digits is not a longer pane block that starts with it. */
408
+ const LANDED_MATCH_CHARS = 40;
409
+ /** A reply's words alone, for comparing what the pane draws with what landed: the Markdown Claude draws
410
+ * otherwise (code fences and their language, list markers and numbers, link targets) is left out. */
411
+ function previewWords(text) {
412
+ return text.split("\n").filter(line => !/^\s*(?:```|~~~)/.test(line))
413
+ .map(line => line.replace(/^\s*(?:\d+[.)]|[-*+•])\s+/, "").replace(/\[([^\]]*)\]\([^)]*\)/g, "$1")).join("\n")
414
+ .replace(/[^\p{L}\p{N}]+/gu, "").toLowerCase();
415
+ }
416
+ /** The pane's words may miss a few stretches of a landed block's: a row taken for Claude's chrome ("Tip: …",
417
+ * a `ctrl+` key), or a number a wrap put at a row's start, taken for a list marker. */
418
+ const LANDED_GAPS = 4, LANDED_GAP_CHARS = 200, LANDED_RESYNC_CHARS = 16;
419
+ /** Whether pane words agree with a landed block's as far as both go, but for at most LANDED_GAPS stretches
420
+ * of the landed block's missing from the pane: a number, or up to LANDED_GAP_CHARS after which the pane's
421
+ * next LANDED_RESYNC_CHARS follow on. Fewer than those left on the pane is a block of its own. */
422
+ function drawsLanded(words, landed) {
423
+ let at = 0, from = 0, gaps = 0;
424
+ while (at < words.length && from < landed.length) {
425
+ if (words[at] === landed[from]) {
426
+ at++;
427
+ from++;
428
+ continue;
429
+ }
430
+ if (++gaps > LANDED_GAPS)
431
+ return false;
432
+ if (/\d/.test(landed[from])) {
433
+ while (/\d/.test(landed[from] ?? ""))
434
+ from++;
435
+ continue;
436
+ }
437
+ const next = words.slice(at, at + LANDED_RESYNC_CHARS);
438
+ const skip = next.length < LANDED_RESYNC_CHARS ? -1 : landed.indexOf(next, from + 1);
439
+ if (skip < 0 || skip - from > LANDED_GAP_CHARS)
440
+ return false;
441
+ from = skip;
442
+ }
443
+ return true;
444
+ }
387
445
  /** Socket-local, ephemeral state. It never writes transcript rows or advances
388
446
  * the history cursor. Final rows bypass the text throttle and clear atomically. */
389
447
  export class TranscriptPreviewStream {
@@ -392,7 +450,11 @@ export class TranscriptPreviewStream {
392
450
  delta;
393
451
  startedAt;
394
452
  prompt = "";
453
+ /** Claude: the turn landed an entry (a reply block, a tool call or result). */
395
454
  landed = false;
455
+ /** Claude: the turn's reply text blocks that landed as entries, compared by their words. The pane keeps
456
+ * showing a landed block until a newer one is drawn, so only a block not among these is previewed. */
457
+ landedTexts = new Set();
396
458
  ended = false;
397
459
  /** Claude's own spinner word for the running turn, sent beside frames as
398
460
  * `activityVerb` for older phones. */
@@ -420,6 +482,7 @@ export class TranscriptPreviewStream {
420
482
  this.observedLine = -1;
421
483
  this.startedAt = undefined;
422
484
  this.landed = false;
485
+ this.landedTexts.clear();
423
486
  this.ended = false;
424
487
  this.wasWorking = false;
425
488
  this.completed.clear();
@@ -494,6 +557,7 @@ export class TranscriptPreviewStream {
494
557
  this.startedAt = raw.timestamp;
495
558
  this.prompt = prompt;
496
559
  this.landed = false;
560
+ this.landedTexts.clear();
497
561
  this.ended = false;
498
562
  this.wasWorking = false;
499
563
  this.verb = undefined;
@@ -509,10 +573,26 @@ export class TranscriptPreviewStream {
509
573
  this.verb = undefined;
510
574
  this.activity = undefined;
511
575
  }
512
- else if (this.startedAt && (raw.type === "assistant" || blocks.some(b => b.type === "tool_result")))
576
+ else if (this.startedAt && (raw.type === "assistant" || blocks.some(b => b.type === "tool_result"))) {
513
577
  this.landed = true;
578
+ if (raw.type === "assistant") {
579
+ const texts = typeof message.content === "string" ? [message.content] : blocks.filter(b => b.type === "text").map(b => String(b.text ?? ""));
580
+ for (const text of texts.map(previewWords).filter(Boolean))
581
+ this.landedTexts.add(text);
582
+ while (this.landedTexts.size > 64)
583
+ this.landedTexts.delete(this.landedTexts.values().next().value);
584
+ }
585
+ }
514
586
  }
515
587
  }
588
+ /** Whether pane text is a reply block that already landed: its words agree with the block's as far as
589
+ * both go (drawsLanded), so a block still drawing the same opening as a landed one waits until the two part. */
590
+ hasLanded(text) {
591
+ const words = previewWords(text);
592
+ return !words || [...this.landedTexts].some(landed =>
593
+ // A short block ("Let me check.") is not a longer one that starts with its words.
594
+ !(landed.length < LANDED_MATCH_CHARS && words.length > landed.length) && drawsLanded(words, landed));
595
+ }
516
596
  async update(status, file, now) {
517
597
  const readAt = now ?? Date.now();
518
598
  let next = null;
@@ -533,10 +613,12 @@ export class TranscriptPreviewStream {
533
613
  if (readAt - this.lastRead < PREVIEW_INTERVAL_MS)
534
614
  return undefined;
535
615
  this.lastRead = readAt;
536
- // The reply text stops once a real entry lands; Claude's spinner
537
- // verb keeps naming the work until the turn ends.
616
+ // A reply block stops once it lands as an entry; the next one written after a tool or thinking
617
+ // previews in turn. Claude's spinner verb keeps naming the work until the turn ends.
538
618
  const pane = await this.pane();
539
- const text = this.landed ? "" : claudePanePreview(pane, this.prompt, this.current?.turnStartedAt === this.startedAt ? this.current.text : "");
619
+ let text = claudePanePreview(pane, this.prompt, this.current?.turnStartedAt === this.startedAt ? this.current.text : "", this.landed);
620
+ if (text && this.hasLanded(text))
621
+ text = "";
540
622
  const spinner = claudeSpinner(pane);
541
623
  if (spinner) {
542
624
  this.activity = spinner;
@@ -2,6 +2,8 @@ import { z } from "zod";
2
2
  import { type Provider } from "./protocol.js";
3
3
  /** Longest final reply kept from a Stop payload, in UTF-8 bytes (the receipt's limit). */
4
4
  export declare const TURN_REPLY_LIMIT = 4000;
5
+ /** Most background tasks a record keeps from one Stop, running ones first. */
6
+ export declare const STOP_TASKS_LIMIT = 256;
5
7
  declare const turnRecordSchema: z.ZodObject<{
6
8
  terminal: z.ZodString;
7
9
  source: z.ZodEnum<{
@@ -26,6 +28,11 @@ declare const turnRecordSchema: z.ZodObject<{
26
28
  reply: z.ZodOptional<z.ZodString>;
27
29
  truncated: z.ZodOptional<z.ZodBoolean>;
28
30
  cwd: z.ZodOptional<z.ZodString>;
31
+ tasks: z.ZodOptional<z.ZodObject<{
32
+ running: z.ZodArray<z.ZodString>;
33
+ finished: z.ZodArray<z.ZodString>;
34
+ truncated: z.ZodOptional<z.ZodBoolean>;
35
+ }, z.core.$strip>>;
29
36
  }, z.core.$strip>>;
30
37
  at: z.ZodString;
31
38
  }, z.core.$strip>;
@@ -41,6 +48,8 @@ export interface TurnEvent {
41
48
  start?: string;
42
49
  /** Stop only: the harness's count of in-flight background tasks, when it reports one. */
43
50
  background?: number;
51
+ /** Stop only: the background tasks it listed, `{id, running}` each (validated here). */
52
+ backgroundTasks?: unknown;
44
53
  /** Stop only: the harness's last assistant message, when it reports one. */
45
54
  reply?: string;
46
55
  /** Stop only: the agent's working directory, as its hook payload names it. */
@@ -83,6 +92,16 @@ export declare function backgroundLeft(count: number | undefined, stoppedAt: str
83
92
  export declare function noteTurn(server: string, pane: string, event: TurnEvent): Promise<TurnRecord | undefined>;
84
93
  /** The recorded turns of `pane`'s latest conversation, if its hooks reported any. */
85
94
  export declare function readTurn(server: string, pane: string): Promise<TurnRecord | undefined>;
95
+ export interface StopTasks {
96
+ seq: number;
97
+ at: string;
98
+ running: string[];
99
+ finished: string[];
100
+ truncated?: boolean;
101
+ }
102
+ /** The background tasks the latest Stop of conversation `session` listed, from whichever pane's record
103
+ * holds it (the child tree knows the conversation, not its pane); undefined when no Stop listed any. */
104
+ export declare function latestStopTasks(source: Provider, session: string): Promise<StopTasks | undefined>;
86
105
  /** OpenCode's turns for a pane running `pids`, from the stamps phren's OpenCode
87
106
  * plugin writes on session.status busy / session.idle; undefined for an older
88
107
  * plugin that writes none. `terminal` is the pane's, since the PIDs are. */