@operad-io/chat 0.1.1 → 0.3.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,502 @@ 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
+ /** `true` when the text was shortened to fit the size cap; read the page with `full=true` for it whole. */
233
+ readonly cut?: true | undefined;
234
+ }
235
+
236
+ /** The recorded start of a tool call's output and how many lines it has. */
237
+ export interface ReplyOutput {
238
+ /** The recorded output, its first 4 KB at most; empty when it printed nothing. */
239
+ readonly text: string;
240
+ /** How many lines the recorded output has; a final newline adds no empty line. */
241
+ readonly lines: number;
242
+ /** The server address of the file that holds the whole output, when it was longer than 4 KB. */
243
+ readonly url?: string | undefined;
244
+ /** Whether the recorded output was cut; `url` then holds the rest. */
245
+ readonly truncated?: true | undefined;
246
+ }
247
+
248
+ export interface ReplyThinkingItem {
249
+ readonly kind: "thinking";
250
+ readonly text: string;
251
+ readonly at?: number | undefined;
252
+ /** `true` when the text was shortened to fit the size cap. */
253
+ readonly cut?: true | undefined;
254
+ }
255
+
256
+ export interface ReplyTextItem {
257
+ readonly kind: "text";
258
+ readonly text: string;
259
+ readonly at?: number | undefined;
260
+ /** `true` when the text was shortened to fit the size cap. */
261
+ readonly cut?: true | undefined;
262
+ }
263
+
264
+ export interface ReplyToolItem {
265
+ readonly kind: "tool";
266
+ readonly callId: string;
267
+ readonly name: string;
268
+ readonly input: string | null;
269
+ /** When the call started; absent for a call whose log had no start line. */
270
+ readonly at?: number | undefined;
271
+ /** Absent while the call is still running. */
272
+ readonly durationMs?: number | undefined;
273
+ readonly failed: boolean;
274
+ /** Absent while the call is still running. */
275
+ readonly result?: ToolResult | undefined;
276
+ readonly output: ReplyOutput;
277
+ /** `true` when the input was shortened to fit the size cap. */
278
+ readonly cut?: true | undefined;
279
+ }
280
+
281
+ export type ReplyItem = ReplyThinkingItem | ReplyTextItem | ReplyToolItem;
282
+
283
+ /** The thinking and tool calls one turn did, with the categories they fall in. */
284
+ export interface ReplyProcess {
285
+ readonly categories: readonly ProcessCategory[];
286
+ readonly items: readonly ReplyItem[];
287
+ }
288
+
289
+ /** One reply: its input, its process grouped per turn, and its answer when it finished. */
290
+ export interface ReplyBlock {
291
+ readonly runId: string;
292
+ readonly input: readonly ReplyMessage[];
293
+ readonly process: readonly ReplyProcess[];
294
+ readonly answer?: ReplyMessage | undefined;
295
+ /** How long the reply took, when its harness reported the timings. */
296
+ readonly durationMs?: number | undefined;
297
+ }
298
+
299
+ /** The category a tool name falls in. */
300
+ export function toolCategory(name: string): ProcessCategory {
301
+ const lower = name.toLowerCase();
302
+ if (["read", "ls", "notebookread"].includes(lower)) return "read";
303
+ if (["write", "edit", "multiedit", "notebookedit"].includes(lower)) return "edit";
304
+ if (["bash", "shell", "shell_command", "command", "terminal", "exec", "run"].includes(lower)) return "run";
305
+ if (["grep", "glob", "search", "websearch", "webfetch", "find"].includes(lower)) return "search";
306
+ return "other";
307
+ }
308
+
309
+ function lineCount(text: string): number {
310
+ const clean = text.replace(/\r\n/g, "\n").replace(/\n+$/, "");
311
+ return clean.length === 0 ? 0 : clean.split("\n").length;
312
+ }
313
+
314
+ function replyOutput(
315
+ text: string | null | undefined,
316
+ path: string | undefined,
317
+ truncated: boolean | undefined,
318
+ home: string | undefined,
319
+ ): ReplyOutput {
320
+ const said = text ?? "";
321
+ const url = path === undefined || home === undefined ? undefined : attachmentUrl(home, path);
322
+ return {
323
+ text: said,
324
+ lines: lineCount(said),
325
+ ...(url === undefined ? {} : { url }),
326
+ ...(truncated === true ? { truncated: true as const } : {}),
327
+ };
328
+ }
329
+
330
+ function replyItemOfEntry(entry: Entry, home: string | undefined): ReplyItem | undefined {
331
+ if (entry.kind === "tool") {
332
+ return {
333
+ kind: "tool",
334
+ callId: entry.callId ?? "",
335
+ name: entry.toolName ?? "tool",
336
+ input: entry.input ?? null,
337
+ ...(typeof entry.startedAt === "number" ? { at: entry.startedAt } : {}),
338
+ ...(entry.durationMs === undefined ? {} : { durationMs: entry.durationMs }),
339
+ failed: entry.result === "failed",
340
+ result: entry.result,
341
+ output: replyOutput(entry.output, entry.outputPath, entry.outputTruncated || entry.outputPath !== undefined, home),
342
+ };
343
+ }
344
+ if (entry.kind !== "text" && entry.kind !== "thinking") return undefined;
345
+ const text = entry.text?.trim();
346
+ if (text === undefined || text.length === 0) return undefined;
347
+ return {
348
+ kind: entry.kind,
349
+ text,
350
+ ...(typeof entry.startedAt === "number" ? { at: entry.startedAt } : {}),
351
+ };
352
+ }
353
+
354
+ function replyItemOfFold(entry: FoldEntry, secrets: readonly string[]): ReplyItem | undefined {
355
+ if (entry.kind === "tool") {
356
+ return {
357
+ kind: "tool",
358
+ callId: maskSecrets(entry.callId, secrets),
359
+ name: maskSecrets(entry.toolName, secrets),
360
+ input: entry.input === null ? null : maskSecrets(entry.input, secrets),
361
+ ...(entry.at === null ? {} : { at: entry.at }),
362
+ durationMs: entry.durationMs,
363
+ failed: entry.result === "failed",
364
+ result: entry.result,
365
+ output: replyOutput(
366
+ entry.output === null ? null : maskSecrets(entry.output, secrets),
367
+ undefined,
368
+ entry.outputTruncated,
369
+ undefined,
370
+ ),
371
+ };
372
+ }
373
+ const text = maskSecrets(entry.text, secrets).trim();
374
+ if (text.length === 0) return undefined;
375
+ return {
376
+ kind: entry.kind,
377
+ text,
378
+ ...(entry.at === undefined ? {} : { at: entry.at }),
379
+ };
380
+ }
381
+
382
+ function replyItemOfOpenCall(
383
+ call: { readonly callId: string; readonly toolName: string; readonly input: string | null; readonly at: number; readonly output: string | null; readonly outputTruncated: boolean },
384
+ secrets: readonly string[],
385
+ ): ReplyToolItem {
386
+ return {
387
+ kind: "tool",
388
+ callId: maskSecrets(call.callId, secrets),
389
+ name: maskSecrets(call.toolName, secrets),
390
+ input: call.input === null ? null : maskSecrets(call.input, secrets),
391
+ at: call.at,
392
+ failed: false,
393
+ output: replyOutput(
394
+ call.output === null ? null : maskSecrets(call.output, secrets),
395
+ undefined,
396
+ call.outputTruncated,
397
+ undefined,
398
+ ),
399
+ };
400
+ }
401
+
402
+ function addCategory(categories: ProcessCategory[], name: string): void {
403
+ const category = toolCategory(name);
404
+ if (!categories.includes(category)) categories.push(category);
405
+ }
406
+
407
+ interface OpenGroups {
408
+ readonly groups: { readonly categories: ProcessCategory[]; readonly items: ReplyItem[] }[];
409
+ categories: ProcessCategory[];
410
+ items: ReplyItem[];
411
+ }
412
+
413
+ function openGroups(): OpenGroups {
414
+ return { groups: [], categories: [], items: [] };
415
+ }
416
+
417
+ function closeGroup(state: OpenGroups): void {
418
+ if (state.items.length > 0) state.groups.push({ categories: state.categories, items: state.items });
419
+ state.categories = [];
420
+ state.items = [];
421
+ }
422
+
423
+ function appendItem(state: OpenGroups, item: ReplyItem): void {
424
+ state.items.push(item);
425
+ if (item.kind === "tool") addCategory(state.categories, item.name);
426
+ }
427
+
428
+ /** The process of one turn's facts, split where a message the reply took arrived. */
429
+ function processOf(chunk: Chunk, home: string | undefined, extra: readonly ReplyItem[] = []): readonly ReplyProcess[] {
430
+ const events: { readonly at?: number | undefined; readonly order: number; readonly message?: Message; readonly item?: ReplyItem }[] = [];
431
+ for (const fact of turnFacts(chunk.facts)) {
432
+ const message = fact.type === MESSAGE_FACT ? messageFrom(fact) : undefined;
433
+ if (message?.role === "user") {
434
+ events.push({ at: shownAt(fact), order: events.length, message });
435
+ continue;
436
+ }
437
+ if (fact.type !== ENTRY_FACT) continue;
438
+ const entry = entryOfFact(fact);
439
+ const item = entry === undefined ? undefined : replyItemOfEntry(entry, home);
440
+ if (item !== undefined) events.push({ ...(item.at === undefined ? {} : { at: item.at }), order: events.length, item });
441
+ }
442
+ // The log's unfinished items follow the facts; their times put them before a
443
+ // message that arrived while the reply was still writing.
444
+ for (const item of extra) events.push({ ...(item.at === undefined ? {} : { at: item.at }), order: events.length, item });
445
+ if (extra.length > 0) {
446
+ const times = events.flatMap((event) => (event.at === undefined ? [] : [event.at]));
447
+ const fallback = times.length === 0 ? Number.MAX_SAFE_INTEGER : Math.max(...times);
448
+ events.sort(
449
+ (left, right) => (left.at ?? fallback) - (right.at ?? fallback) || left.order - right.order,
450
+ );
451
+ }
452
+ const state = openGroups();
453
+ for (const event of events) {
454
+ if (event.message !== undefined) closeGroup(state);
455
+ else if (event.item !== undefined) appendItem(state, event.item);
456
+ }
457
+ closeGroup(state);
458
+ return state.groups;
459
+ }
460
+
461
+ function processOfItems(items: readonly ReplyItem[]): readonly ReplyProcess[] {
462
+ if (items.length === 0) return [];
463
+ const state = openGroups();
464
+ for (const item of items) appendItem(state, item);
465
+ closeGroup(state);
466
+ return state.groups;
467
+ }
468
+
469
+ function replyMessage(message: Message): ReplyMessage {
470
+ return { id: message.id, text: message.text, at: message.at };
471
+ }
472
+
473
+ function messagesInTime(messages: readonly Message[]): readonly ReplyMessage[] {
474
+ return [...messages].sort((left, right) => left.sequence - right.sequence).map(replyMessage);
475
+ }
476
+
477
+ interface LiveReply {
478
+ readonly runId: string;
479
+ readonly items: readonly ReplyItem[];
480
+ }
481
+
482
+ /** The structured form of each reply, with the live reply's unfinished items when one runs. */
483
+ interface BuiltReply {
484
+ readonly block: ReplyBlock;
485
+ /** The finished chunk the reply came from; absent for a reply still being written. */
486
+ readonly chunk?: Chunk | undefined;
487
+ /** The answer's fact position; absent while the reply is still being written. */
488
+ readonly answerSequence?: number | undefined;
489
+ }
490
+
491
+ /** The assistant message a chunk ends with, when it has one. */
492
+ function answerIn(chunk: Chunk): Message | undefined {
493
+ return chunk.facts
494
+ .map((fact) => (fact.type === MESSAGE_FACT ? messageFrom(fact) : undefined))
495
+ .find((message) => message?.role === "assistant");
496
+ }
497
+
498
+ /** The last answer before `sequence`, so a window's first reply still names its input. */
499
+ function answerBefore(chunks: readonly Chunk[], sequence: number): number {
500
+ let previous = -1;
501
+ for (const chunk of chunks) {
502
+ const answer = answerIn(chunk);
503
+ if (answer === undefined) continue;
504
+ if (answer.sequence >= sequence) break;
505
+ previous = answer.sequence;
506
+ }
507
+ return previous;
508
+ }
509
+
510
+ /**
511
+ * The replies already finished among `chunks`, in order. `previousAnswer` is
512
+ * the answer before the first chunk, so a page or a read after a mark builds
513
+ * only the replies it carries while keeping an older reply's input right.
514
+ */
515
+ function storedReplies(
516
+ chunks: readonly Chunk[],
517
+ messages: readonly Message[],
518
+ home: string | undefined,
519
+ previousAnswer = -1,
520
+ ): readonly BuiltReply[] {
521
+ const byId = new Map(messages.map((message) => [message.id, message]));
522
+ const blocks: BuiltReply[] = [];
523
+ let previous = previousAnswer;
524
+ for (const chunk of chunks) {
525
+ const answer = answerIn(chunk);
526
+ if (answer === undefined) continue;
527
+ const runId = answer.runId ?? chunk.runId;
528
+ if (runId === undefined) continue;
529
+ const named = answer.replyTo === undefined || answer.replyTo.length === 0
530
+ ? []
531
+ : answer.replyTo
532
+ .map((id) => byId.get(id))
533
+ .filter((message): message is Message => message !== undefined && message.role === "user");
534
+ const input = named.length > 0
535
+ ? named
536
+ : messages.filter(
537
+ (message) =>
538
+ message.role === "user" &&
539
+ message.sequence > previous &&
540
+ message.sequence < answer.sequence,
541
+ );
542
+ blocks.push({
543
+ block: {
544
+ runId,
545
+ input: messagesInTime(input),
546
+ process: processOf(chunk, home),
547
+ answer: replyMessage(answer),
548
+ ...(answer.timings === undefined ? {} : { durationMs: answer.timings.totalMs }),
549
+ },
550
+ chunk,
551
+ answerSequence: answer.sequence,
552
+ });
553
+ previous = answer.sequence;
554
+ }
555
+ return blocks;
556
+ }
557
+
558
+ /** The one reply still being written, with the log's unfinished items. */
559
+ function liveReply(
560
+ facts: readonly PluginFact[],
561
+ messages: readonly Message[],
562
+ live: LiveReply,
563
+ home: string | undefined,
564
+ ): BuiltReply | undefined {
565
+ const chunks = chunksOf(facts);
566
+ let target = -1;
567
+ chunks.forEach((chunk, index) => {
568
+ if (chunk.runId === live.runId) target = index;
569
+ });
570
+ const chunk = target < 0 ? undefined : chunks[target];
571
+ const answer = chunk?.facts
572
+ .map((fact) => (fact.type === MESSAGE_FACT ? messageFrom(fact) : undefined))
573
+ .find((message) => message?.role === "assistant");
574
+ if (chunk !== undefined && answer === undefined) {
575
+ return {
576
+ block: {
577
+ runId: chunk.runId ?? live.runId,
578
+ input: messagesInTime(unanswered(messages, facts)),
579
+ process: processOf(chunk, home, live.items),
580
+ },
581
+ chunk,
582
+ };
583
+ }
584
+ const pending = unanswered(messages, facts);
585
+ if (pending.length === 0 && live.items.length === 0) return undefined;
586
+ return {
587
+ block: {
588
+ runId: live.runId,
589
+ input: messagesInTime(pending),
590
+ process: processOfItems(live.items),
591
+ },
592
+ };
593
+ }
594
+
595
+ function jsonBytes(value: unknown): number {
596
+ return Buffer.byteLength(JSON.stringify(value), "utf8");
597
+ }
598
+
599
+ /**
600
+ * The transcript's data, cut to fit its budget: tool output text first, then
601
+ * the other reply text, and at last the oldest reply blocks. A read that still
602
+ * did not fit would be refused, so this always answers within the budget.
603
+ * Every reply is measured once and a running total is kept, so the work is
604
+ * linear in the size of the page; `measure` is a seam for tests.
605
+ */
606
+ export function replyData(
607
+ replies: readonly ReplyBlock[],
608
+ maxBytes: number,
609
+ base: Readonly<Record<string, JsonValue>> = {},
610
+ measure: (value: unknown) => number = jsonBytes,
611
+ ): Readonly<Record<string, JsonValue>> {
612
+ const data = (shown: readonly ReplyBlock[], extra: Readonly<Record<string, JsonValue>> = base) =>
613
+ ({ ...extra, replies: shown }) as unknown as Readonly<Record<string, JsonValue>>;
614
+ const whole = data(replies);
615
+ if (measure(whole) <= maxBytes) return whole;
616
+ // A tool's output is the largest part and the least useful to a structured
617
+ // client, so it goes first, keeping its line count and `truncated`.
618
+ const blanked = replies.map((reply) => ({
619
+ ...reply,
620
+ process: reply.process.map((group) => ({
621
+ ...group,
622
+ items: group.items.map((item) => {
623
+ if (item.kind !== "tool" || item.output.text.length === 0) return item;
624
+ return {
625
+ ...item,
626
+ output: { ...item.output, text: "", truncated: true as const },
627
+ };
628
+ }),
629
+ })),
630
+ }));
631
+ // The page's size is the wrapper (the base and an empty list), each reply,
632
+ // and the commas between replies; each part is measured once.
633
+ const overhead = measure(data([]));
634
+ const sizes = blanked.map((reply) => measure(reply));
635
+ let sum = sizes.reduce((total, size) => total + size, 0);
636
+ const sizeOf = (count: number, inner: number): number => overhead + inner + Math.max(0, count - 1);
637
+ if (sizeOf(blanked.length, sum) <= maxBytes) return data(blanked);
638
+ // Thinking, text, input and answer text are shortened next, the oldest reply
639
+ // first and whole reply by whole reply: a reply is cut only when every older
640
+ // one is already at the smallest cap, so the newest stays whole the longest.
641
+ const cuts: ReplyBlock[] = [...blanked];
642
+ for (let at = 0; at < blanked.length; at += 1) {
643
+ const original = blanked[at];
644
+ if (original === undefined) continue;
645
+ for (const cap of [512, 128, 32, 0]) {
646
+ const cut = cutReply(original, cap);
647
+ const size = measure(cut);
648
+ sum += size - (sizes[at] ?? 0);
649
+ sizes[at] = size;
650
+ cuts[at] = cut;
651
+ if (sizeOf(cuts.length, sum) <= maxBytes) return data(cuts);
652
+ }
653
+ }
654
+ // Even empty text leaves too much structure: the oldest replies go.
655
+ for (let drop = 1; drop <= cuts.length; drop += 1) {
656
+ sum -= sizes[drop - 1] ?? 0;
657
+ if (sizeOf(cuts.length - drop, sum) <= maxBytes) return data(cuts.slice(drop));
658
+ }
659
+ // The base is the only thing left; it is small in every caller but is cut
660
+ // last rather than letting the read be refused.
661
+ if (overhead <= maxBytes) return data([]);
662
+ return (measure({ replies: [] }) <= maxBytes ? { replies: [] } : {}) as Readonly<Record<string, JsonValue>>;
663
+ }
664
+
665
+ /** Text cut to fit a byte budget, ending with an ellipsis when it was longer. */
666
+ function shorten(text: string, capBytes: number): string {
667
+ if (capBytes <= 0) return "";
668
+ if (Buffer.byteLength(text, "utf8") <= capBytes) return text;
669
+ if (capBytes <= 3) return "";
670
+ let end = Math.min(text.length, capBytes);
671
+ while (end > 0 && Buffer.byteLength(text.slice(0, end), "utf8") + 3 > capBytes) end -= 1;
672
+ return end === 0 ? "" : `${text.slice(0, end)}…`;
673
+ }
674
+
675
+ /** One reply with its free text cut to a budget; every text that got shorter says `cut`. */
676
+ function cutReply(reply: ReplyBlock, capBytes: number): ReplyBlock {
677
+ const text = (original: string): { readonly text: string; readonly cut?: true } => {
678
+ const shortened = shorten(original, capBytes);
679
+ return shortened === original ? { text: shortened } : { text: shortened, cut: true };
680
+ };
681
+ const message = (block: ReplyMessage): ReplyMessage => ({ ...block, ...text(block.text) });
682
+ const item = (entry: ReplyItem): ReplyItem => {
683
+ if (entry.kind === "tool") {
684
+ if (entry.input === null) return entry;
685
+ const shortened = shorten(entry.input, capBytes);
686
+ return shortened === entry.input ? entry : { ...entry, input: shortened, cut: true };
687
+ }
688
+ return { ...entry, ...text(entry.text) };
689
+ };
690
+ return {
691
+ ...reply,
692
+ input: reply.input.map(message),
693
+ ...(reply.answer === undefined ? {} : { answer: message(reply.answer) }),
694
+ process: reply.process.map((group) => ({
695
+ ...group,
696
+ items: group.items.map(item),
697
+ })),
698
+ };
699
+ }
700
+
170
701
  /** 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 {
702
+ function entryMarkdown(entry: Entry | FoldEntry, speaker: string, harness: string): string | undefined {
703
+ // A failure line is shown for every harness; it is already one plain line.
704
+ if (entry.kind === "failure") {
705
+ const said = flat(entry.text ?? "");
706
+ return said.length === 0 ? undefined : said;
707
+ }
708
+ if (entry.kind === "worktree") {
709
+ const said = flat(entry.text ?? "");
710
+ return said.length === 0 ? undefined : said;
711
+ }
712
+ // The line a crash or restart leaves is shown for every harness, as a failure is.
713
+ if (entry.kind === "stopped" && entry.interrupted === true) {
714
+ const said = flat(entry.text ?? "");
715
+ return said.length === 0 ? undefined : said;
716
+ }
172
717
  // Radian gives no text or thinking increments; its chats show the tool lines only.
173
718
  if (entry.kind !== "tool" && harness === "radian") return undefined;
174
719
  if (entry.kind === "tool") return toolMarkdown(entry);
@@ -179,22 +724,10 @@ function entryMarkdown(entry: Entry, speaker: string, harness: string): string |
179
724
  .map((line) => `> ${line}`)
180
725
  .join("\n");
181
726
  }
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;
727
+ const said = block(entry.text);
728
+ if (said.length === 0) return undefined;
729
+ const body = `**${speaker}:** ${said}`;
730
+ return entry.kind === "stopped" ? `${body}\n\n*stopped*` : body;
198
731
  }
199
732
 
200
733
  interface Chunk {
@@ -202,18 +735,114 @@ interface Chunk {
202
735
  /** How many messages, not entries, the chunk holds. */
203
736
  readonly messages: number;
204
737
  readonly last: number;
738
+ /** The run a run chunk belongs to; absent for a message or older chunk. */
739
+ readonly runId?: string | undefined;
205
740
  }
206
741
 
207
- function chunkOf(facts: readonly PluginFact[]): Chunk {
742
+ function chunkOf(facts: readonly PluginFact[], runId?: string): Chunk {
208
743
  return {
209
744
  facts,
210
- messages: facts.filter((fact) => fact.type === MESSAGE_FACT).length,
745
+ messages: facts.filter((fact) => fact.type === MESSAGE_FACT || fact.type === COMMAND_FACT).length,
211
746
  last: facts.at(-1)?.sequence ?? 0,
747
+ ...(runId === undefined ? {} : { runId }),
212
748
  };
213
749
  }
214
750
 
751
+ /** The facts a turn shows: messages, commands, withdraw entries and finished entries. */
752
+ function shownFact(fact: PluginFact): boolean {
753
+ if (fact.type === MESSAGE_CHANGE_FACT) return messageChangeOfFact(fact)?.kind === "withdraw";
754
+ return fact.type === MESSAGE_FACT || fact.type === COMMAND_FACT || fact.type === ENTRY_FACT;
755
+ }
756
+
757
+ /** What one run took: the messages its reply or answer fact names, and whether either says so. */
758
+ interface RunTaken {
759
+ readonly ids: ReadonlySet<string>;
760
+ readonly known: boolean;
761
+ }
762
+
763
+ /**
764
+ * The messages each run took. A reply names them in `replyTo`; a run that ended
765
+ * without a reply names the ones it took in `chat.answered`. A run with neither
766
+ * says nothing, so an older chat keeps the order it recorded.
767
+ */
768
+ function takenByRun(facts: readonly PluginFact[]): ReadonlyMap<string, RunTaken> {
769
+ const found = new Map<string, { readonly ids: Set<string>; known: boolean }>();
770
+ const add = (runId: unknown, ids: readonly string[], known: boolean): void => {
771
+ if (typeof runId !== "string" || runId.length === 0) return;
772
+ const run = found.get(runId) ?? { ids: new Set<string>(), known: false };
773
+ for (const id of ids) run.ids.add(id);
774
+ run.known = run.known || known;
775
+ found.set(runId, run);
776
+ };
777
+ for (const fact of facts) {
778
+ if (fact.type === MESSAGE_FACT && fact.data.role === "assistant") {
779
+ const replyTo = fact.data.replyTo;
780
+ const ids = Array.isArray(replyTo)
781
+ ? replyTo.filter((id): id is string => typeof id === "string" && id.length > 0)
782
+ : [];
783
+ add(fact.data.runId, ids, Array.isArray(replyTo));
784
+ } else if (fact.type === ANSWER_FACT) {
785
+ add(fact.data.runId, answeredOfFact(fact), true);
786
+ }
787
+ }
788
+ return found;
789
+ }
790
+
791
+ interface RunChunk {
792
+ readonly chunk: Chunk;
793
+ readonly span: number;
794
+ }
795
+
796
+ /**
797
+ * The chunks of each run, from the run fact to its reply. A message the run
798
+ * took while it wrote is in that span, so it is ordered with the run's items
799
+ * rather than left as a chunk above all of them. A message the run did not take
800
+ * waits for the next round, so it stays out of the reply's items. Content before
801
+ * the first run fact, and a store that predates run facts, keeps the older
802
+ * chunking.
803
+ */
804
+ function runChunks(
805
+ facts: readonly PluginFact[],
806
+ ): { readonly chunks: readonly RunChunk[]; readonly consumed: ReadonlySet<number>; readonly spans: readonly number[] } | undefined {
807
+ const starts: { readonly index: number; readonly runId: string }[] = [];
808
+ facts.forEach((fact, index) => {
809
+ if (fact.type === RUN_FACT && typeof fact.data.runId === "string" && fact.data.runId.length > 0) {
810
+ starts.push({ index, runId: fact.data.runId });
811
+ }
812
+ });
813
+ if (starts.length === 0) return undefined;
814
+ const taken = takenByRun(facts);
815
+ const spans = facts.map(() => -1);
816
+ const chunks: RunChunk[] = [];
817
+ const consumed = new Set<number>();
818
+ starts.forEach((start, at) => {
819
+ const end = starts[at + 1]?.index ?? facts.length;
820
+ for (let index = start.index; index < end; index += 1) spans[index] = start.index;
821
+ const took = taken.get(start.runId);
822
+ let turn: PluginFact[] = [];
823
+ for (let index = start.index + 1; index < end; index += 1) {
824
+ const fact = facts[index];
825
+ if (fact === undefined || !shownFact(fact)) continue;
826
+ // A person's message that this run's reply does not name was not given
827
+ // to the agent; it is the next round's, not part of this reply.
828
+ if (fact.type === MESSAGE_FACT && fact.data.role === "user") {
829
+ const id = typeof fact.data.id === "string" ? fact.data.id : undefined;
830
+ if (id !== undefined && took?.known === true && !took.ids.has(id)) continue;
831
+ }
832
+ turn.push(fact);
833
+ consumed.add(index);
834
+ if (fact.type === MESSAGE_FACT && fact.data.role === "assistant" && fact.data.runId === start.runId) {
835
+ chunks.push({ chunk: chunkOf(turn, start.runId), span: start.index });
836
+ turn = [];
837
+ }
838
+ }
839
+ if (turn.length > 0) chunks.push({ chunk: chunkOf(turn, start.runId), span: start.index });
840
+ });
841
+ return { chunks, consumed, spans };
842
+ }
843
+
215
844
  /** 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[] {
845
+ function legacyChunksOf(facts: readonly PluginFact[]): readonly Chunk[] {
217
846
  const replies = new Map<string, number[]>();
218
847
  const indexes = new Map<number, number>();
219
848
  facts.forEach((fact, index) => {
@@ -251,12 +880,74 @@ function chunksOf(facts: readonly PluginFact[]): readonly Chunk[] {
251
880
  index = end;
252
881
  continue;
253
882
  }
254
- if (fact.type === MESSAGE_FACT) chunks.push(chunkOf([fact]));
883
+ if (
884
+ fact.type === MESSAGE_FACT ||
885
+ fact.type === COMMAND_FACT ||
886
+ (fact.type === MESSAGE_CHANGE_FACT && messageChangeOfFact(fact)?.kind === "withdraw")
887
+ ) {
888
+ chunks.push(chunkOf([fact]));
889
+ }
255
890
  index += 1;
256
891
  }
257
892
  return chunks;
258
893
  }
259
894
 
895
+ function chunksOf(facts: readonly PluginFact[]): readonly Chunk[] {
896
+ const runs = runChunks(facts);
897
+ if (runs === undefined) return legacyChunksOf(facts);
898
+ // A chunk carries the run span it belongs to. A run's own chunks come before
899
+ // what its span left out: a message it did not take waits above the next
900
+ // round, below this reply, rather than splitting the reply's items.
901
+ const placed: { readonly chunk: Chunk; readonly span: number; readonly after: boolean }[] = runs.chunks.map(
902
+ (run) => ({ chunk: run.chunk, span: run.span, after: false }),
903
+ );
904
+ const rest = (first: number, chunk: Chunk): void => {
905
+ placed.push({ chunk, span: runs.spans[first] ?? -1, after: true });
906
+ };
907
+ let index = 0;
908
+ while (index < facts.length) {
909
+ if (runs.consumed.has(index)) {
910
+ index += 1;
911
+ continue;
912
+ }
913
+ const fact = facts[index];
914
+ if (fact === undefined) break;
915
+ if (
916
+ fact.type === MESSAGE_FACT ||
917
+ fact.type === COMMAND_FACT ||
918
+ (fact.type === MESSAGE_CHANGE_FACT && messageChangeOfFact(fact)?.kind === "withdraw")
919
+ ) {
920
+ rest(index, chunkOf([fact]));
921
+ index += 1;
922
+ continue;
923
+ }
924
+ if (fact.type === ENTRY_FACT) {
925
+ const runId = typeof fact.data.runId === "string" ? fact.data.runId : undefined;
926
+ let end = index + 1;
927
+ while (
928
+ end < facts.length &&
929
+ !runs.consumed.has(end) &&
930
+ facts[end]?.type === ENTRY_FACT &&
931
+ (runId === undefined || facts[end]?.data.runId === runId)
932
+ ) {
933
+ end += 1;
934
+ }
935
+ rest(index, chunkOf(facts.slice(index, end)));
936
+ index = end;
937
+ continue;
938
+ }
939
+ index += 1;
940
+ }
941
+ return placed
942
+ .sort(
943
+ (left, right) =>
944
+ left.span - right.span ||
945
+ (left.after === right.after ? 0 : left.after ? 1 : -1) ||
946
+ (left.chunk.facts[0]?.sequence ?? 0) - (right.chunk.facts[0]?.sequence ?? 0),
947
+ )
948
+ .map((item) => item.chunk);
949
+ }
950
+
260
951
  interface Page {
261
952
  readonly chunks: readonly Chunk[];
262
953
  readonly after: number | undefined;
@@ -302,6 +993,29 @@ function cursorAfter(cursor: string): number | undefined {
302
993
  return value.kind === "facts" && typeof value.after === "number" ? value.after : undefined;
303
994
  }
304
995
 
996
+ /** When one shown item happened, for ordering a turn with a message sent during it. */
997
+ function shownAt(fact: PluginFact): number {
998
+ const entry = fact.type === ENTRY_FACT ? entryOfFact(fact) : undefined;
999
+ return entry !== undefined && typeof entry.startedAt === "number" ? entry.startedAt : fact.at;
1000
+ }
1001
+
1002
+ /**
1003
+ * The facts of a turn in time order, when the entries carry times. A store whose
1004
+ * entries carry none keeps the order it recorded, so an older chat reads as it
1005
+ * always did. Messages and commands always carry their fact's time.
1006
+ */
1007
+ function turnFacts(facts: readonly PluginFact[]): readonly PluginFact[] {
1008
+ const timed = facts.some((fact) => {
1009
+ const entry = fact.type === ENTRY_FACT ? entryOfFact(fact) : undefined;
1010
+ return entry !== undefined && typeof entry.startedAt === "number";
1011
+ });
1012
+ if (!timed) return facts;
1013
+ return facts
1014
+ .map((fact, index) => ({ fact, index, at: shownAt(fact) }))
1015
+ .sort((left, right) => left.at - right.at || left.index - right.index)
1016
+ .map((item) => item.fact);
1017
+ }
1018
+
305
1019
  function rendered(chunk: Chunk, speaker: string, home: string | undefined, harness: string): readonly string[] {
306
1020
  const blocks: string[] = [];
307
1021
  let lines: string[] = [];
@@ -309,7 +1023,19 @@ function rendered(chunk: Chunk, speaker: string, home: string | undefined, harne
309
1023
  if (lines.length > 0) blocks.push(lines.join("\n"));
310
1024
  lines = [];
311
1025
  };
312
- for (const fact of chunk.facts) {
1026
+ for (const fact of turnFacts(chunk.facts)) {
1027
+ if (fact.type === COMMAND_FACT) {
1028
+ flush();
1029
+ const command = commandOfFact(fact);
1030
+ if (command !== undefined) blocks.push(commandMarkdown(command));
1031
+ continue;
1032
+ }
1033
+ if (fact.type === MESSAGE_CHANGE_FACT) {
1034
+ flush();
1035
+ const change = messageChangeOfFact(fact);
1036
+ if (change?.kind === "withdraw") blocks.push(withdrawalMarkdown(change));
1037
+ continue;
1038
+ }
313
1039
  if (fact.type === ENTRY_FACT) {
314
1040
  const entry = entryOfFact(fact);
315
1041
  const markdown = entry === undefined ? undefined : entryMarkdown(entry, speaker, harness);
@@ -338,85 +1064,390 @@ function clock(at: number): string {
338
1064
  return new Date(at).toISOString().slice(11, 19);
339
1065
  }
340
1066
 
1067
+ /** The changing part of a transcript: its tail, what the reply is doing, and where finished content pauses. */
1068
+ interface Live {
1069
+ readonly tail?: string | undefined;
1070
+ readonly status?: SectionStatus | undefined;
1071
+ readonly retry?: SectionRetry | undefined;
1072
+ /** The last fact before a message the live tail holds, so a client reads it again with the reply. */
1073
+ readonly cut?: number | undefined;
1074
+ /** The run still being written, so its structured reply can take the unfinished items. */
1075
+ readonly run?: string | undefined;
1076
+ /** The process items the log holds and the facts do not, oldest first. */
1077
+ readonly items?: readonly ReplyItem[] | undefined;
1078
+ }
1079
+
1080
+ /** One line for a model request the agent is waiting to try again. */
1081
+ function retryMarkdown(retry: SectionRetry): string {
1082
+ const reason = flat(retry.reason);
1083
+ return `Retrying the model request (${retry.attempt} of ${retry.maxAttempts})${reason.length === 0 ? "" : `: ${reason}`}`;
1084
+ }
1085
+
1086
+ interface TailItem {
1087
+ readonly at?: number | undefined;
1088
+ readonly order: number;
1089
+ readonly markdown: string;
1090
+ readonly item?: ReplyItem | undefined;
1091
+ }
1092
+
1093
+ /**
1094
+ * The person's messages a reply still owes an answer. A reply recorded before
1095
+ * `replyTo` existed answers every message before it, so an old snapshot that
1096
+ * ends with an assistant message is not left looking unanswered.
1097
+ */
1098
+ function statusPending(messages: readonly Message[], facts: readonly PluginFact[]): readonly Message[] {
1099
+ const pending = unanswered(messages, facts);
1100
+ if (pending.length === 0) return pending;
1101
+ const legacy = messages.filter(
1102
+ (message) => message.role === "assistant" && (message.replyTo === undefined || message.replyTo.length === 0),
1103
+ );
1104
+ return pending.filter((message) => !legacy.some((reply) => reply.sequence > message.sequence));
1105
+ }
1106
+
1107
+ /**
1108
+ * What the reply is doing, or undefined when nothing of it is in progress. A
1109
+ * question waiting for the person, a failure, a stop and a chat whose messages
1110
+ * are all answered say nothing. Before the log has the ready line, the first
1111
+ * message still unanswered is what the reply waits on.
1112
+ */
1113
+ function statusOf(
1114
+ facts: readonly PluginFact[],
1115
+ pending: readonly Message[],
1116
+ runId: string | undefined,
1117
+ times: Awaited<ReturnType<NonNullable<ViewContext["runTimes"]>>>,
1118
+ read: TailRead | undefined,
1119
+ called: ReadonlySet<string>,
1120
+ secrets: readonly string[],
1121
+ ): SectionStatus | undefined {
1122
+ const newest = pending.at(-1);
1123
+ if (newest === undefined) return undefined;
1124
+ const last = times?.segments.at(-1);
1125
+ if (last?.person === true && last.to === null) return undefined;
1126
+ // A failure or stop after the newest message that still waits ends the
1127
+ // reply for it. A message that came later starts another reply.
1128
+ let ended = -1;
1129
+ if (runId !== undefined) {
1130
+ for (const fact of facts) {
1131
+ const entry = entryOfFact(fact);
1132
+ if (entry !== undefined && (entry.kind === "failure" || entry.kind === "stopped") && entry.runId === runId) {
1133
+ ended = Math.max(ended, entry.sequence);
1134
+ }
1135
+ if (stopOfFact(fact)?.runId === runId) ended = Math.max(ended, fact.sequence);
1136
+ }
1137
+ }
1138
+ if (ended >= newest.sequence) return undefined;
1139
+ const endedAt = times?.endedAt;
1140
+ if (endedAt !== null && endedAt !== undefined && newest.at <= endedAt) return undefined;
1141
+ const first = pending[0] ?? newest;
1142
+ if (read === undefined || !read.ready) return { text: "Starting", since: first.at };
1143
+ const open = read.state.calls.find((call) => !called.has(maskSecrets(call.callId, secrets)));
1144
+ if (open !== undefined) {
1145
+ return { text: `Running ${maskSecrets(open.toolName, secrets)}`, since: open.at };
1146
+ }
1147
+ return { text: "Thinking", since: read.lastAt ?? times?.startedAt ?? first.at };
1148
+ }
1149
+
1150
+ /** One shown fact as a tail line, for a message the live reply is holding. */
1151
+ function factTailItem(fact: PluginFact, speaker: string, home: string | undefined, harness: string): string | undefined {
1152
+ if (fact.type === COMMAND_FACT) {
1153
+ const command = commandOfFact(fact);
1154
+ return command === undefined ? undefined : commandMarkdown(command);
1155
+ }
1156
+ if (fact.type === ENTRY_FACT) {
1157
+ const entry = entryOfFact(fact);
1158
+ return entry === undefined ? undefined : entryMarkdown(entry, speaker, harness);
1159
+ }
1160
+ if (fact.type === MESSAGE_CHANGE_FACT) {
1161
+ const change = messageChangeOfFact(fact);
1162
+ return change?.kind === "withdraw" ? withdrawalMarkdown(change) : undefined;
1163
+ }
1164
+ if (fact.type !== MESSAGE_FACT) return undefined;
1165
+ const message = messageFrom(fact);
1166
+ return message === undefined ? undefined : messageMarkdown(message, speaker, home);
1167
+ }
1168
+
341
1169
  /**
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.
1170
+ * The tail of a reply that has a message sent during it. The message is a fact
1171
+ * but the reply's items are still in the log: both are put in time order, so
1172
+ * the live tail and the stored transcript place the message alike. `cut` is the
1173
+ * fact before the first such message; finished content stops there until the
1174
+ * run ends or the message can be appended with the rest.
345
1175
  */
346
- async function tailOf(
1176
+ function heldTail(
1177
+ facts: readonly PluginFact[],
1178
+ cut: number,
1179
+ log: readonly TailItem[],
1180
+ speaker: string,
1181
+ home: string | undefined,
1182
+ harness: string,
1183
+ ): string | undefined {
1184
+ const held: TailItem[] = [];
1185
+ for (const fact of facts) {
1186
+ if (fact.sequence <= cut) continue;
1187
+ const markdown = factTailItem(fact, speaker, home, harness);
1188
+ if (markdown === undefined) continue;
1189
+ held.push({ at: shownAt(fact), order: held.length, markdown });
1190
+ }
1191
+ const all = [...held, ...log.map((item, index) => ({ ...item, order: held.length + index }))];
1192
+ const fallback = log.at(-1)?.at ?? 0;
1193
+ const ordered = all
1194
+ .map((item) => ({ ...item, sort: item.at ?? fallback }))
1195
+ .sort((left, right) => left.sort - right.sort || left.order - right.order);
1196
+ const lines = ordered.map((item) => item.markdown).filter((line) => line.trim().length > 0);
1197
+ return lines.length === 0 ? undefined : lines.join("\n\n");
1198
+ }
1199
+
1200
+ /**
1201
+ * What the running reply has written and the facts do not hold yet, as
1202
+ * Markdown, or undefined when no reply runs. It is read from the end of the log
1203
+ * of the step that runs the agent. A finished entry stays here until the fact
1204
+ * that holds it is visible to the same read, so the text never has a gap. The
1205
+ * same read gives the status beside it.
1206
+ */
1207
+ async function liveOf(
347
1208
  ctx: ViewContext,
348
1209
  object: StoredObject,
349
1210
  facts: readonly PluginFact[],
1211
+ messages: readonly Message[],
350
1212
  speaker: string,
351
- ): Promise<string | undefined> {
1213
+ ): Promise<Live> {
352
1214
  const chat = chatData(object.data);
353
1215
  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());
1216
+ const pending = statusPending(messages, facts);
1217
+ const times = runId !== undefined && ctx.runTimes !== undefined ? await ctx.runTimes(runId) : undefined;
1218
+ let tail: string | undefined;
1219
+ let read: TailRead | undefined;
1220
+ let retry: SectionRetry | undefined;
1221
+ let called: ReadonlySet<string> = new Set<string>();
1222
+ let secrets: readonly string[] = [];
1223
+ let cut: number | undefined;
1224
+ let items: readonly ReplyItem[] | undefined;
1225
+ let liveRun: string | undefined;
1226
+ if (runId !== undefined && chat.harness.length > 0 && ctx.runTimes !== undefined && times !== undefined && times.endedAt === null) {
1227
+ liveRun = runId;
1228
+ secrets = await secretValues(ctx);
1229
+ const said = new Set<string>();
1230
+ const calls = new Set<string>();
1231
+ let runStart = -1;
1232
+ for (const fact of facts) {
1233
+ if (fact.type === RUN_FACT && fact.data.runId === runId) runStart = fact.sequence;
1234
+ if (fact.data.runId !== runId) continue;
1235
+ if (fact.type === MESSAGE_FACT && fact.data.role === "assistant" && typeof fact.data.text === "string") {
1236
+ said.add(fact.data.text.trim());
1237
+ }
1238
+ const entry = fact.type === ENTRY_FACT ? entryOfFact(fact) : undefined;
1239
+ if (entry?.kind === "tool" && entry.callId !== undefined) calls.add(entry.callId);
1240
+ else if (entry?.text !== undefined) said.add(entry.text.trim());
1241
+ }
1242
+ called = calls;
1243
+ // A person's message after the run began is inside the reply. Its fact is
1244
+ // already stored while the reply's own items are still in the log.
1245
+ const during = runStart < 0
1246
+ ? undefined
1247
+ : facts.find(
1248
+ (fact) =>
1249
+ fact.sequence > runStart &&
1250
+ fact.type === MESSAGE_FACT &&
1251
+ fact.data.role === "user",
1252
+ );
1253
+ cut = during?.sequence === undefined ? undefined : during.sequence - 1;
1254
+ // The read drops a finished entry the facts already hold, so a long run does
1255
+ // not keep them all in the saved fold.
1256
+ const held = (entry: FoldEntry): boolean => {
1257
+ if (entry.kind === "tool") return calls.has(maskSecrets(entry.callId, secrets));
1258
+ return said.has(maskSecrets(entry.text, secrets).trim());
1259
+ };
1260
+ read = foldLogTail(agentLogPath(ctx.store.root, chat.harness, runId), held);
1261
+ const waiting = read?.state.retry;
1262
+ // The retry's own line stamps when the wait began; a later line's time
1263
+ // would move `until` on every read, so it is not used as a fallback.
1264
+ const retryAt = waiting?.at;
1265
+ retry =
1266
+ waiting === undefined || retryAt === undefined
1267
+ ? undefined
1268
+ : {
1269
+ attempt: waiting.attempt,
1270
+ maxAttempts: waiting.maxAttempts,
1271
+ until: retryAt + waiting.delayMs,
1272
+ reason: maskSecrets(waiting.reason, secrets),
1273
+ };
1274
+ if (read !== undefined) {
1275
+ const fresh = (text: string): string | undefined => {
1276
+ const masked = maskSecrets(text, secrets);
1277
+ return masked.trim().length === 0 || said.has(masked.trim()) ? undefined : masked;
1278
+ };
1279
+ const tailItems: TailItem[] = [];
1280
+ const push = (at: number | null | undefined, markdown: string | undefined, item?: ReplyItem): void => {
1281
+ if (markdown === undefined || markdown.trim().length === 0) return;
1282
+ tailItems.push({
1283
+ ...(at === null || at === undefined ? {} : { at }),
1284
+ order: tailItems.length,
1285
+ markdown,
1286
+ ...(item === undefined ? {} : { item }),
1287
+ });
1288
+ };
1289
+ // A finished entry is shown until the facts hold it; then `said` and `called` drop it.
1290
+ for (const entry of read.state.entries) {
1291
+ // Radian gives no text or thinking increments; its chats show tool lines only.
1292
+ if (chat.harness === "radian" && entry.kind !== "tool") continue;
1293
+ const item = replyItemOfFold(entry, secrets);
1294
+ if (entry.kind === "tool") {
1295
+ if (calls.has(maskSecrets(entry.callId, secrets))) continue;
1296
+ push(
1297
+ entry.at,
1298
+ entryMarkdown(
1299
+ {
1300
+ ...entry,
1301
+ toolName: maskSecrets(entry.toolName, secrets),
1302
+ input: entry.input === null ? null : maskSecrets(entry.input, secrets),
1303
+ error: entry.error === null ? null : maskSecrets(entry.error, secrets),
1304
+ },
1305
+ speaker,
1306
+ chat.harness,
1307
+ ),
1308
+ item,
1309
+ );
1310
+ continue;
1311
+ }
1312
+ const text = fresh(entry.text);
1313
+ if (text === undefined) continue;
1314
+ push(entry.at, entryMarkdown({ ...entry, text }, speaker, chat.harness), item);
1315
+ }
1316
+ // Radian gives no text or thinking increments; its chats show the tool lines only.
1317
+ if (chat.harness !== "radian") {
1318
+ const thinking = fresh(read.state.thinking);
1319
+ if (thinking !== undefined) {
1320
+ push(
1321
+ read.lastAt,
1322
+ thinking.split(/\r?\n/).map((line) => `> ${line}`).join("\n"),
1323
+ { kind: "thinking", text: thinking.trim(), ...(read.lastAt === undefined ? {} : { at: read.lastAt }) },
1324
+ );
1325
+ }
1326
+ const text = fresh(read.state.text);
1327
+ if (text !== undefined) {
1328
+ push(read.lastAt, `**${speaker}:** ${block(text)}`, {
1329
+ kind: "text",
1330
+ text: block(text),
1331
+ ...(read.lastAt === undefined ? {} : { at: read.lastAt }),
1332
+ });
1333
+ }
1334
+ }
1335
+ for (const call of read.state.calls) {
1336
+ if (calls.has(maskSecrets(call.callId, secrets))) continue;
1337
+ const input = call.input === null ? "" : flat(maskSecrets(call.input, secrets));
1338
+ const what = input.length === 0 ? "" : ` ${inlineCode(input.length <= 160 ? input : `${input.slice(0, 159)}…`)}`;
1339
+ push(
1340
+ call.at,
1341
+ `tool ${maskSecrets(call.toolName, secrets)} since ${clock(call.at)}${what}`,
1342
+ replyItemOfOpenCall(call, secrets),
1343
+ );
1344
+ }
1345
+ if (retry !== undefined) push(undefined, retryMarkdown(retry));
1346
+ const structured = tailItems.flatMap((item) => (item.item === undefined ? [] : [item.item]));
1347
+ if (structured.length > 0) items = structured;
1348
+ tail = cut === undefined
1349
+ ? (tailItems.length === 0 ? undefined : tailItems.map((item) => item.markdown).join("\n\n"))
1350
+ : heldTail(facts, cut, tailItems, speaker, ctx.home, chat.harness);
1351
+ } else if (retry !== undefined) {
1352
+ tail = retryMarkdown(retry);
1353
+ }
1354
+ // The log may not exist yet; the mid-run message still belongs in the tail.
1355
+ if (cut !== undefined && tail === undefined) {
1356
+ tail = heldTail(facts, cut, [], speaker, ctx.home, chat.harness);
366
1357
  }
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
1358
  }
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;
1359
+ const status = statusOf(facts, pending, runId, times, read, called, secrets);
1360
+ return {
1361
+ ...(tail === undefined ? {} : { tail }),
1362
+ ...(status === undefined ? {} : { status }),
1363
+ ...(retry === undefined ? {} : { retry }),
1364
+ ...(cut === undefined ? {} : { cut }),
1365
+ ...(liveRun === undefined ? {} : { run: liveRun }),
1366
+ ...(items === undefined ? {} : { items }),
374
1367
  };
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
1368
  }
391
1369
 
392
1370
  async function load(
393
1371
  ctx: ViewContext,
394
1372
  object: StoredObject,
395
1373
  sectionId: string,
396
- options: { readonly cursor?: string | undefined; readonly after?: string | undefined },
1374
+ options: { readonly cursor?: string | undefined; readonly after?: string | undefined; readonly full?: boolean | undefined },
397
1375
  ): Promise<SectionContent> {
398
1376
  if (sectionId !== TRANSCRIPT) return { markdown: "" };
399
1377
  const ref = chatRef(object.id);
400
1378
  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);
1379
+ const read = readChat(ctx.store, object.id);
1380
+ const speaker = await speakerOf(ctx, object, true);
1381
+ const facts = messageFactsInForce(read.facts);
1382
+ const messages = read.messages;
1383
+ const queued = queuedData(queuedMessages(messages, facts));
1384
+ const queueData: Record<string, JsonValue> = {
1385
+ queued: queued as unknown as JsonValue,
1386
+ queuedCount: queued.length,
1387
+ };
1388
+ const live = await liveOf(ctx, object, facts, messages, speaker);
1389
+ const { cut, run: liveRun, items: liveItems, ...liveContent } = live;
1390
+ const liveBlock =
1391
+ liveRun === undefined
1392
+ ? undefined
1393
+ : liveReply(facts, messages, { runId: liveRun, items: liveItems ?? [] }, ctx.home);
1394
+ const limit = options.full === true ? Number.POSITIVE_INFINITY : ctx.sectionCapBytes ?? DEFAULT_SECTION_CAP_BYTES;
1395
+ // A message the live tail holds stays unread as finished content until the
1396
+ // run ends, so the same facts then arrive together with the reply's items.
1397
+ const finished = cut === undefined ? facts : facts.filter((fact) => fact.sequence <= cut);
1398
+ const context = chatContext(object, read);
404
1399
  const since = markAfter(options.after);
1400
+ const finishedChunks = chunksOf(finished);
405
1401
  if (since !== undefined) {
406
1402
  // 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));
1403
+ const chunks = chunksOf(finished.filter((fact) => fact.sequence > since));
408
1404
  const blocks = chunks.flatMap((chunk) => rendered(chunk, speaker, ctx.home, chat.harness));
1405
+ const markdown = blocks.join("\n\n---\n\n");
1406
+ // The replies whose answer is after the mark, and the one still running.
1407
+ const sinceChunks = finishedChunks.filter((chunk) => {
1408
+ const answer = answerIn(chunk);
1409
+ return answer !== undefined && answer.sequence > since;
1410
+ });
1411
+ const firstSince = sinceChunks
1412
+ .map((chunk) => answerIn(chunk)?.sequence)
1413
+ .find((sequence): sequence is number => sequence !== undefined);
1414
+ const changed = storedReplies(
1415
+ sinceChunks,
1416
+ messages,
1417
+ ctx.home,
1418
+ firstSince === undefined ? -1 : answerBefore(finishedChunks, firstSince),
1419
+ );
1420
+ const replies = liveBlock === undefined ? changed : [...changed, liveBlock];
1421
+ const data = replyData(
1422
+ replies.map((reply) => reply.block),
1423
+ Math.max(0, limit - Buffer.byteLength(markdown, "utf8") - Buffer.byteLength(liveContent.tail ?? "", "utf8")),
1424
+ queueData,
1425
+ );
409
1426
  return {
410
- markdown: blocks.join("\n\n---\n\n"),
1427
+ markdown,
411
1428
  mark: markOf(Math.max(since, chunks.at(-1)?.last ?? 0)),
412
1429
  delta: true,
413
- ...(tail === undefined ? {} : { tail }),
1430
+ ...liveContent,
1431
+ ...(context === undefined ? {} : { context }),
1432
+ data,
414
1433
  };
415
1434
  }
416
- const pages = pagesOf(ref, chunksOf(facts));
1435
+ const pages = pagesOf(ref, finishedChunks);
417
1436
  const after = options.cursor === undefined ? undefined : cursorAfter(options.cursor);
418
1437
  const index = pages.findIndex((page) => page.after === after);
419
1438
  const selected = pages[index < 0 ? 0 : index] ?? pages[0];
1439
+ const pageIndex = index < 0 ? 0 : index;
1440
+ const pageChunks = selected?.chunks ?? [];
1441
+ const firstOnPage = pageChunks[0]?.facts[0]?.sequence ?? Number.MAX_SAFE_INTEGER;
1442
+ const onPageBlocks = storedReplies(
1443
+ pageChunks,
1444
+ messages,
1445
+ ctx.home,
1446
+ answerBefore(finishedChunks, firstOnPage),
1447
+ );
1448
+ const pageReplies = pageIndex === pages.length - 1 && liveBlock !== undefined
1449
+ ? [...onPageBlocks, liveBlock]
1450
+ : onPageBlocks;
420
1451
  const blocks = (selected?.chunks ?? []).flatMap((chunk) => rendered(chunk, speaker, ctx.home, chat.harness));
421
1452
  const body = blocks.length === 0 && options.cursor === undefined ? "No messages yet." : blocks.join("\n\n---\n\n");
422
1453
  // Every page says which agent answers, as the row does.
@@ -424,6 +1455,11 @@ async function load(
424
1455
  ? `Agent: ${agentLine(chat)}\n\n${body}`
425
1456
  : body;
426
1457
  const nextPage = index < 0 ? undefined : pages[index + 1];
1458
+ const data = replyData(
1459
+ pageReplies.map((reply) => reply.block),
1460
+ Math.max(0, limit - Buffer.byteLength(markdown, "utf8") - Buffer.byteLength(liveContent.tail ?? "", "utf8")),
1461
+ queueData,
1462
+ );
427
1463
 
428
1464
  // The table of contents: the cursor each page starts at, the first one without.
429
1465
  const toc: SectionPage[] = pages.map((page, at) =>
@@ -436,9 +1472,85 @@ async function load(
436
1472
  mark: markOf(selected?.chunks.at(-1)?.last ?? 0),
437
1473
  ...(nextPage?.cursor === undefined ? {} : { next: nextPage.cursor }),
438
1474
  ...(toc.length > 1 ? { pages: toc } : {}),
439
- ...(tail === undefined ? {} : { tail }),
1475
+ ...liveContent,
1476
+ ...(context === undefined ? {} : { context }),
1477
+ data,
1478
+ };
1479
+ }
1480
+
1481
+ /** Reads an object through its type's `prepare`, or the store when the view has none. */
1482
+ function objectReader(ctx: ViewContext): ObjectReader {
1483
+ return async (type, id) =>
1484
+ ctx.refreshedObject === undefined ? ctx.store.get(type, id) : ctx.refreshedObject(type, id);
1485
+ }
1486
+
1487
+ /**
1488
+ * The changing part of the transcript, for the event stream's live push. It
1489
+ * is the same tail and status a section read returns, without the finished
1490
+ * content, so a client renders what the reply writes as it arrives.
1491
+ */
1492
+ async function tailPush(
1493
+ ctx: ViewContext,
1494
+ object: StoredObject,
1495
+ ): Promise<{ readonly section: string; readonly tail?: string; readonly status?: SectionStatus; readonly retry?: SectionRetry; readonly data?: Readonly<Record<string, JsonValue>> } | undefined> {
1496
+ const read = readChat(ctx.store, object.id);
1497
+ const facts = messageFactsInForce(read.facts);
1498
+ const messages = read.messages;
1499
+ const speaker = await speakerOf(ctx, object);
1500
+ const live = await liveOf(ctx, object, facts, messages, speaker);
1501
+ const liveBlock = live.run === undefined
1502
+ ? undefined
1503
+ : liveReply(facts, messages, { runId: live.run, items: live.items ?? [] }, ctx.home);
1504
+ const limit = ctx.sectionCapBytes ?? DEFAULT_SECTION_CAP_BYTES;
1505
+ const data = liveBlock === undefined
1506
+ ? undefined
1507
+ : replyData(
1508
+ [liveBlock.block],
1509
+ Math.max(0, limit - Buffer.byteLength(live.tail ?? "", "utf8")),
1510
+ );
1511
+ if (live.tail === undefined && live.status === undefined && live.retry === undefined && data === undefined) {
1512
+ return undefined;
1513
+ }
1514
+ return {
1515
+ section: TRANSCRIPT,
1516
+ ...(live.tail === undefined ? {} : { tail: live.tail }),
1517
+ ...(live.status === undefined ? {} : { status: live.status }),
1518
+ ...(live.retry === undefined ? {} : { retry: live.retry }),
1519
+ ...(data === undefined ? {} : { data }),
440
1520
  };
441
1521
  }
442
1522
 
1523
+ /** Whether a requested path is one the chat's own facts name, never one a client chose. */
1524
+ async function file(ctx: ViewContext, object: StoredObject, path: readonly string[]): Promise<boolean> {
1525
+ if (
1526
+ path.length === 0 ||
1527
+ path.some(
1528
+ (part) => part.length === 0 || part === "." || part === ".." || part.includes("/") || part.includes("\\"),
1529
+ )
1530
+ ) {
1531
+ return false;
1532
+ }
1533
+ const requested = join(attachmentDir(ctx.home, CHAT_TYPE, object.id), ...path);
1534
+ const named = new Set<string>();
1535
+ for (const fact of factsOf(ctx.store, chatRef(object.id))) {
1536
+ if (fact.type === MESSAGE_FACT) {
1537
+ for (const attachment of attachmentsOf(fact.data.attachments)) named.add(attachment.path);
1538
+ } else if (fact.type === ENTRY_FACT) {
1539
+ const entry = entryOfFact(fact);
1540
+ if (entry?.outputPath !== undefined) named.add(entry.outputPath);
1541
+ }
1542
+ }
1543
+ return named.has(requested);
1544
+ }
1545
+
443
1546
  /** The views of the chat type. */
444
- export const chatViews: ObjectViews = { row, sections, load };
1547
+ export const chatViews: ObjectViews = {
1548
+ row,
1549
+ sections,
1550
+ context: (ctx, object) => chatContext(object, readChat(ctx.store, object.id)),
1551
+ skills: async (ctx, object) =>
1552
+ skillSummaries(await readChatSkills(chatData(object.data), objectReader(ctx))),
1553
+ file,
1554
+ tail: tailPush,
1555
+ load,
1556
+ };