@operad-io/chat 0.1.1 → 0.2.0

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.
package/src/views.ts CHANGED
@@ -1,21 +1,27 @@
1
1
  /** How a chat shows in a list and on its page: a row and a transcript. */
2
2
 
3
- import { attachmentUrl, decodeCursor, encodeCursor } from "@operad-io/engine";
3
+ import { attachmentDir, attachmentUrl, decodeCursor, DEFAULT_SECTION_CAP_BYTES, encodeCursor, formatElapsed, isRecord, parseObjectId } from "@operad-io/engine";
4
4
  import type {
5
+ JsonValue,
5
6
  ObjectRef,
6
7
  ObjectRow,
7
8
  ObjectViews,
8
9
  PluginFact,
9
10
  SectionContent,
10
11
  SectionPage,
12
+ SectionRetry,
13
+ SectionStatus,
11
14
  StoredObject,
12
15
  ViewContext,
13
16
  ViewSection,
14
17
  } from "@operad-io/engine";
15
- import { maskSecrets } from "@operad-io/harness-process";
18
+ import { join } from "node:path";
19
+ import { maskSecrets, type FoldEntry } from "@operad-io/harness-process";
16
20
  import { secretValues } from "./reply.ts";
21
+ import { readChatSkills, skillSummaries, type ObjectReader } from "./skills.ts";
17
22
  import { foldLogTail, agentLogPath } from "./tail.ts";
18
- import { agentLine, attachmentsOf, chatData, chatRef, ENTRY_FACT, entryOfFact, IMAGE_TYPES, latestRunOf, MESSAGE_FACT, modelAndCost, type Attachment, type Entry, type Message } from "./model.ts";
23
+ import { agentLine, answeredOfFact, attachmentsOf, CHAT_TYPE, chatData, chatRef, COMMAND_FACT, commandOfFact, ENTRY_FACT, entryOfFact, factsOf, IMAGE_TYPES, lastReplyContext, latestRunOf, MESSAGE_CHANGE_FACT, MESSAGE_FACT, messageChangeOfFact, messageFactsInForce, modelAndCost, queuedData, queuedMessages, queuedOf, readChat, RUN_FACT, stopOfFact, timingsOf, unanswered, ANSWER_FACT, type Attachment, type ChatContext, type ChatRead, type Command, type Entry, type Message, type MessageChange, type ToolResult } from "./model.ts";
24
+ import type { TailRead } from "./tail.ts";
19
25
 
20
26
  /** How many messages of a chat one page of the transcript holds. */
21
27
  export const TRANSCRIPT_PAGE = 50;
@@ -28,13 +34,25 @@ export const TRANSCRIPT = "transcript";
28
34
 
29
35
  function row(object: StoredObject): ObjectRow {
30
36
  const chat = chatData(object.data);
37
+ const note = [
38
+ ...(chat.harness.length > 0 ? [agentLine(chat)] : []),
39
+ ...(chat.accessLevel !== chat.accessDefault ? [chat.accessLevel ?? ""] : []),
40
+ ].filter((part) => part.length > 0);
41
+ const queued = queuedOf(object.data.queued);
42
+ const data: Record<string, JsonValue> = {
43
+ ...(chat.scheduled === undefined ? {} : { scheduled: chat.scheduled }),
44
+ ...(queued.length === 0
45
+ ? {}
46
+ : { queued: queued as unknown as JsonValue, queuedCount: queued.length }),
47
+ };
31
48
  return {
32
49
  id: object.id,
33
50
  title: chat.title.length > 0 ? chat.title : object.id,
34
51
  state: chat.closed ? "closed" : "open",
35
- ...(chat.harness.length > 0 ? { note: agentLine(chat) } : {}),
52
+ ...(note.length === 0 ? {} : { note: note.join(" · ") }),
36
53
  ...(chat.closed ? { final: true } : {}),
37
54
  ...(typeof chat.parent === "string" && chat.parent.length > 0 ? { parent: chat.parent } : {}),
55
+ ...(Object.keys(data).length === 0 ? {} : { data }),
38
56
  };
39
57
  }
40
58
 
@@ -42,10 +60,27 @@ function sections(): readonly ViewSection[] {
42
60
  return [{ id: TRANSCRIPT, title: "Transcript", live: true }];
43
61
  }
44
62
 
63
+ /** The context the chat's detail page and transcript show: its last finished reply's. */
64
+ function chatContext(object: StoredObject, read: ChatRead): ChatContext | undefined {
65
+ return lastReplyContext(chatData(object.data), read.messages);
66
+ }
67
+
45
68
  function minute(at: number): string {
46
69
  return new Date(at).toISOString().slice(0, 16).replace("T", " ");
47
70
  }
48
71
 
72
+ /** One command as a transcript entry: who, the command and how it went. */
73
+ export function commandMarkdown(command: Command): string {
74
+ const via = command.from.via.length > 0 ? ` via ${command.from.via}` : "";
75
+ return `**you**${via} · ${minute(command.at)} — \`${command.command.replace(/`/g, "\\`")}\`\n\n${command.outcome}`;
76
+ }
77
+
78
+ /** One withdrawn message as the history entry that says what happened to it. */
79
+ export function withdrawalMarkdown(change: MessageChange): string {
80
+ const via = change.by.via.length > 0 ? ` via ${change.by.via}` : "";
81
+ return `**you**${via} · ${minute(change.at)} — \`withdraw ${change.id}\`\n\nThe message was withdrawn and was not sent to the agent.`;
82
+ }
83
+
49
84
  /** A path as a Markdown link destination: spaces and parentheses are escaped. */
50
85
  function destination(path: string, home: string | undefined): string {
51
86
  // A client fetches the file from the server, so the link is the server's attachment address.
@@ -77,14 +112,14 @@ export function messageMarkdown(message: Message, speaker: string = DEFAULT_SPEA
77
112
  * It is read at every draw, so a changed name shows on the messages already
78
113
  * recorded too.
79
114
  */
80
- async function speakerOf(ctx: ViewContext, object: StoredObject): Promise<string> {
115
+ async function speakerOf(ctx: ViewContext, object: StoredObject, refresh = false): Promise<string> {
81
116
  const parent = chatData(object.data).parent;
82
117
  if (parent !== undefined) {
83
- const at = parent.indexOf(":");
84
- if (at > 0 && at < parent.length - 1) {
85
- const owner = ctx.refreshedObject === undefined
86
- ? await ctx.store.get(parent.slice(0, at), parent.slice(at + 1))
87
- : await ctx.refreshedObject(parent.slice(0, at), parent.slice(at + 1));
118
+ const ref = parseObjectId(parent);
119
+ if (ref !== undefined) {
120
+ const owner = refresh && ctx.refreshedObject !== undefined
121
+ ? await ctx.refreshedObject(ref.type, ref.id)
122
+ : await ctx.store.get(ref.type, ref.id);
88
123
  const speaker = owner?.data.speaker;
89
124
  if (typeof speaker === "string" && speaker.length > 0) return speaker;
90
125
  }
@@ -104,11 +139,16 @@ function messageFrom(fact: {
104
139
  const data = fact.data;
105
140
  if (typeof data.id !== "string" || typeof data.text !== "string") return undefined;
106
141
  if (data.role !== "user" && data.role !== "assistant") return undefined;
142
+ const from = isRecord(data.from) ? data.from : {};
107
143
  const source = typeof data.source === "object" && data.source !== null ? (data.source as Record<string, unknown>) : {};
144
+ const timings = timingsOf(data.timings);
108
145
  return {
109
146
  id: data.id,
110
147
  role: data.role,
111
- from: { via: "", id: "" },
148
+ from: {
149
+ via: typeof from.via === "string" ? from.via : "",
150
+ id: typeof from.id === "string" ? from.id : "",
151
+ },
112
152
  text: data.text,
113
153
  attachments: attachmentsOf(data.attachments),
114
154
  source: {
@@ -117,26 +157,28 @@ function messageFrom(fact: {
117
157
  },
118
158
  ...(typeof data.runId === "string" && data.runId.length > 0 ? { runId: data.runId } : {}),
119
159
  ...(typeof data.model === "string" && data.model.length > 0 ? { model: data.model } : {}),
160
+ ...(timings === undefined ? {} : { timings }),
120
161
  ...(typeof data.costMicros === "number" && Number.isFinite(data.costMicros) ? { costMicros: data.costMicros } : {}),
121
162
  ...(data.costQuality === "exact" || data.costQuality === "estimated" || data.costQuality === "incomplete"
122
163
  ? { costQuality: data.costQuality }
123
164
  : {}),
165
+ ...(Array.isArray(data.replyTo)
166
+ ? { replyTo: data.replyTo.filter((id): id is string => typeof id === "string") }
167
+ : {}),
124
168
  at: fact.at,
125
169
  sequence: fact.sequence,
126
170
  };
127
171
  }
128
172
 
129
- function seconds(ms: number): string {
130
- if (ms < 1000) return "<1s";
131
- const total = Math.round(ms / 1000);
132
- const minutes = Math.floor(total / 60);
133
- return minutes === 0 ? `${total}s` : `${minutes}m${String(total % 60).padStart(2, "0")}s`;
134
- }
135
-
136
173
  function flat(text: string): string {
137
174
  return text.replace(/\s+/g, " ").trim();
138
175
  }
139
176
 
177
+ /** Text as a Markdown block: its lines stay, only the space around them goes. */
178
+ function block(text: string): string {
179
+ return text.replace(/\r\n/g, "\n").trim();
180
+ }
181
+
140
182
  function inlineCode(text: string): string {
141
183
  const longest = Math.max(0, ...(text.match(/`+/g) ?? []).map((run) => run.length));
142
184
  const fence = "`".repeat(longest + 1);
@@ -148,10 +190,19 @@ function firstLine(text: string | null | undefined): string | undefined {
148
190
  return line === undefined || line.length === 0 ? undefined : line;
149
191
  }
150
192
 
193
+ /** What a tool line shows, whether it comes from a fact or from the log. */
194
+ interface ShownTool {
195
+ readonly toolName?: string | undefined;
196
+ readonly durationMs?: number | undefined;
197
+ readonly input?: string | null | undefined;
198
+ readonly result?: string | undefined;
199
+ readonly error?: string | null | undefined;
200
+ }
201
+
151
202
  /** One tool call as a log line: what ran, how long it took and how it ended. */
152
- function toolMarkdown(entry: Entry): string {
203
+ function toolMarkdown(entry: ShownTool): string {
153
204
  const name = entry.toolName ?? "tool";
154
- const took = entry.durationMs === undefined ? "" : ` ${seconds(entry.durationMs)}`;
205
+ const took = entry.durationMs === undefined ? "" : ` ${formatElapsed(entry.durationMs)}`;
155
206
  const input = entry.input === undefined || entry.input === null ? "" : flat(entry.input);
156
207
  const what = input.length === 0 ? "" : ` ${inlineCode(input.length <= 160 ? input : `${input.slice(0, 159)}…`)}`;
157
208
  const head = `tool ${name}${took}${what}`;
@@ -167,8 +218,477 @@ function toolMarkdown(entry: Entry): string {
167
218
  return head;
168
219
  }
169
220
 
221
+ /** What a process group did: category ids, never sentences; a client words them. */
222
+ export const PROCESS_CATEGORIES = ["read", "edit", "run", "search", "other"] as const;
223
+
224
+ export type ProcessCategory = (typeof PROCESS_CATEGORIES)[number];
225
+
226
+ /** One message of a reply's input or answer. */
227
+ export interface ReplyMessage {
228
+ readonly id: string;
229
+ readonly text: string;
230
+ /** When it was recorded, in milliseconds since the epoch. */
231
+ readonly at: number;
232
+ }
233
+
234
+ /** The recorded start of a tool call's output and how many lines it has. */
235
+ export interface ReplyOutput {
236
+ /** The recorded output, its first 4 KB at most; empty when it printed nothing. */
237
+ readonly text: string;
238
+ /** How many lines the recorded output has; a final newline adds no empty line. */
239
+ readonly lines: number;
240
+ /** The server address of the file that holds the whole output, when it was longer than 4 KB. */
241
+ readonly url?: string | undefined;
242
+ /** Whether the recorded output was cut; `url` then holds the rest. */
243
+ readonly truncated?: true | undefined;
244
+ }
245
+
246
+ export interface ReplyThinkingItem {
247
+ readonly kind: "thinking";
248
+ readonly text: string;
249
+ readonly at?: number | undefined;
250
+ }
251
+
252
+ export interface ReplyTextItem {
253
+ readonly kind: "text";
254
+ readonly text: string;
255
+ readonly at?: number | undefined;
256
+ }
257
+
258
+ export interface ReplyToolItem {
259
+ readonly kind: "tool";
260
+ readonly callId: string;
261
+ readonly name: string;
262
+ readonly input: string | null;
263
+ /** When the call started; absent for a call whose log had no start line. */
264
+ readonly at?: number | undefined;
265
+ /** Absent while the call is still running. */
266
+ readonly durationMs?: number | undefined;
267
+ readonly failed: boolean;
268
+ /** Absent while the call is still running. */
269
+ readonly result?: ToolResult | undefined;
270
+ readonly output: ReplyOutput;
271
+ }
272
+
273
+ export type ReplyItem = ReplyThinkingItem | ReplyTextItem | ReplyToolItem;
274
+
275
+ /** The thinking and tool calls one turn did, with the categories they fall in. */
276
+ export interface ReplyProcess {
277
+ readonly categories: readonly ProcessCategory[];
278
+ readonly items: readonly ReplyItem[];
279
+ }
280
+
281
+ /** One reply: its input, its process grouped per turn, and its answer when it finished. */
282
+ export interface ReplyBlock {
283
+ readonly runId: string;
284
+ readonly input: readonly ReplyMessage[];
285
+ readonly process: readonly ReplyProcess[];
286
+ readonly answer?: ReplyMessage | undefined;
287
+ /** How long the reply took, when its harness reported the timings. */
288
+ readonly durationMs?: number | undefined;
289
+ }
290
+
291
+ /** The category a tool name falls in. */
292
+ export function toolCategory(name: string): ProcessCategory {
293
+ const lower = name.toLowerCase();
294
+ if (["read", "ls", "notebookread"].includes(lower)) return "read";
295
+ if (["write", "edit", "multiedit", "notebookedit"].includes(lower)) return "edit";
296
+ if (["bash", "shell", "shell_command", "command", "terminal", "exec", "run"].includes(lower)) return "run";
297
+ if (["grep", "glob", "search", "websearch", "webfetch", "find"].includes(lower)) return "search";
298
+ return "other";
299
+ }
300
+
301
+ function lineCount(text: string): number {
302
+ const clean = text.replace(/\r\n/g, "\n").replace(/\n+$/, "");
303
+ return clean.length === 0 ? 0 : clean.split("\n").length;
304
+ }
305
+
306
+ function replyOutput(
307
+ text: string | null | undefined,
308
+ path: string | undefined,
309
+ truncated: boolean | undefined,
310
+ home: string | undefined,
311
+ ): ReplyOutput {
312
+ const said = text ?? "";
313
+ const url = path === undefined || home === undefined ? undefined : attachmentUrl(home, path);
314
+ return {
315
+ text: said,
316
+ lines: lineCount(said),
317
+ ...(url === undefined ? {} : { url }),
318
+ ...(truncated === true ? { truncated: true as const } : {}),
319
+ };
320
+ }
321
+
322
+ function replyItemOfEntry(entry: Entry, home: string | undefined): ReplyItem | undefined {
323
+ if (entry.kind === "tool") {
324
+ return {
325
+ kind: "tool",
326
+ callId: entry.callId ?? "",
327
+ name: entry.toolName ?? "tool",
328
+ input: entry.input ?? null,
329
+ ...(typeof entry.startedAt === "number" ? { at: entry.startedAt } : {}),
330
+ ...(entry.durationMs === undefined ? {} : { durationMs: entry.durationMs }),
331
+ failed: entry.result === "failed",
332
+ result: entry.result,
333
+ output: replyOutput(entry.output, entry.outputPath, entry.outputTruncated || entry.outputPath !== undefined, home),
334
+ };
335
+ }
336
+ if (entry.kind !== "text" && entry.kind !== "thinking") return undefined;
337
+ const text = entry.text?.trim();
338
+ if (text === undefined || text.length === 0) return undefined;
339
+ return {
340
+ kind: entry.kind,
341
+ text,
342
+ ...(typeof entry.startedAt === "number" ? { at: entry.startedAt } : {}),
343
+ };
344
+ }
345
+
346
+ function replyItemOfFold(entry: FoldEntry, secrets: readonly string[]): ReplyItem | undefined {
347
+ if (entry.kind === "tool") {
348
+ return {
349
+ kind: "tool",
350
+ callId: maskSecrets(entry.callId, secrets),
351
+ name: maskSecrets(entry.toolName, secrets),
352
+ input: entry.input === null ? null : maskSecrets(entry.input, secrets),
353
+ ...(entry.at === null ? {} : { at: entry.at }),
354
+ durationMs: entry.durationMs,
355
+ failed: entry.result === "failed",
356
+ result: entry.result,
357
+ output: replyOutput(
358
+ entry.output === null ? null : maskSecrets(entry.output, secrets),
359
+ undefined,
360
+ entry.outputTruncated,
361
+ undefined,
362
+ ),
363
+ };
364
+ }
365
+ const text = maskSecrets(entry.text, secrets).trim();
366
+ if (text.length === 0) return undefined;
367
+ return {
368
+ kind: entry.kind,
369
+ text,
370
+ ...(entry.at === undefined ? {} : { at: entry.at }),
371
+ };
372
+ }
373
+
374
+ function replyItemOfOpenCall(
375
+ call: { readonly callId: string; readonly toolName: string; readonly input: string | null; readonly at: number; readonly output: string | null; readonly outputTruncated: boolean },
376
+ secrets: readonly string[],
377
+ ): ReplyToolItem {
378
+ return {
379
+ kind: "tool",
380
+ callId: maskSecrets(call.callId, secrets),
381
+ name: maskSecrets(call.toolName, secrets),
382
+ input: call.input === null ? null : maskSecrets(call.input, secrets),
383
+ at: call.at,
384
+ failed: false,
385
+ output: replyOutput(
386
+ call.output === null ? null : maskSecrets(call.output, secrets),
387
+ undefined,
388
+ call.outputTruncated,
389
+ undefined,
390
+ ),
391
+ };
392
+ }
393
+
394
+ function addCategory(categories: ProcessCategory[], name: string): void {
395
+ const category = toolCategory(name);
396
+ if (!categories.includes(category)) categories.push(category);
397
+ }
398
+
399
+ interface OpenGroups {
400
+ readonly groups: { readonly categories: ProcessCategory[]; readonly items: ReplyItem[] }[];
401
+ categories: ProcessCategory[];
402
+ items: ReplyItem[];
403
+ }
404
+
405
+ function openGroups(): OpenGroups {
406
+ return { groups: [], categories: [], items: [] };
407
+ }
408
+
409
+ function closeGroup(state: OpenGroups): void {
410
+ if (state.items.length > 0) state.groups.push({ categories: state.categories, items: state.items });
411
+ state.categories = [];
412
+ state.items = [];
413
+ }
414
+
415
+ function appendItem(state: OpenGroups, item: ReplyItem): void {
416
+ state.items.push(item);
417
+ if (item.kind === "tool") addCategory(state.categories, item.name);
418
+ }
419
+
420
+ /** The process of one turn's facts, split where a message the reply took arrived. */
421
+ function processOf(chunk: Chunk, home: string | undefined, extra: readonly ReplyItem[] = []): readonly ReplyProcess[] {
422
+ const events: { readonly at?: number | undefined; readonly order: number; readonly message?: Message; readonly item?: ReplyItem }[] = [];
423
+ for (const fact of turnFacts(chunk.facts)) {
424
+ const message = fact.type === MESSAGE_FACT ? messageFrom(fact) : undefined;
425
+ if (message?.role === "user") {
426
+ events.push({ at: shownAt(fact), order: events.length, message });
427
+ continue;
428
+ }
429
+ if (fact.type !== ENTRY_FACT) continue;
430
+ const entry = entryOfFact(fact);
431
+ const item = entry === undefined ? undefined : replyItemOfEntry(entry, home);
432
+ if (item !== undefined) events.push({ ...(item.at === undefined ? {} : { at: item.at }), order: events.length, item });
433
+ }
434
+ // The log's unfinished items follow the facts; their times put them before a
435
+ // message that arrived while the reply was still writing.
436
+ for (const item of extra) events.push({ ...(item.at === undefined ? {} : { at: item.at }), order: events.length, item });
437
+ if (extra.length > 0) {
438
+ const times = events.flatMap((event) => (event.at === undefined ? [] : [event.at]));
439
+ const fallback = times.length === 0 ? Number.MAX_SAFE_INTEGER : Math.max(...times);
440
+ events.sort(
441
+ (left, right) => (left.at ?? fallback) - (right.at ?? fallback) || left.order - right.order,
442
+ );
443
+ }
444
+ const state = openGroups();
445
+ for (const event of events) {
446
+ if (event.message !== undefined) closeGroup(state);
447
+ else if (event.item !== undefined) appendItem(state, event.item);
448
+ }
449
+ closeGroup(state);
450
+ return state.groups;
451
+ }
452
+
453
+ function processOfItems(items: readonly ReplyItem[]): readonly ReplyProcess[] {
454
+ if (items.length === 0) return [];
455
+ const state = openGroups();
456
+ for (const item of items) appendItem(state, item);
457
+ closeGroup(state);
458
+ return state.groups;
459
+ }
460
+
461
+ function replyMessage(message: Message): ReplyMessage {
462
+ return { id: message.id, text: message.text, at: message.at };
463
+ }
464
+
465
+ function messagesInTime(messages: readonly Message[]): readonly ReplyMessage[] {
466
+ return [...messages].sort((left, right) => left.sequence - right.sequence).map(replyMessage);
467
+ }
468
+
469
+ interface LiveReply {
470
+ readonly runId: string;
471
+ readonly items: readonly ReplyItem[];
472
+ }
473
+
474
+ /** The structured form of each reply, with the live reply's unfinished items when one runs. */
475
+ interface BuiltReply {
476
+ readonly block: ReplyBlock;
477
+ /** The finished chunk the reply came from; absent for a reply still being written. */
478
+ readonly chunk?: Chunk | undefined;
479
+ /** The answer's fact position; absent while the reply is still being written. */
480
+ readonly answerSequence?: number | undefined;
481
+ }
482
+
483
+ /** The assistant message a chunk ends with, when it has one. */
484
+ function answerIn(chunk: Chunk): Message | undefined {
485
+ return chunk.facts
486
+ .map((fact) => (fact.type === MESSAGE_FACT ? messageFrom(fact) : undefined))
487
+ .find((message) => message?.role === "assistant");
488
+ }
489
+
490
+ /** The last answer before `sequence`, so a window's first reply still names its input. */
491
+ function answerBefore(chunks: readonly Chunk[], sequence: number): number {
492
+ let previous = -1;
493
+ for (const chunk of chunks) {
494
+ const answer = answerIn(chunk);
495
+ if (answer === undefined) continue;
496
+ if (answer.sequence >= sequence) break;
497
+ previous = answer.sequence;
498
+ }
499
+ return previous;
500
+ }
501
+
502
+ /**
503
+ * The replies already finished among `chunks`, in order. `previousAnswer` is
504
+ * the answer before the first chunk, so a page or a read after a mark builds
505
+ * only the replies it carries while keeping an older reply's input right.
506
+ */
507
+ function storedReplies(
508
+ chunks: readonly Chunk[],
509
+ messages: readonly Message[],
510
+ home: string | undefined,
511
+ previousAnswer = -1,
512
+ ): readonly BuiltReply[] {
513
+ const byId = new Map(messages.map((message) => [message.id, message]));
514
+ const blocks: BuiltReply[] = [];
515
+ let previous = previousAnswer;
516
+ for (const chunk of chunks) {
517
+ const answer = answerIn(chunk);
518
+ if (answer === undefined) continue;
519
+ const runId = answer.runId ?? chunk.runId;
520
+ if (runId === undefined) continue;
521
+ const named = answer.replyTo === undefined || answer.replyTo.length === 0
522
+ ? []
523
+ : answer.replyTo
524
+ .map((id) => byId.get(id))
525
+ .filter((message): message is Message => message !== undefined && message.role === "user");
526
+ const input = named.length > 0
527
+ ? named
528
+ : messages.filter(
529
+ (message) =>
530
+ message.role === "user" &&
531
+ message.sequence > previous &&
532
+ message.sequence < answer.sequence,
533
+ );
534
+ blocks.push({
535
+ block: {
536
+ runId,
537
+ input: messagesInTime(input),
538
+ process: processOf(chunk, home),
539
+ answer: replyMessage(answer),
540
+ ...(answer.timings === undefined ? {} : { durationMs: answer.timings.totalMs }),
541
+ },
542
+ chunk,
543
+ answerSequence: answer.sequence,
544
+ });
545
+ previous = answer.sequence;
546
+ }
547
+ return blocks;
548
+ }
549
+
550
+ /** The one reply still being written, with the log's unfinished items. */
551
+ function liveReply(
552
+ facts: readonly PluginFact[],
553
+ messages: readonly Message[],
554
+ live: LiveReply,
555
+ home: string | undefined,
556
+ ): BuiltReply | undefined {
557
+ const chunks = chunksOf(facts);
558
+ let target = -1;
559
+ chunks.forEach((chunk, index) => {
560
+ if (chunk.runId === live.runId) target = index;
561
+ });
562
+ const chunk = target < 0 ? undefined : chunks[target];
563
+ const answer = chunk?.facts
564
+ .map((fact) => (fact.type === MESSAGE_FACT ? messageFrom(fact) : undefined))
565
+ .find((message) => message?.role === "assistant");
566
+ if (chunk !== undefined && answer === undefined) {
567
+ return {
568
+ block: {
569
+ runId: chunk.runId ?? live.runId,
570
+ input: messagesInTime(unanswered(messages, facts)),
571
+ process: processOf(chunk, home, live.items),
572
+ },
573
+ chunk,
574
+ };
575
+ }
576
+ const pending = unanswered(messages, facts);
577
+ if (pending.length === 0 && live.items.length === 0) return undefined;
578
+ return {
579
+ block: {
580
+ runId: live.runId,
581
+ input: messagesInTime(pending),
582
+ process: processOfItems(live.items),
583
+ },
584
+ };
585
+ }
586
+
587
+ function jsonBytes(value: unknown): number {
588
+ return Buffer.byteLength(JSON.stringify(value), "utf8");
589
+ }
590
+
591
+ /**
592
+ * The transcript's data, cut to fit its budget: tool output text first, then
593
+ * the other reply text, and at last the oldest reply blocks. A read that still
594
+ * did not fit would be refused, so this always answers within the budget.
595
+ */
596
+ function replyData(
597
+ replies: readonly ReplyBlock[],
598
+ maxBytes: number,
599
+ base: Readonly<Record<string, JsonValue>> = {},
600
+ ): Readonly<Record<string, JsonValue>> {
601
+ const data = (shown: readonly ReplyBlock[], extra: Readonly<Record<string, JsonValue>> = base) =>
602
+ ({ ...extra, replies: shown }) as unknown as Readonly<Record<string, JsonValue>>;
603
+ const whole = data(replies);
604
+ if (jsonBytes(whole) <= maxBytes) return whole;
605
+ // A tool's output is the largest part and the least useful to a structured
606
+ // client, so it goes first, keeping its line count and `truncated`.
607
+ const blanked = replies.map((reply) => ({
608
+ ...reply,
609
+ process: reply.process.map((group) => ({
610
+ ...group,
611
+ items: group.items.map((item) => {
612
+ if (item.kind !== "tool" || item.output.text.length === 0) return item;
613
+ return {
614
+ ...item,
615
+ output: { ...item.output, text: "", truncated: true as const },
616
+ };
617
+ }),
618
+ })),
619
+ }));
620
+ if (jsonBytes(data(blanked)) <= maxBytes) return data(blanked);
621
+ // Thinking, text, input and answer text are shortened next, in steps, so a
622
+ // long absence still leaves every reply's structure.
623
+ for (const cap of [512, 128, 32, 0]) {
624
+ const cut = blanked.map((reply) => cutReply(reply, cap));
625
+ if (jsonBytes(data(cut)) <= maxBytes) return data(cut);
626
+ }
627
+ // Even empty text leaves too much structure: the oldest replies go.
628
+ for (let drop = 1; drop <= blanked.length; drop += 1) {
629
+ const kept = blanked.slice(drop);
630
+ const cut = kept.map((reply) => cutReply(reply, 0));
631
+ if (jsonBytes(data(cut)) <= maxBytes) return data(cut);
632
+ }
633
+ const empty = data([]);
634
+ if (jsonBytes(empty) <= maxBytes) return empty;
635
+ // The base is the only thing left; it is small in every caller but is cut
636
+ // last rather than letting the read be refused.
637
+ return (jsonBytes({ replies: [] }) <= maxBytes ? { replies: [] } : {}) as Readonly<Record<string, JsonValue>>;
638
+ }
639
+
640
+ /** Text cut to fit a byte budget, ending with an ellipsis when it was longer. */
641
+ function shorten(text: string, capBytes: number): string {
642
+ if (capBytes <= 0) return "";
643
+ if (Buffer.byteLength(text, "utf8") <= capBytes) return text;
644
+ if (capBytes <= 3) return "";
645
+ let end = Math.min(text.length, capBytes);
646
+ while (end > 0 && Buffer.byteLength(text.slice(0, end), "utf8") + 3 > capBytes) end -= 1;
647
+ return end === 0 ? "" : `${text.slice(0, end)}…`;
648
+ }
649
+
650
+ /** One reply with its free text cut to a budget and its tool output left empty. */
651
+ function cutReply(reply: ReplyBlock, capBytes: number): ReplyBlock {
652
+ const message = (block: ReplyMessage): ReplyMessage => ({
653
+ ...block,
654
+ text: shorten(block.text, capBytes),
655
+ });
656
+ const item = (entry: ReplyItem): ReplyItem => {
657
+ if (entry.kind === "tool") {
658
+ return {
659
+ ...entry,
660
+ input: entry.input === null ? null : shorten(entry.input, capBytes),
661
+ };
662
+ }
663
+ return { ...entry, text: shorten(entry.text, capBytes) };
664
+ };
665
+ return {
666
+ ...reply,
667
+ input: reply.input.map(message),
668
+ ...(reply.answer === undefined ? {} : { answer: message(reply.answer) }),
669
+ process: reply.process.map((group) => ({
670
+ ...group,
671
+ items: group.items.map(item),
672
+ })),
673
+ };
674
+ }
675
+
170
676
  /** One finished part of an answer as Markdown lines; tool output is never shown. */
171
- function entryMarkdown(entry: Entry, speaker: string, harness: string): string | undefined {
677
+ function entryMarkdown(entry: Entry | FoldEntry, speaker: string, harness: string): string | undefined {
678
+ // A failure line is shown for every harness; it is already one plain line.
679
+ if (entry.kind === "failure") {
680
+ const said = flat(entry.text ?? "");
681
+ return said.length === 0 ? undefined : said;
682
+ }
683
+ if (entry.kind === "worktree") {
684
+ const said = flat(entry.text ?? "");
685
+ return said.length === 0 ? undefined : said;
686
+ }
687
+ // The line a crash or restart leaves is shown for every harness, as a failure is.
688
+ if (entry.kind === "stopped" && entry.interrupted === true) {
689
+ const said = flat(entry.text ?? "");
690
+ return said.length === 0 ? undefined : said;
691
+ }
172
692
  // Radian gives no text or thinking increments; its chats show the tool lines only.
173
693
  if (entry.kind !== "tool" && harness === "radian") return undefined;
174
694
  if (entry.kind === "tool") return toolMarkdown(entry);
@@ -179,22 +699,10 @@ function entryMarkdown(entry: Entry, speaker: string, harness: string): string |
179
699
  .map((line) => `> ${line}`)
180
700
  .join("\n");
181
701
  }
182
- const said = flat(entry.text);
183
- return said.length === 0 ? undefined : `**${speaker}:** ${said}`;
184
- }
185
-
186
- function allFacts(ctx: ViewContext, ref: ObjectRef): readonly PluginFact[] {
187
- const facts: PluginFact[] = [];
188
- let cursor: string | undefined;
189
- do {
190
- const page = ctx.store.facts(ref, {
191
- ...(cursor === undefined ? {} : { cursor }),
192
- limit: 500,
193
- });
194
- facts.push(...page.facts);
195
- cursor = page.next;
196
- } while (cursor !== undefined);
197
- return facts;
702
+ const said = block(entry.text);
703
+ if (said.length === 0) return undefined;
704
+ const body = `**${speaker}:** ${said}`;
705
+ return entry.kind === "stopped" ? `${body}\n\n*stopped*` : body;
198
706
  }
199
707
 
200
708
  interface Chunk {
@@ -202,18 +710,114 @@ interface Chunk {
202
710
  /** How many messages, not entries, the chunk holds. */
203
711
  readonly messages: number;
204
712
  readonly last: number;
713
+ /** The run a run chunk belongs to; absent for a message or older chunk. */
714
+ readonly runId?: string | undefined;
205
715
  }
206
716
 
207
- function chunkOf(facts: readonly PluginFact[]): Chunk {
717
+ function chunkOf(facts: readonly PluginFact[], runId?: string): Chunk {
208
718
  return {
209
719
  facts,
210
- messages: facts.filter((fact) => fact.type === MESSAGE_FACT).length,
720
+ messages: facts.filter((fact) => fact.type === MESSAGE_FACT || fact.type === COMMAND_FACT).length,
211
721
  last: facts.at(-1)?.sequence ?? 0,
722
+ ...(runId === undefined ? {} : { runId }),
723
+ };
724
+ }
725
+
726
+ /** The facts a turn shows: messages, commands, withdraw entries and finished entries. */
727
+ function shownFact(fact: PluginFact): boolean {
728
+ if (fact.type === MESSAGE_CHANGE_FACT) return messageChangeOfFact(fact)?.kind === "withdraw";
729
+ return fact.type === MESSAGE_FACT || fact.type === COMMAND_FACT || fact.type === ENTRY_FACT;
730
+ }
731
+
732
+ /** What one run took: the messages its reply or answer fact names, and whether either says so. */
733
+ interface RunTaken {
734
+ readonly ids: ReadonlySet<string>;
735
+ readonly known: boolean;
736
+ }
737
+
738
+ /**
739
+ * The messages each run took. A reply names them in `replyTo`; a run that ended
740
+ * without a reply names the ones it took in `chat.answered`. A run with neither
741
+ * says nothing, so an older chat keeps the order it recorded.
742
+ */
743
+ function takenByRun(facts: readonly PluginFact[]): ReadonlyMap<string, RunTaken> {
744
+ const found = new Map<string, { readonly ids: Set<string>; known: boolean }>();
745
+ const add = (runId: unknown, ids: readonly string[], known: boolean): void => {
746
+ if (typeof runId !== "string" || runId.length === 0) return;
747
+ const run = found.get(runId) ?? { ids: new Set<string>(), known: false };
748
+ for (const id of ids) run.ids.add(id);
749
+ run.known = run.known || known;
750
+ found.set(runId, run);
212
751
  };
752
+ for (const fact of facts) {
753
+ if (fact.type === MESSAGE_FACT && fact.data.role === "assistant") {
754
+ const replyTo = fact.data.replyTo;
755
+ const ids = Array.isArray(replyTo)
756
+ ? replyTo.filter((id): id is string => typeof id === "string" && id.length > 0)
757
+ : [];
758
+ add(fact.data.runId, ids, Array.isArray(replyTo));
759
+ } else if (fact.type === ANSWER_FACT) {
760
+ add(fact.data.runId, answeredOfFact(fact), true);
761
+ }
762
+ }
763
+ return found;
764
+ }
765
+
766
+ interface RunChunk {
767
+ readonly chunk: Chunk;
768
+ readonly span: number;
769
+ }
770
+
771
+ /**
772
+ * The chunks of each run, from the run fact to its reply. A message the run
773
+ * took while it wrote is in that span, so it is ordered with the run's items
774
+ * rather than left as a chunk above all of them. A message the run did not take
775
+ * waits for the next round, so it stays out of the reply's items. Content before
776
+ * the first run fact, and a store that predates run facts, keeps the older
777
+ * chunking.
778
+ */
779
+ function runChunks(
780
+ facts: readonly PluginFact[],
781
+ ): { readonly chunks: readonly RunChunk[]; readonly consumed: ReadonlySet<number>; readonly spans: readonly number[] } | undefined {
782
+ const starts: { readonly index: number; readonly runId: string }[] = [];
783
+ facts.forEach((fact, index) => {
784
+ if (fact.type === RUN_FACT && typeof fact.data.runId === "string" && fact.data.runId.length > 0) {
785
+ starts.push({ index, runId: fact.data.runId });
786
+ }
787
+ });
788
+ if (starts.length === 0) return undefined;
789
+ const taken = takenByRun(facts);
790
+ const spans = facts.map(() => -1);
791
+ const chunks: RunChunk[] = [];
792
+ const consumed = new Set<number>();
793
+ starts.forEach((start, at) => {
794
+ const end = starts[at + 1]?.index ?? facts.length;
795
+ for (let index = start.index; index < end; index += 1) spans[index] = start.index;
796
+ const took = taken.get(start.runId);
797
+ let turn: PluginFact[] = [];
798
+ for (let index = start.index + 1; index < end; index += 1) {
799
+ const fact = facts[index];
800
+ if (fact === undefined || !shownFact(fact)) continue;
801
+ // A person's message that this run's reply does not name was not given
802
+ // to the agent; it is the next round's, not part of this reply.
803
+ if (fact.type === MESSAGE_FACT && fact.data.role === "user") {
804
+ const id = typeof fact.data.id === "string" ? fact.data.id : undefined;
805
+ if (id !== undefined && took?.known === true && !took.ids.has(id)) continue;
806
+ }
807
+ turn.push(fact);
808
+ consumed.add(index);
809
+ if (fact.type === MESSAGE_FACT && fact.data.role === "assistant" && fact.data.runId === start.runId) {
810
+ chunks.push({ chunk: chunkOf(turn, start.runId), span: start.index });
811
+ turn = [];
812
+ }
813
+ }
814
+ if (turn.length > 0) chunks.push({ chunk: chunkOf(turn, start.runId), span: start.index });
815
+ });
816
+ return { chunks, consumed, spans };
213
817
  }
214
818
 
215
819
  /** A turn is the entries of a run and the reply they led to, so a page never splits them. */
216
- function chunksOf(facts: readonly PluginFact[]): readonly Chunk[] {
820
+ function legacyChunksOf(facts: readonly PluginFact[]): readonly Chunk[] {
217
821
  const replies = new Map<string, number[]>();
218
822
  const indexes = new Map<number, number>();
219
823
  facts.forEach((fact, index) => {
@@ -251,12 +855,74 @@ function chunksOf(facts: readonly PluginFact[]): readonly Chunk[] {
251
855
  index = end;
252
856
  continue;
253
857
  }
254
- if (fact.type === MESSAGE_FACT) chunks.push(chunkOf([fact]));
858
+ if (
859
+ fact.type === MESSAGE_FACT ||
860
+ fact.type === COMMAND_FACT ||
861
+ (fact.type === MESSAGE_CHANGE_FACT && messageChangeOfFact(fact)?.kind === "withdraw")
862
+ ) {
863
+ chunks.push(chunkOf([fact]));
864
+ }
255
865
  index += 1;
256
866
  }
257
867
  return chunks;
258
868
  }
259
869
 
870
+ function chunksOf(facts: readonly PluginFact[]): readonly Chunk[] {
871
+ const runs = runChunks(facts);
872
+ if (runs === undefined) return legacyChunksOf(facts);
873
+ // A chunk carries the run span it belongs to. A run's own chunks come before
874
+ // what its span left out: a message it did not take waits above the next
875
+ // round, below this reply, rather than splitting the reply's items.
876
+ const placed: { readonly chunk: Chunk; readonly span: number; readonly after: boolean }[] = runs.chunks.map(
877
+ (run) => ({ chunk: run.chunk, span: run.span, after: false }),
878
+ );
879
+ const rest = (first: number, chunk: Chunk): void => {
880
+ placed.push({ chunk, span: runs.spans[first] ?? -1, after: true });
881
+ };
882
+ let index = 0;
883
+ while (index < facts.length) {
884
+ if (runs.consumed.has(index)) {
885
+ index += 1;
886
+ continue;
887
+ }
888
+ const fact = facts[index];
889
+ if (fact === undefined) break;
890
+ if (
891
+ fact.type === MESSAGE_FACT ||
892
+ fact.type === COMMAND_FACT ||
893
+ (fact.type === MESSAGE_CHANGE_FACT && messageChangeOfFact(fact)?.kind === "withdraw")
894
+ ) {
895
+ rest(index, chunkOf([fact]));
896
+ index += 1;
897
+ continue;
898
+ }
899
+ if (fact.type === ENTRY_FACT) {
900
+ const runId = typeof fact.data.runId === "string" ? fact.data.runId : undefined;
901
+ let end = index + 1;
902
+ while (
903
+ end < facts.length &&
904
+ !runs.consumed.has(end) &&
905
+ facts[end]?.type === ENTRY_FACT &&
906
+ (runId === undefined || facts[end]?.data.runId === runId)
907
+ ) {
908
+ end += 1;
909
+ }
910
+ rest(index, chunkOf(facts.slice(index, end)));
911
+ index = end;
912
+ continue;
913
+ }
914
+ index += 1;
915
+ }
916
+ return placed
917
+ .sort(
918
+ (left, right) =>
919
+ left.span - right.span ||
920
+ (left.after === right.after ? 0 : left.after ? 1 : -1) ||
921
+ (left.chunk.facts[0]?.sequence ?? 0) - (right.chunk.facts[0]?.sequence ?? 0),
922
+ )
923
+ .map((item) => item.chunk);
924
+ }
925
+
260
926
  interface Page {
261
927
  readonly chunks: readonly Chunk[];
262
928
  readonly after: number | undefined;
@@ -302,6 +968,29 @@ function cursorAfter(cursor: string): number | undefined {
302
968
  return value.kind === "facts" && typeof value.after === "number" ? value.after : undefined;
303
969
  }
304
970
 
971
+ /** When one shown item happened, for ordering a turn with a message sent during it. */
972
+ function shownAt(fact: PluginFact): number {
973
+ const entry = fact.type === ENTRY_FACT ? entryOfFact(fact) : undefined;
974
+ return entry !== undefined && typeof entry.startedAt === "number" ? entry.startedAt : fact.at;
975
+ }
976
+
977
+ /**
978
+ * The facts of a turn in time order, when the entries carry times. A store whose
979
+ * entries carry none keeps the order it recorded, so an older chat reads as it
980
+ * always did. Messages and commands always carry their fact's time.
981
+ */
982
+ function turnFacts(facts: readonly PluginFact[]): readonly PluginFact[] {
983
+ const timed = facts.some((fact) => {
984
+ const entry = fact.type === ENTRY_FACT ? entryOfFact(fact) : undefined;
985
+ return entry !== undefined && typeof entry.startedAt === "number";
986
+ });
987
+ if (!timed) return facts;
988
+ return facts
989
+ .map((fact, index) => ({ fact, index, at: shownAt(fact) }))
990
+ .sort((left, right) => left.at - right.at || left.index - right.index)
991
+ .map((item) => item.fact);
992
+ }
993
+
305
994
  function rendered(chunk: Chunk, speaker: string, home: string | undefined, harness: string): readonly string[] {
306
995
  const blocks: string[] = [];
307
996
  let lines: string[] = [];
@@ -309,7 +998,19 @@ function rendered(chunk: Chunk, speaker: string, home: string | undefined, harne
309
998
  if (lines.length > 0) blocks.push(lines.join("\n"));
310
999
  lines = [];
311
1000
  };
312
- for (const fact of chunk.facts) {
1001
+ for (const fact of turnFacts(chunk.facts)) {
1002
+ if (fact.type === COMMAND_FACT) {
1003
+ flush();
1004
+ const command = commandOfFact(fact);
1005
+ if (command !== undefined) blocks.push(commandMarkdown(command));
1006
+ continue;
1007
+ }
1008
+ if (fact.type === MESSAGE_CHANGE_FACT) {
1009
+ flush();
1010
+ const change = messageChangeOfFact(fact);
1011
+ if (change?.kind === "withdraw") blocks.push(withdrawalMarkdown(change));
1012
+ continue;
1013
+ }
313
1014
  if (fact.type === ENTRY_FACT) {
314
1015
  const entry = entryOfFact(fact);
315
1016
  const markdown = entry === undefined ? undefined : entryMarkdown(entry, speaker, harness);
@@ -338,85 +1039,390 @@ function clock(at: number): string {
338
1039
  return new Date(at).toISOString().slice(11, 19);
339
1040
  }
340
1041
 
1042
+ /** The changing part of a transcript: its tail, what the reply is doing, and where finished content pauses. */
1043
+ interface Live {
1044
+ readonly tail?: string | undefined;
1045
+ readonly status?: SectionStatus | undefined;
1046
+ readonly retry?: SectionRetry | undefined;
1047
+ /** The last fact before a message the live tail holds, so a client reads it again with the reply. */
1048
+ readonly cut?: number | undefined;
1049
+ /** The run still being written, so its structured reply can take the unfinished items. */
1050
+ readonly run?: string | undefined;
1051
+ /** The process items the log holds and the facts do not, oldest first. */
1052
+ readonly items?: readonly ReplyItem[] | undefined;
1053
+ }
1054
+
1055
+ /** One line for a model request the agent is waiting to try again. */
1056
+ function retryMarkdown(retry: SectionRetry): string {
1057
+ const reason = flat(retry.reason);
1058
+ return `Retrying the model request (${retry.attempt} of ${retry.maxAttempts})${reason.length === 0 ? "" : `: ${reason}`}`;
1059
+ }
1060
+
1061
+ interface TailItem {
1062
+ readonly at?: number | undefined;
1063
+ readonly order: number;
1064
+ readonly markdown: string;
1065
+ readonly item?: ReplyItem | undefined;
1066
+ }
1067
+
1068
+ /**
1069
+ * The person's messages a reply still owes an answer. A reply recorded before
1070
+ * `replyTo` existed answers every message before it, so an old snapshot that
1071
+ * ends with an assistant message is not left looking unanswered.
1072
+ */
1073
+ function statusPending(messages: readonly Message[], facts: readonly PluginFact[]): readonly Message[] {
1074
+ const pending = unanswered(messages, facts);
1075
+ if (pending.length === 0) return pending;
1076
+ const legacy = messages.filter(
1077
+ (message) => message.role === "assistant" && (message.replyTo === undefined || message.replyTo.length === 0),
1078
+ );
1079
+ return pending.filter((message) => !legacy.some((reply) => reply.sequence > message.sequence));
1080
+ }
1081
+
1082
+ /**
1083
+ * What the reply is doing, or undefined when nothing of it is in progress. A
1084
+ * question waiting for the person, a failure, a stop and a chat whose messages
1085
+ * are all answered say nothing. Before the log has the ready line, the first
1086
+ * message still unanswered is what the reply waits on.
1087
+ */
1088
+ function statusOf(
1089
+ facts: readonly PluginFact[],
1090
+ pending: readonly Message[],
1091
+ runId: string | undefined,
1092
+ times: Awaited<ReturnType<NonNullable<ViewContext["runTimes"]>>>,
1093
+ read: TailRead | undefined,
1094
+ called: ReadonlySet<string>,
1095
+ secrets: readonly string[],
1096
+ ): SectionStatus | undefined {
1097
+ const newest = pending.at(-1);
1098
+ if (newest === undefined) return undefined;
1099
+ const last = times?.segments.at(-1);
1100
+ if (last?.person === true && last.to === null) return undefined;
1101
+ // A failure or stop after the newest message that still waits ends the
1102
+ // reply for it. A message that came later starts another reply.
1103
+ let ended = -1;
1104
+ if (runId !== undefined) {
1105
+ for (const fact of facts) {
1106
+ const entry = entryOfFact(fact);
1107
+ if (entry !== undefined && (entry.kind === "failure" || entry.kind === "stopped") && entry.runId === runId) {
1108
+ ended = Math.max(ended, entry.sequence);
1109
+ }
1110
+ if (stopOfFact(fact)?.runId === runId) ended = Math.max(ended, fact.sequence);
1111
+ }
1112
+ }
1113
+ if (ended >= newest.sequence) return undefined;
1114
+ const endedAt = times?.endedAt;
1115
+ if (endedAt !== null && endedAt !== undefined && newest.at <= endedAt) return undefined;
1116
+ const first = pending[0] ?? newest;
1117
+ if (read === undefined || !read.ready) return { text: "Starting", since: first.at };
1118
+ const open = read.state.calls.find((call) => !called.has(maskSecrets(call.callId, secrets)));
1119
+ if (open !== undefined) {
1120
+ return { text: `Running ${maskSecrets(open.toolName, secrets)}`, since: open.at };
1121
+ }
1122
+ return { text: "Thinking", since: read.lastAt ?? times?.startedAt ?? first.at };
1123
+ }
1124
+
1125
+ /** One shown fact as a tail line, for a message the live reply is holding. */
1126
+ function factTailItem(fact: PluginFact, speaker: string, home: string | undefined, harness: string): string | undefined {
1127
+ if (fact.type === COMMAND_FACT) {
1128
+ const command = commandOfFact(fact);
1129
+ return command === undefined ? undefined : commandMarkdown(command);
1130
+ }
1131
+ if (fact.type === ENTRY_FACT) {
1132
+ const entry = entryOfFact(fact);
1133
+ return entry === undefined ? undefined : entryMarkdown(entry, speaker, harness);
1134
+ }
1135
+ if (fact.type === MESSAGE_CHANGE_FACT) {
1136
+ const change = messageChangeOfFact(fact);
1137
+ return change?.kind === "withdraw" ? withdrawalMarkdown(change) : undefined;
1138
+ }
1139
+ if (fact.type !== MESSAGE_FACT) return undefined;
1140
+ const message = messageFrom(fact);
1141
+ return message === undefined ? undefined : messageMarkdown(message, speaker, home);
1142
+ }
1143
+
341
1144
  /**
342
- * What the running reply has written and not finished, as Markdown, or
343
- * undefined when no reply runs. It is read from the end of the log of the
344
- * step that runs the agent. What the facts already hold is not repeated.
1145
+ * The tail of a reply that has a message sent during it. The message is a fact
1146
+ * but the reply's items are still in the log: both are put in time order, so
1147
+ * the live tail and the stored transcript place the message alike. `cut` is the
1148
+ * fact before the first such message; finished content stops there until the
1149
+ * run ends or the message can be appended with the rest.
345
1150
  */
346
- async function tailOf(
1151
+ function heldTail(
1152
+ facts: readonly PluginFact[],
1153
+ cut: number,
1154
+ log: readonly TailItem[],
1155
+ speaker: string,
1156
+ home: string | undefined,
1157
+ harness: string,
1158
+ ): string | undefined {
1159
+ const held: TailItem[] = [];
1160
+ for (const fact of facts) {
1161
+ if (fact.sequence <= cut) continue;
1162
+ const markdown = factTailItem(fact, speaker, home, harness);
1163
+ if (markdown === undefined) continue;
1164
+ held.push({ at: shownAt(fact), order: held.length, markdown });
1165
+ }
1166
+ const all = [...held, ...log.map((item, index) => ({ ...item, order: held.length + index }))];
1167
+ const fallback = log.at(-1)?.at ?? 0;
1168
+ const ordered = all
1169
+ .map((item) => ({ ...item, sort: item.at ?? fallback }))
1170
+ .sort((left, right) => left.sort - right.sort || left.order - right.order);
1171
+ const lines = ordered.map((item) => item.markdown).filter((line) => line.trim().length > 0);
1172
+ return lines.length === 0 ? undefined : lines.join("\n\n");
1173
+ }
1174
+
1175
+ /**
1176
+ * What the running reply has written and the facts do not hold yet, as
1177
+ * Markdown, or undefined when no reply runs. It is read from the end of the log
1178
+ * of the step that runs the agent. A finished entry stays here until the fact
1179
+ * that holds it is visible to the same read, so the text never has a gap. The
1180
+ * same read gives the status beside it.
1181
+ */
1182
+ async function liveOf(
347
1183
  ctx: ViewContext,
348
1184
  object: StoredObject,
349
1185
  facts: readonly PluginFact[],
1186
+ messages: readonly Message[],
350
1187
  speaker: string,
351
- ): Promise<string | undefined> {
1188
+ ): Promise<Live> {
352
1189
  const chat = chatData(object.data);
353
1190
  const runId = latestRunOf(facts);
354
- if (runId === undefined || chat.harness.length === 0 || ctx.runTimes === undefined) return undefined;
355
- const times = await ctx.runTimes(runId);
356
- if (times === undefined || times.endedAt !== null) return undefined;
357
- const read = foldLogTail(agentLogPath(ctx.store.root, chat.harness, runId));
358
- if (read === undefined) return undefined;
359
- const secrets = await secretValues(ctx);
360
- const said = new Set<string>();
361
- const called = new Set<string>();
362
- for (const fact of facts) {
363
- if (fact.data.runId !== runId) continue;
364
- if (fact.type === MESSAGE_FACT && fact.data.role === "assistant" && typeof fact.data.text === "string") {
365
- said.add(fact.data.text.trim());
1191
+ const pending = statusPending(messages, facts);
1192
+ const times = runId !== undefined && ctx.runTimes !== undefined ? await ctx.runTimes(runId) : undefined;
1193
+ let tail: string | undefined;
1194
+ let read: TailRead | undefined;
1195
+ let retry: SectionRetry | undefined;
1196
+ let called: ReadonlySet<string> = new Set<string>();
1197
+ let secrets: readonly string[] = [];
1198
+ let cut: number | undefined;
1199
+ let items: readonly ReplyItem[] | undefined;
1200
+ let liveRun: string | undefined;
1201
+ if (runId !== undefined && chat.harness.length > 0 && ctx.runTimes !== undefined && times !== undefined && times.endedAt === null) {
1202
+ liveRun = runId;
1203
+ secrets = await secretValues(ctx);
1204
+ const said = new Set<string>();
1205
+ const calls = new Set<string>();
1206
+ let runStart = -1;
1207
+ for (const fact of facts) {
1208
+ if (fact.type === RUN_FACT && fact.data.runId === runId) runStart = fact.sequence;
1209
+ if (fact.data.runId !== runId) continue;
1210
+ if (fact.type === MESSAGE_FACT && fact.data.role === "assistant" && typeof fact.data.text === "string") {
1211
+ said.add(fact.data.text.trim());
1212
+ }
1213
+ const entry = fact.type === ENTRY_FACT ? entryOfFact(fact) : undefined;
1214
+ if (entry?.kind === "tool" && entry.callId !== undefined) calls.add(entry.callId);
1215
+ else if (entry?.text !== undefined) said.add(entry.text.trim());
1216
+ }
1217
+ called = calls;
1218
+ // A person's message after the run began is inside the reply. Its fact is
1219
+ // already stored while the reply's own items are still in the log.
1220
+ const during = runStart < 0
1221
+ ? undefined
1222
+ : facts.find(
1223
+ (fact) =>
1224
+ fact.sequence > runStart &&
1225
+ fact.type === MESSAGE_FACT &&
1226
+ fact.data.role === "user",
1227
+ );
1228
+ cut = during?.sequence === undefined ? undefined : during.sequence - 1;
1229
+ // The read drops a finished entry the facts already hold, so a long run does
1230
+ // not keep them all in the saved fold.
1231
+ const held = (entry: FoldEntry): boolean => {
1232
+ if (entry.kind === "tool") return calls.has(maskSecrets(entry.callId, secrets));
1233
+ return said.has(maskSecrets(entry.text, secrets).trim());
1234
+ };
1235
+ read = foldLogTail(agentLogPath(ctx.store.root, chat.harness, runId), held);
1236
+ const waiting = read?.state.retry;
1237
+ // The retry's own line stamps when the wait began; a later line's time
1238
+ // would move `until` on every read, so it is not used as a fallback.
1239
+ const retryAt = waiting?.at;
1240
+ retry =
1241
+ waiting === undefined || retryAt === undefined
1242
+ ? undefined
1243
+ : {
1244
+ attempt: waiting.attempt,
1245
+ maxAttempts: waiting.maxAttempts,
1246
+ until: retryAt + waiting.delayMs,
1247
+ reason: maskSecrets(waiting.reason, secrets),
1248
+ };
1249
+ if (read !== undefined) {
1250
+ const fresh = (text: string): string | undefined => {
1251
+ const masked = maskSecrets(text, secrets);
1252
+ return masked.trim().length === 0 || said.has(masked.trim()) ? undefined : masked;
1253
+ };
1254
+ const tailItems: TailItem[] = [];
1255
+ const push = (at: number | null | undefined, markdown: string | undefined, item?: ReplyItem): void => {
1256
+ if (markdown === undefined || markdown.trim().length === 0) return;
1257
+ tailItems.push({
1258
+ ...(at === null || at === undefined ? {} : { at }),
1259
+ order: tailItems.length,
1260
+ markdown,
1261
+ ...(item === undefined ? {} : { item }),
1262
+ });
1263
+ };
1264
+ // A finished entry is shown until the facts hold it; then `said` and `called` drop it.
1265
+ for (const entry of read.state.entries) {
1266
+ // Radian gives no text or thinking increments; its chats show tool lines only.
1267
+ if (chat.harness === "radian" && entry.kind !== "tool") continue;
1268
+ const item = replyItemOfFold(entry, secrets);
1269
+ if (entry.kind === "tool") {
1270
+ if (calls.has(maskSecrets(entry.callId, secrets))) continue;
1271
+ push(
1272
+ entry.at,
1273
+ entryMarkdown(
1274
+ {
1275
+ ...entry,
1276
+ toolName: maskSecrets(entry.toolName, secrets),
1277
+ input: entry.input === null ? null : maskSecrets(entry.input, secrets),
1278
+ error: entry.error === null ? null : maskSecrets(entry.error, secrets),
1279
+ },
1280
+ speaker,
1281
+ chat.harness,
1282
+ ),
1283
+ item,
1284
+ );
1285
+ continue;
1286
+ }
1287
+ const text = fresh(entry.text);
1288
+ if (text === undefined) continue;
1289
+ push(entry.at, entryMarkdown({ ...entry, text }, speaker, chat.harness), item);
1290
+ }
1291
+ // Radian gives no text or thinking increments; its chats show the tool lines only.
1292
+ if (chat.harness !== "radian") {
1293
+ const thinking = fresh(read.state.thinking);
1294
+ if (thinking !== undefined) {
1295
+ push(
1296
+ read.lastAt,
1297
+ thinking.split(/\r?\n/).map((line) => `> ${line}`).join("\n"),
1298
+ { kind: "thinking", text: thinking.trim(), ...(read.lastAt === undefined ? {} : { at: read.lastAt }) },
1299
+ );
1300
+ }
1301
+ const text = fresh(read.state.text);
1302
+ if (text !== undefined) {
1303
+ push(read.lastAt, `**${speaker}:** ${block(text)}`, {
1304
+ kind: "text",
1305
+ text: block(text),
1306
+ ...(read.lastAt === undefined ? {} : { at: read.lastAt }),
1307
+ });
1308
+ }
1309
+ }
1310
+ for (const call of read.state.calls) {
1311
+ if (calls.has(maskSecrets(call.callId, secrets))) continue;
1312
+ const input = call.input === null ? "" : flat(maskSecrets(call.input, secrets));
1313
+ const what = input.length === 0 ? "" : ` ${inlineCode(input.length <= 160 ? input : `${input.slice(0, 159)}…`)}`;
1314
+ push(
1315
+ call.at,
1316
+ `tool ${maskSecrets(call.toolName, secrets)} since ${clock(call.at)}${what}`,
1317
+ replyItemOfOpenCall(call, secrets),
1318
+ );
1319
+ }
1320
+ if (retry !== undefined) push(undefined, retryMarkdown(retry));
1321
+ const structured = tailItems.flatMap((item) => (item.item === undefined ? [] : [item.item]));
1322
+ if (structured.length > 0) items = structured;
1323
+ tail = cut === undefined
1324
+ ? (tailItems.length === 0 ? undefined : tailItems.map((item) => item.markdown).join("\n\n"))
1325
+ : heldTail(facts, cut, tailItems, speaker, ctx.home, chat.harness);
1326
+ } else if (retry !== undefined) {
1327
+ tail = retryMarkdown(retry);
1328
+ }
1329
+ // The log may not exist yet; the mid-run message still belongs in the tail.
1330
+ if (cut !== undefined && tail === undefined) {
1331
+ tail = heldTail(facts, cut, [], speaker, ctx.home, chat.harness);
366
1332
  }
367
- const entry = fact.type === ENTRY_FACT ? entryOfFact(fact) : undefined;
368
- if (entry?.kind === "tool" && entry.callId !== undefined) called.add(entry.callId);
369
- else if (entry?.text !== undefined) said.add(entry.text.trim());
370
1333
  }
371
- const fresh = (text: string): string | undefined => {
372
- const masked = maskSecrets(text, secrets);
373
- return masked.trim().length === 0 || said.has(masked.trim()) ? undefined : masked;
1334
+ const status = statusOf(facts, pending, runId, times, read, called, secrets);
1335
+ return {
1336
+ ...(tail === undefined ? {} : { tail }),
1337
+ ...(status === undefined ? {} : { status }),
1338
+ ...(retry === undefined ? {} : { retry }),
1339
+ ...(cut === undefined ? {} : { cut }),
1340
+ ...(liveRun === undefined ? {} : { run: liveRun }),
1341
+ ...(items === undefined ? {} : { items }),
374
1342
  };
375
- const lines: string[] = [];
376
- // Radian gives no text or thinking increments; its chats show the tool lines only.
377
- if (chat.harness !== "radian") {
378
- const thinking = fresh(read.state.thinking);
379
- if (thinking !== undefined) lines.push(thinking.split(/\r?\n/).map((line) => `> ${line}`).join("\n"));
380
- const text = fresh(read.state.text);
381
- if (text !== undefined) lines.push(`**${speaker}:** ${flat(text)}`);
382
- }
383
- for (const call of read.state.calls) {
384
- if (called.has(maskSecrets(call.callId, secrets))) continue;
385
- const input = call.input === null ? "" : flat(maskSecrets(call.input, secrets));
386
- const what = input.length === 0 ? "" : ` ${inlineCode(input.length <= 160 ? input : `${input.slice(0, 159)}…`)}`;
387
- lines.push(`tool ${maskSecrets(call.toolName, secrets)} since ${clock(call.at)}${what}`);
388
- }
389
- return lines.length === 0 ? undefined : lines.join("\n\n");
390
1343
  }
391
1344
 
392
1345
  async function load(
393
1346
  ctx: ViewContext,
394
1347
  object: StoredObject,
395
1348
  sectionId: string,
396
- options: { readonly cursor?: string | undefined; readonly after?: string | undefined },
1349
+ options: { readonly cursor?: string | undefined; readonly after?: string | undefined; readonly full?: boolean | undefined },
397
1350
  ): Promise<SectionContent> {
398
1351
  if (sectionId !== TRANSCRIPT) return { markdown: "" };
399
1352
  const ref = chatRef(object.id);
400
1353
  const chat = chatData(object.data);
401
- const speaker = await speakerOf(ctx, object);
402
- const facts = allFacts(ctx, ref);
403
- const tail = await tailOf(ctx, object, facts, speaker);
1354
+ const read = readChat(ctx.store, object.id);
1355
+ const speaker = await speakerOf(ctx, object, true);
1356
+ const facts = messageFactsInForce(read.facts);
1357
+ const messages = read.messages;
1358
+ const queued = queuedData(queuedMessages(messages, facts));
1359
+ const queueData: Record<string, JsonValue> = {
1360
+ queued: queued as unknown as JsonValue,
1361
+ queuedCount: queued.length,
1362
+ };
1363
+ const live = await liveOf(ctx, object, facts, messages, speaker);
1364
+ const { cut, run: liveRun, items: liveItems, ...liveContent } = live;
1365
+ const liveBlock =
1366
+ liveRun === undefined
1367
+ ? undefined
1368
+ : liveReply(facts, messages, { runId: liveRun, items: liveItems ?? [] }, ctx.home);
1369
+ const limit = options.full === true ? Number.POSITIVE_INFINITY : ctx.sectionCapBytes ?? DEFAULT_SECTION_CAP_BYTES;
1370
+ // A message the live tail holds stays unread as finished content until the
1371
+ // run ends, so the same facts then arrive together with the reply's items.
1372
+ const finished = cut === undefined ? facts : facts.filter((fact) => fact.sequence <= cut);
1373
+ const context = chatContext(object, read);
404
1374
  const since = markAfter(options.after);
1375
+ const finishedChunks = chunksOf(finished);
405
1376
  if (since !== undefined) {
406
1377
  // Only what was recorded after the mark, in the same Markdown as a full read.
407
- const chunks = chunksOf(facts.filter((fact) => fact.sequence > since));
1378
+ const chunks = chunksOf(finished.filter((fact) => fact.sequence > since));
408
1379
  const blocks = chunks.flatMap((chunk) => rendered(chunk, speaker, ctx.home, chat.harness));
1380
+ const markdown = blocks.join("\n\n---\n\n");
1381
+ // The replies whose answer is after the mark, and the one still running.
1382
+ const sinceChunks = finishedChunks.filter((chunk) => {
1383
+ const answer = answerIn(chunk);
1384
+ return answer !== undefined && answer.sequence > since;
1385
+ });
1386
+ const firstSince = sinceChunks
1387
+ .map((chunk) => answerIn(chunk)?.sequence)
1388
+ .find((sequence): sequence is number => sequence !== undefined);
1389
+ const changed = storedReplies(
1390
+ sinceChunks,
1391
+ messages,
1392
+ ctx.home,
1393
+ firstSince === undefined ? -1 : answerBefore(finishedChunks, firstSince),
1394
+ );
1395
+ const replies = liveBlock === undefined ? changed : [...changed, liveBlock];
1396
+ const data = replyData(
1397
+ replies.map((reply) => reply.block),
1398
+ Math.max(0, limit - Buffer.byteLength(markdown, "utf8") - Buffer.byteLength(liveContent.tail ?? "", "utf8")),
1399
+ queueData,
1400
+ );
409
1401
  return {
410
- markdown: blocks.join("\n\n---\n\n"),
1402
+ markdown,
411
1403
  mark: markOf(Math.max(since, chunks.at(-1)?.last ?? 0)),
412
1404
  delta: true,
413
- ...(tail === undefined ? {} : { tail }),
1405
+ ...liveContent,
1406
+ ...(context === undefined ? {} : { context }),
1407
+ data,
414
1408
  };
415
1409
  }
416
- const pages = pagesOf(ref, chunksOf(facts));
1410
+ const pages = pagesOf(ref, finishedChunks);
417
1411
  const after = options.cursor === undefined ? undefined : cursorAfter(options.cursor);
418
1412
  const index = pages.findIndex((page) => page.after === after);
419
1413
  const selected = pages[index < 0 ? 0 : index] ?? pages[0];
1414
+ const pageIndex = index < 0 ? 0 : index;
1415
+ const pageChunks = selected?.chunks ?? [];
1416
+ const firstOnPage = pageChunks[0]?.facts[0]?.sequence ?? Number.MAX_SAFE_INTEGER;
1417
+ const onPageBlocks = storedReplies(
1418
+ pageChunks,
1419
+ messages,
1420
+ ctx.home,
1421
+ answerBefore(finishedChunks, firstOnPage),
1422
+ );
1423
+ const pageReplies = pageIndex === pages.length - 1 && liveBlock !== undefined
1424
+ ? [...onPageBlocks, liveBlock]
1425
+ : onPageBlocks;
420
1426
  const blocks = (selected?.chunks ?? []).flatMap((chunk) => rendered(chunk, speaker, ctx.home, chat.harness));
421
1427
  const body = blocks.length === 0 && options.cursor === undefined ? "No messages yet." : blocks.join("\n\n---\n\n");
422
1428
  // Every page says which agent answers, as the row does.
@@ -424,6 +1430,11 @@ async function load(
424
1430
  ? `Agent: ${agentLine(chat)}\n\n${body}`
425
1431
  : body;
426
1432
  const nextPage = index < 0 ? undefined : pages[index + 1];
1433
+ const data = replyData(
1434
+ pageReplies.map((reply) => reply.block),
1435
+ Math.max(0, limit - Buffer.byteLength(markdown, "utf8") - Buffer.byteLength(liveContent.tail ?? "", "utf8")),
1436
+ queueData,
1437
+ );
427
1438
 
428
1439
  // The table of contents: the cursor each page starts at, the first one without.
429
1440
  const toc: SectionPage[] = pages.map((page, at) =>
@@ -436,9 +1447,85 @@ async function load(
436
1447
  mark: markOf(selected?.chunks.at(-1)?.last ?? 0),
437
1448
  ...(nextPage?.cursor === undefined ? {} : { next: nextPage.cursor }),
438
1449
  ...(toc.length > 1 ? { pages: toc } : {}),
439
- ...(tail === undefined ? {} : { tail }),
1450
+ ...liveContent,
1451
+ ...(context === undefined ? {} : { context }),
1452
+ data,
1453
+ };
1454
+ }
1455
+
1456
+ /** Reads an object through its type's `prepare`, or the store when the view has none. */
1457
+ function objectReader(ctx: ViewContext): ObjectReader {
1458
+ return async (type, id) =>
1459
+ ctx.refreshedObject === undefined ? ctx.store.get(type, id) : ctx.refreshedObject(type, id);
1460
+ }
1461
+
1462
+ /**
1463
+ * The changing part of the transcript, for the event stream's live push. It
1464
+ * is the same tail and status a section read returns, without the finished
1465
+ * content, so a client renders what the reply writes as it arrives.
1466
+ */
1467
+ async function tailPush(
1468
+ ctx: ViewContext,
1469
+ object: StoredObject,
1470
+ ): Promise<{ readonly section: string; readonly tail?: string; readonly status?: SectionStatus; readonly retry?: SectionRetry; readonly data?: Readonly<Record<string, JsonValue>> } | undefined> {
1471
+ const read = readChat(ctx.store, object.id);
1472
+ const facts = messageFactsInForce(read.facts);
1473
+ const messages = read.messages;
1474
+ const speaker = await speakerOf(ctx, object);
1475
+ const live = await liveOf(ctx, object, facts, messages, speaker);
1476
+ const liveBlock = live.run === undefined
1477
+ ? undefined
1478
+ : liveReply(facts, messages, { runId: live.run, items: live.items ?? [] }, ctx.home);
1479
+ const limit = ctx.sectionCapBytes ?? DEFAULT_SECTION_CAP_BYTES;
1480
+ const data = liveBlock === undefined
1481
+ ? undefined
1482
+ : replyData(
1483
+ [liveBlock.block],
1484
+ Math.max(0, limit - Buffer.byteLength(live.tail ?? "", "utf8")),
1485
+ );
1486
+ if (live.tail === undefined && live.status === undefined && live.retry === undefined && data === undefined) {
1487
+ return undefined;
1488
+ }
1489
+ return {
1490
+ section: TRANSCRIPT,
1491
+ ...(live.tail === undefined ? {} : { tail: live.tail }),
1492
+ ...(live.status === undefined ? {} : { status: live.status }),
1493
+ ...(live.retry === undefined ? {} : { retry: live.retry }),
1494
+ ...(data === undefined ? {} : { data }),
440
1495
  };
441
1496
  }
442
1497
 
1498
+ /** Whether a requested path is one the chat's own facts name, never one a client chose. */
1499
+ async function file(ctx: ViewContext, object: StoredObject, path: readonly string[]): Promise<boolean> {
1500
+ if (
1501
+ path.length === 0 ||
1502
+ path.some(
1503
+ (part) => part.length === 0 || part === "." || part === ".." || part.includes("/") || part.includes("\\"),
1504
+ )
1505
+ ) {
1506
+ return false;
1507
+ }
1508
+ const requested = join(attachmentDir(ctx.home, CHAT_TYPE, object.id), ...path);
1509
+ const named = new Set<string>();
1510
+ for (const fact of factsOf(ctx.store, chatRef(object.id))) {
1511
+ if (fact.type === MESSAGE_FACT) {
1512
+ for (const attachment of attachmentsOf(fact.data.attachments)) named.add(attachment.path);
1513
+ } else if (fact.type === ENTRY_FACT) {
1514
+ const entry = entryOfFact(fact);
1515
+ if (entry?.outputPath !== undefined) named.add(entry.outputPath);
1516
+ }
1517
+ }
1518
+ return named.has(requested);
1519
+ }
1520
+
443
1521
  /** The views of the chat type. */
444
- export const chatViews: ObjectViews = { row, sections, load };
1522
+ export const chatViews: ObjectViews = {
1523
+ row,
1524
+ sections,
1525
+ context: (ctx, object) => chatContext(object, readChat(ctx.store, object.id)),
1526
+ skills: async (ctx, object) =>
1527
+ skillSummaries(await readChatSkills(chatData(object.data), objectReader(ctx))),
1528
+ file,
1529
+ tail: tailPush,
1530
+ load,
1531
+ };