@operad-io/chat 0.3.0 → 0.4.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.
@@ -0,0 +1,125 @@
1
+ /**
2
+ * The segments of a long chat: each stretch that `/new` or a compaction starts.
3
+ * A segment is named by the sequence of the fact that began it, so a title
4
+ * recorded for it keeps meaning the same stretch as the chat grows.
5
+ */
6
+
7
+ import type { PluginFact } from "@operad-io/engine";
8
+ import { COMMAND_FACT, MESSAGE_FACT, NEW_FACT, type Message } from "./model.ts";
9
+
10
+ /** A title made for a segment after its first exchange. */
11
+ export const SEGMENT_TITLE_FACT = "chat.segment_title";
12
+
13
+ /** The longest a segment's title is, in characters. */
14
+ export const SEGMENT_TITLE_MAX = 80;
15
+
16
+ /** How a segment began: the chat's start, a `/new`, or a compaction. */
17
+ export type SegmentKind = "first" | "new" | "compact";
18
+
19
+ /** One segment of a chat. */
20
+ export interface Segment {
21
+ /** Counting from 1, in order. */
22
+ readonly number: number;
23
+ /** The sequence of the fact that began it; 0 for the first. */
24
+ readonly sequence: number;
25
+ /** When it began, in milliseconds since the epoch. */
26
+ readonly at: number;
27
+ readonly kind: SegmentKind;
28
+ /** The goal of `/new`, the generated title, or the chat's own title for the first. Empty when none exists yet. */
29
+ readonly title: string;
30
+ }
31
+
32
+ /** One line, cut to what a marker and a list show. */
33
+ export function titleLine(text: string): string {
34
+ const flat = text.replace(/\s+/gu, " ").trim();
35
+ return flat.length <= SEGMENT_TITLE_MAX ? flat : `${flat.slice(0, SEGMENT_TITLE_MAX - 1)}…`;
36
+ }
37
+
38
+ /** Whether a command line says the context was compacted: `/compact` and the automatic one, when they worked. */
39
+ function compactedLine(fact: PluginFact): boolean {
40
+ return (
41
+ fact.type === COMMAND_FACT &&
42
+ fact.data.ok === true &&
43
+ (fact.data.command === "compact" || fact.data.command === "compact (automatic)")
44
+ );
45
+ }
46
+
47
+ interface Boundary {
48
+ readonly sequence: number;
49
+ readonly at: number;
50
+ readonly kind: "new" | "compact";
51
+ readonly goal: string;
52
+ }
53
+
54
+ /**
55
+ * The segments in order. A stretch with no message in it is not one, so a
56
+ * `/new` typed twice, or a compaction nothing followed, adds none and the
57
+ * numbers stay what a client saw.
58
+ */
59
+ export function segmentsOf(facts: readonly PluginFact[], chatTitle: string): readonly Segment[] {
60
+ const boundaries: Boundary[] = [];
61
+ const titles = new Map<number, string>();
62
+ const withMessage = new Set<number>();
63
+ let current = 0;
64
+ const start = facts[0]?.at ?? 0;
65
+ for (const fact of facts) {
66
+ if (fact.type === NEW_FACT || compactedLine(fact)) {
67
+ const goal = fact.type === NEW_FACT && typeof fact.data.goal === "string" ? titleLine(fact.data.goal) : "";
68
+ boundaries.push({ sequence: fact.sequence, at: fact.at, kind: fact.type === NEW_FACT ? "new" : "compact", goal });
69
+ current = fact.sequence;
70
+ continue;
71
+ }
72
+ if (fact.type === MESSAGE_FACT) withMessage.add(current);
73
+ else if (
74
+ fact.type === SEGMENT_TITLE_FACT &&
75
+ typeof fact.data.segment === "number" &&
76
+ typeof fact.data.text === "string"
77
+ ) {
78
+ const text = titleLine(fact.data.text);
79
+ if (text.length > 0) titles.set(fact.data.segment, text);
80
+ }
81
+ }
82
+ const found: Segment[] = [];
83
+ if (withMessage.has(0) || boundaries.length === 0) {
84
+ found.push({ number: 1, sequence: 0, at: start, kind: "first", title: chatTitle });
85
+ }
86
+ for (const boundary of boundaries) {
87
+ if (!withMessage.has(boundary.sequence)) continue;
88
+ found.push({
89
+ number: found.length + 1,
90
+ sequence: boundary.sequence,
91
+ at: boundary.at,
92
+ kind: boundary.kind,
93
+ title: boundary.goal.length > 0 ? boundary.goal : (titles.get(boundary.sequence) ?? ""),
94
+ });
95
+ }
96
+ return found;
97
+ }
98
+
99
+ /** The first exchange of a segment that has no title yet. */
100
+ export interface TitleDue {
101
+ readonly segment: number;
102
+ readonly question: string;
103
+ readonly answer: string;
104
+ }
105
+
106
+ /**
107
+ * The segment that has had its first exchange and has no title: not the first
108
+ * (it carries the chat's own title), not one `/new` gave a goal, and not one
109
+ * already titled. Undefined when none is due.
110
+ */
111
+ export function titleDue(facts: readonly PluginFact[], messages: readonly Message[], chatTitle: string): TitleDue | undefined {
112
+ const segments = segmentsOf(facts, chatTitle);
113
+ for (const segment of segments) {
114
+ if (segment.kind === "first" || segment.title.length > 0) continue;
115
+ const after = messages.filter((message) => message.sequence > segment.sequence);
116
+ const next = segments[segment.number]?.sequence;
117
+ const inside = next === undefined ? after : after.filter((message) => message.sequence < next);
118
+ const question = inside.find((message) => message.role === "user");
119
+ const answer = question === undefined ? undefined : inside.find((message) => message.role === "assistant" && message.sequence > question.sequence);
120
+ if (question !== undefined && answer !== undefined) {
121
+ return { segment: segment.sequence, question: question.text, answer: answer.text };
122
+ }
123
+ }
124
+ return undefined;
125
+ }
package/src/views.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  /** How a chat shows in a list and on its page: a row and a transcript. */
2
2
 
3
- import { attachmentDir, attachmentUrl, decodeCursor, DEFAULT_SECTION_CAP_BYTES, encodeCursor, formatElapsed, isRecord, parseObjectId } from "@operad-io/engine";
3
+ import { attachmentDir, attachmentUrl, CursorError, decodeCursor, DEFAULT_SECTION_CAP_BYTES, encodeCursor, formatElapsed, isRecord, parseObjectId } from "@operad-io/engine";
4
4
  import type {
5
5
  JsonValue,
6
6
  ObjectRef,
@@ -20,7 +20,8 @@ import { maskSecrets, type FoldEntry } from "@operad-io/harness-process";
20
20
  import { secretValues } from "./reply.ts";
21
21
  import { readChatSkills, skillSummaries, type ObjectReader } from "./skills.ts";
22
22
  import { foldLogTail, agentLogPath } from "./tail.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";
23
+ import { segmentsOf, type Segment } from "./segments.ts";
24
+ import { PRIVATE_STATUS, agentLine, answeredOfFact, attachmentsOf, CHAT_TYPE, deliveryHeader, deliveryOf, chatData, chatRef, COMMAND_FACT, commandOfFact, ENTRY_FACT, entryOfFact, factsOf, IMAGE_TYPES, lastReplyContext, latestRunOf, MESSAGE_CHANGE_FACT, MESSAGE_FACT, memoryShownOf, memoryUsedLine, memoryWroteLine, 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 MemoryShown, type MessageChange, type ToolResult } from "./model.ts";
24
25
  import type { TailRead } from "./tail.ts";
25
26
 
26
27
  /** How many messages of a chat one page of the transcript holds. */
@@ -37,9 +38,11 @@ function row(object: StoredObject): ObjectRow {
37
38
  const note = [
38
39
  ...(chat.harness.length > 0 ? [agentLine(chat)] : []),
39
40
  ...(chat.accessLevel !== chat.accessDefault ? [chat.accessLevel ?? ""] : []),
41
+ ...(chat.private === true ? [PRIVATE_STATUS] : []),
40
42
  ].filter((part) => part.length > 0);
41
43
  const queued = queuedOf(object.data.queued);
42
44
  const data: Record<string, JsonValue> = {
45
+ ...(chat.channels.length === 0 ? {} : { channels: [...chat.channels] }),
43
46
  ...(chat.scheduled === undefined ? {} : { scheduled: chat.scheduled }),
44
47
  ...(queued.length === 0
45
48
  ? {}
@@ -48,9 +51,10 @@ function row(object: StoredObject): ObjectRow {
48
51
  return {
49
52
  id: object.id,
50
53
  title: chat.title.length > 0 ? chat.title : object.id,
51
- state: chat.closed ? "closed" : "open",
54
+ // A run of a routine is in neither list: its state is in no filter.
55
+ state: chat.run === true ? "run" : chat.closed ? "closed" : "open",
52
56
  ...(note.length === 0 ? {} : { note: note.join(" · ") }),
53
- ...(chat.closed ? { final: true } : {}),
57
+ ...(chat.closed || chat.run === true ? { final: true } : {}),
54
58
  ...(typeof chat.parent === "string" && chat.parent.length > 0 ? { parent: chat.parent } : {}),
55
59
  ...(Object.keys(data).length === 0 ? {} : { data }),
56
60
  };
@@ -62,7 +66,7 @@ function sections(): readonly ViewSection[] {
62
66
 
63
67
  /** The context the chat's detail page and transcript show: its last finished reply's. */
64
68
  function chatContext(object: StoredObject, read: ChatRead): ChatContext | undefined {
65
- return lastReplyContext(chatData(object.data), read.messages);
69
+ return lastReplyContext(chatData(object.data), read.messages, read.facts);
66
70
  }
67
71
 
68
72
  function minute(at: number): string {
@@ -97,12 +101,19 @@ function attachmentMarkdown(file: Attachment, home: string | undefined): string
97
101
 
98
102
  /** One message as Markdown: who, when and where from, then the text. */
99
103
  export function messageMarkdown(message: Message, speaker: string = DEFAULT_SPEAKER, home?: string): string {
104
+ if (message.delivery !== undefined) {
105
+ return [`**${deliveryHeader(message.delivery)}** · ${minute(message.at)}`, message.text].filter((part) => part.length > 0).join("\n\n");
106
+ }
107
+ if (message.role === "recap") return [`**Recap** · ${minute(message.at)}`, message.text].join("\n\n");
100
108
  const who = message.role === "assistant" ? speaker : "you";
101
109
  const via = message.role === "user" && message.source.kind.length > 0 ? ` via ${message.source.kind}` : "";
102
110
  const head = `**${who}**${via} · ${minute(message.at)}`;
103
111
  const used = message.role === "assistant" ? modelAndCost(message.model, message.costMicros, message.costQuality) : [];
104
112
  const under = used.length > 0 ? `*${used.join(" · ")}*` : "";
105
- const body = [message.text, ...message.attachments.map((file) => attachmentMarkdown(file, home)), under].filter((part) => part.length > 0);
113
+ const memoryLines = message.role === "assistant"
114
+ ? [memoryWroteLine(message.memory), memoryUsedLine(message.memory)].flatMap((line) => (line === undefined ? [] : [`*${line}*`]))
115
+ : [];
116
+ const body = [message.text, ...message.attachments.map((file) => attachmentMarkdown(file, home)), under, ...memoryLines].filter((part) => part.length > 0);
106
117
  return [head, ...body].join("\n\n");
107
118
  }
108
119
 
@@ -138,10 +149,13 @@ function messageFrom(fact: {
138
149
  }): Message | undefined {
139
150
  const data = fact.data;
140
151
  if (typeof data.id !== "string" || typeof data.text !== "string") return undefined;
141
- if (data.role !== "user" && data.role !== "assistant") return undefined;
152
+ if (data.role !== "user" && data.role !== "assistant" && data.role !== "delivery" && data.role !== "recap") return undefined;
153
+ const delivery = data.role === "delivery" ? deliveryOf(data.delivery) : undefined;
154
+ if (data.role === "delivery" && delivery === undefined) return undefined;
142
155
  const from = isRecord(data.from) ? data.from : {};
143
156
  const source = typeof data.source === "object" && data.source !== null ? (data.source as Record<string, unknown>) : {};
144
157
  const timings = timingsOf(data.timings);
158
+ const memory = memoryShownOf(data.memory);
145
159
  return {
146
160
  id: data.id,
147
161
  role: data.role,
@@ -155,9 +169,11 @@ function messageFrom(fact: {
155
169
  kind: typeof source.kind === "string" ? source.kind : "",
156
170
  ref: typeof source.ref === "string" ? source.ref : null,
157
171
  },
172
+ ...(delivery === undefined ? {} : { delivery }),
158
173
  ...(typeof data.runId === "string" && data.runId.length > 0 ? { runId: data.runId } : {}),
159
174
  ...(typeof data.model === "string" && data.model.length > 0 ? { model: data.model } : {}),
160
175
  ...(timings === undefined ? {} : { timings }),
176
+ ...(memory === undefined ? {} : { memory }),
161
177
  ...(typeof data.costMicros === "number" && Number.isFinite(data.costMicros) ? { costMicros: data.costMicros } : {}),
162
178
  ...(data.costQuality === "exact" || data.costQuality === "estimated" || data.costQuality === "incomplete"
163
179
  ? { costQuality: data.costQuality }
@@ -292,6 +308,8 @@ export interface ReplyBlock {
292
308
  readonly input: readonly ReplyMessage[];
293
309
  readonly process: readonly ReplyProcess[];
294
310
  readonly answer?: ReplyMessage | undefined;
311
+ /** The memory notes the reply wrote and used, when it did either. */
312
+ readonly memory?: MemoryShown | undefined;
295
313
  /** How long the reply took, when its harness reported the timings. */
296
314
  readonly durationMs?: number | undefined;
297
315
  }
@@ -545,6 +563,7 @@ function storedReplies(
545
563
  input: messagesInTime(input),
546
564
  process: processOf(chunk, home),
547
565
  answer: replyMessage(answer),
566
+ ...(answer.memory === undefined ? {} : { memory: answer.memory }),
548
567
  ...(answer.timings === undefined ? {} : { durationMs: answer.timings.totalMs }),
549
568
  },
550
569
  chunk,
@@ -592,6 +611,32 @@ function liveReply(
592
611
  };
593
612
  }
594
613
 
614
+ /** The deliveries recorded in the chunks shown, as the transcript's data names them. */
615
+ function deliveriesData(chunks: readonly Chunk[]): JsonValue[] {
616
+ const found: JsonValue[] = [];
617
+ for (const chunk of chunks) {
618
+ for (const fact of chunk.facts) {
619
+ const message = fact.type === MESSAGE_FACT ? messageFrom(fact) : undefined;
620
+ const delivery = message?.delivery;
621
+ if (message === undefined || delivery === undefined) continue;
622
+ found.push({
623
+ id: message.id,
624
+ at: message.at,
625
+ routine: delivery.routine,
626
+ ...(delivery.routineId === undefined ? {} : { routineId: delivery.routineId }),
627
+ runId: delivery.runId,
628
+ ...(delivery.failed === true ? { failed: true } : {}),
629
+ });
630
+ }
631
+ }
632
+ return found;
633
+ }
634
+
635
+ function withDeliveries(base: Readonly<Record<string, JsonValue>>, chunks: readonly Chunk[]): Readonly<Record<string, JsonValue>> {
636
+ const deliveries = deliveriesData(chunks);
637
+ return deliveries.length === 0 ? base : { ...base, deliveries };
638
+ }
639
+
595
640
  function jsonBytes(value: unknown): number {
596
641
  return Buffer.byteLength(JSON.stringify(value), "utf8");
597
642
  }
@@ -635,20 +680,31 @@ export function replyData(
635
680
  let sum = sizes.reduce((total, size) => total + size, 0);
636
681
  const sizeOf = (count: number, inner: number): number => overhead + inner + Math.max(0, count - 1);
637
682
  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.
683
+ // Shortening goes in three passes, each the oldest reply first and whole
684
+ // reply by whole reply, so the newest stays whole the longest. Pass 1
685
+ // shortens everything that is not an answer (thinking, text, tool input and
686
+ // the input messages, which keep a preview). Pass 2 shortens answers to a
687
+ // preview of about two lines. Pass 3 goes below the preview, and only then
688
+ // are replies dropped.
641
689
  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);
690
+ const step = (at: number, caps: ReplyCaps): boolean => {
691
+ const original = cuts[at];
692
+ if (original === undefined) return false;
693
+ const cut = cutReply(original, caps);
694
+ const size = measure(cut);
695
+ sum += size - (sizes[at] ?? 0);
696
+ sizes[at] = size;
697
+ cuts[at] = cut;
698
+ return sizeOf(cuts.length, sum) <= maxBytes;
699
+ };
700
+ const passes: readonly (readonly ReplyCaps[])[] = [
701
+ FREE_CAPS.map((free) => ({ free, input: Math.max(free, PREVIEW_BYTES), answer: Infinity })),
702
+ [{ free: 0, input: PREVIEW_BYTES, answer: PREVIEW_BYTES }],
703
+ [64, 0].map((all) => ({ free: all, input: all, answer: all })),
704
+ ];
705
+ for (const pass of passes) {
706
+ for (let at = 0; at < cuts.length; at += 1) {
707
+ for (const caps of pass) if (step(at, caps)) return data(cuts);
652
708
  }
653
709
  }
654
710
  // Even empty text leaves too much structure: the oldest replies go.
@@ -662,35 +718,64 @@ export function replyData(
662
718
  return (measure({ replies: [] }) <= maxBytes ? { replies: [] } : {}) as Readonly<Record<string, JsonValue>>;
663
719
  }
664
720
 
665
- /** Text cut to fit a byte budget, ending with an ellipsis when it was longer. */
721
+ /** The preview an older reply's answer and input keep while anything else can still be cut: about two lines. */
722
+ const PREVIEW_BYTES = 200;
723
+ const FREE_CAPS: readonly number[] = [128, 0];
724
+
725
+ /** Byte caps for the three kinds of text in a reply; `Infinity` leaves a kind whole. */
726
+ interface ReplyCaps {
727
+ readonly free: number;
728
+ readonly input: number;
729
+ readonly answer: number;
730
+ }
731
+
732
+ /**
733
+ * Text cut to fit a byte budget, ending with an ellipsis when it was longer.
734
+ * The cut is at a line or sentence end when one is in the last quarter of what
735
+ * fits, and never inside a code point.
736
+ */
666
737
  function shorten(text: string, capBytes: number): string {
667
738
  if (capBytes <= 0) return "";
668
739
  if (Buffer.byteLength(text, "utf8") <= capBytes) return text;
669
740
  if (capBytes <= 3) return "";
670
741
  let end = Math.min(text.length, capBytes);
671
742
  while (end > 0 && Buffer.byteLength(text.slice(0, end), "utf8") + 3 > capBytes) end -= 1;
672
- return end === 0 ? "" : `${text.slice(0, end)}…`;
743
+ const last = text.charCodeAt(end - 1);
744
+ if (end > 0 && last >= 0xd800 && last <= 0xdbff) end -= 1;
745
+ if (end === 0) return "";
746
+ const head = text.slice(0, end);
747
+ const floor = Math.floor(end * 0.75);
748
+ const newline = head.lastIndexOf("\n");
749
+ if (newline > 0 && newline >= floor) {
750
+ const line = head.slice(0, newline).trimEnd();
751
+ if (line !== "") return `${line}…`;
752
+ }
753
+ const sentence = /[.!?。!?](?=\s|$)/g;
754
+ let stop = -1;
755
+ for (let found = sentence.exec(head); found !== null; found = sentence.exec(head)) stop = found.index + 1;
756
+ if (stop > 0 && stop >= floor) return `${head.slice(0, stop)}…`;
757
+ return `${head}…`;
673
758
  }
674
759
 
675
760
  /** 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 } => {
761
+ function cutReply(reply: ReplyBlock, caps: ReplyCaps): ReplyBlock {
762
+ const text = (original: string, capBytes: number): { readonly text: string; readonly cut?: true } => {
678
763
  const shortened = shorten(original, capBytes);
679
764
  return shortened === original ? { text: shortened } : { text: shortened, cut: true };
680
765
  };
681
- const message = (block: ReplyMessage): ReplyMessage => ({ ...block, ...text(block.text) });
766
+ const message = (block: ReplyMessage, capBytes: number): ReplyMessage => ({ ...block, ...text(block.text, capBytes) });
682
767
  const item = (entry: ReplyItem): ReplyItem => {
683
768
  if (entry.kind === "tool") {
684
769
  if (entry.input === null) return entry;
685
- const shortened = shorten(entry.input, capBytes);
770
+ const shortened = shorten(entry.input, caps.free);
686
771
  return shortened === entry.input ? entry : { ...entry, input: shortened, cut: true };
687
772
  }
688
- return { ...entry, ...text(entry.text) };
773
+ return { ...entry, ...text(entry.text, caps.free) };
689
774
  };
690
775
  return {
691
776
  ...reply,
692
- input: reply.input.map(message),
693
- ...(reply.answer === undefined ? {} : { answer: message(reply.answer) }),
777
+ input: reply.input.map((block) => message(block, caps.input)),
778
+ ...(reply.answer === undefined ? {} : { answer: message(reply.answer, caps.answer) }),
694
779
  process: reply.process.map((group) => ({
695
780
  ...group,
696
781
  items: group.items.map(item),
@@ -1367,6 +1452,103 @@ async function liveOf(
1367
1452
  };
1368
1453
  }
1369
1454
 
1455
+ /** The line that marks where a segment starts: its title and its date (UTC); the date alone while it has no title. */
1456
+ export function segmentMarker(segment: Segment): string {
1457
+ const date = new Date(segment.at).toISOString().slice(0, 10);
1458
+ return `### ${segment.title.length > 0 ? `${segment.title} · ` : ""}${date}`;
1459
+ }
1460
+
1461
+ function firstSequence(chunk: Chunk): number {
1462
+ return chunk.facts.reduce((least, fact) => Math.min(least, fact.sequence), Number.MAX_SAFE_INTEGER);
1463
+ }
1464
+
1465
+ /** The first chunk after each segment's beginning: where its marker goes. The first segment has none. */
1466
+ function segmentStarts(chunks: readonly Chunk[], segments: readonly Segment[]): ReadonlyMap<Chunk, Segment> {
1467
+ const starts = new Map<Chunk, Segment>();
1468
+ for (const segment of segments) {
1469
+ if (segment.kind === "first") continue;
1470
+ const chunk = chunks.find((candidate) => firstSequence(candidate) > segment.sequence);
1471
+ if (chunk !== undefined && !starts.has(chunk)) starts.set(chunk, segment);
1472
+ }
1473
+ return starts;
1474
+ }
1475
+
1476
+ /** What a chunk renders as, led by the marker of the segment that starts with it. */
1477
+ function chunkBlocks(
1478
+ chunk: Chunk,
1479
+ starts: ReadonlyMap<Chunk, Segment>,
1480
+ speaker: string,
1481
+ home: string | undefined,
1482
+ harness: string,
1483
+ ): readonly string[] {
1484
+ const start = starts.get(chunk);
1485
+ return [...(start === undefined ? [] : [segmentMarker(start)]), ...rendered(chunk, speaker, home, harness)];
1486
+ }
1487
+
1488
+ /** One page of chunks from `start`, by the size rule `pagesOf` follows. */
1489
+ function pageFrom(ref: ObjectRef, chunks: readonly Chunk[], start: number): Page & { readonly end: number } {
1490
+ const pageChunks: Chunk[] = [];
1491
+ let messages = 0;
1492
+ let index = start;
1493
+ while (index < chunks.length) {
1494
+ const chunk = chunks[index];
1495
+ if (chunk === undefined) break;
1496
+ if (pageChunks.length > 0 && messages + chunk.messages > TRANSCRIPT_PAGE) break;
1497
+ pageChunks.push(chunk);
1498
+ messages += chunk.messages;
1499
+ index += 1;
1500
+ if (messages >= TRANSCRIPT_PAGE) break;
1501
+ }
1502
+ const before = chunks[start - 1]?.last;
1503
+ return {
1504
+ chunks: pageChunks,
1505
+ after: before,
1506
+ cursor: before === undefined ? undefined : factsCursor(ref, before),
1507
+ end: index,
1508
+ };
1509
+ }
1510
+
1511
+ const DAY = /^\d{4}-\d{2}-\d{2}$/u;
1512
+
1513
+ /**
1514
+ * Where a person's own words ask the transcript to start: `segment:<n>`,
1515
+ * `date:<YYYY-MM-DD>` (UTC, the first thing on or after that day) or
1516
+ * `message:<id>`. The index of the first chunk shown, or undefined for a cursor
1517
+ * that is none of these.
1518
+ */
1519
+ function startOf(
1520
+ cursor: string,
1521
+ chunks: readonly Chunk[],
1522
+ segments: readonly Segment[],
1523
+ starts: ReadonlyMap<Chunk, Segment>,
1524
+ ): number | undefined {
1525
+ const colon = cursor.indexOf(":");
1526
+ if (colon < 0) return undefined;
1527
+ const kind = cursor.slice(0, colon);
1528
+ const value = cursor.slice(colon + 1);
1529
+ if (kind === "segment") {
1530
+ const segment = segments.find((candidate) => String(candidate.number) === value);
1531
+ if (segment === undefined) throw new CursorError(`chat transcript: there is no segment ${value}`);
1532
+ if (segment.kind === "first") return 0;
1533
+ const at = chunks.findIndex((chunk) => starts.get(chunk) === segment);
1534
+ if (at < 0) throw new CursorError(`chat transcript: segment ${value} has nothing to show`);
1535
+ return at;
1536
+ }
1537
+ if (kind === "date") {
1538
+ const day = DAY.test(value) ? Date.parse(`${value}T00:00:00Z`) : Number.NaN;
1539
+ if (Number.isNaN(day)) throw new CursorError("chat transcript: a date is written YYYY-MM-DD");
1540
+ const at = chunks.findIndex((chunk) => chunk.facts.some((fact) => fact.at >= day));
1541
+ if (at < 0) throw new CursorError(`chat transcript: nothing on or after ${value}`);
1542
+ return at;
1543
+ }
1544
+ if (kind === "message") {
1545
+ const at = chunks.findIndex((chunk) => chunk.facts.some((fact) => fact.type === MESSAGE_FACT && fact.data.id === value));
1546
+ if (at < 0) throw new CursorError(`chat transcript: there is no message ${value}`);
1547
+ return at;
1548
+ }
1549
+ return undefined;
1550
+ }
1551
+
1370
1552
  async function load(
1371
1553
  ctx: ViewContext,
1372
1554
  object: StoredObject,
@@ -1381,9 +1563,22 @@ async function load(
1381
1563
  const facts = messageFactsInForce(read.facts);
1382
1564
  const messages = read.messages;
1383
1565
  const queued = queuedData(queuedMessages(messages, facts));
1566
+ const segments = segmentsOf(read.facts, chat.title.length > 0 ? chat.title : object.id);
1384
1567
  const queueData: Record<string, JsonValue> = {
1385
1568
  queued: queued as unknown as JsonValue,
1386
1569
  queuedCount: queued.length,
1570
+ // A chat with one segment has nothing to jump between.
1571
+ ...(segments.length < 2
1572
+ ? {}
1573
+ : {
1574
+ segments: segments.map((segment) => ({
1575
+ number: segment.number,
1576
+ at: segment.at,
1577
+ kind: segment.kind,
1578
+ title: segment.title,
1579
+ cursor: `segment:${segment.number}`,
1580
+ })) as unknown as JsonValue,
1581
+ }),
1387
1582
  };
1388
1583
  const live = await liveOf(ctx, object, facts, messages, speaker);
1389
1584
  const { cut, run: liveRun, items: liveItems, ...liveContent } = live;
@@ -1401,7 +1596,8 @@ async function load(
1401
1596
  if (since !== undefined) {
1402
1597
  // Only what was recorded after the mark, in the same Markdown as a full read.
1403
1598
  const chunks = chunksOf(finished.filter((fact) => fact.sequence > since));
1404
- const blocks = chunks.flatMap((chunk) => rendered(chunk, speaker, ctx.home, chat.harness));
1599
+ const sinceStarts = segmentStarts(chunks, segments.filter((segment) => segment.sequence > since));
1600
+ const blocks = chunks.flatMap((chunk) => chunkBlocks(chunk, sinceStarts, speaker, ctx.home, chat.harness));
1405
1601
  const markdown = blocks.join("\n\n---\n\n");
1406
1602
  // The replies whose answer is after the mark, and the one still running.
1407
1603
  const sinceChunks = finishedChunks.filter((chunk) => {
@@ -1421,7 +1617,7 @@ async function load(
1421
1617
  const data = replyData(
1422
1618
  replies.map((reply) => reply.block),
1423
1619
  Math.max(0, limit - Buffer.byteLength(markdown, "utf8") - Buffer.byteLength(liveContent.tail ?? "", "utf8")),
1424
- queueData,
1620
+ withDeliveries(queueData, chunks),
1425
1621
  );
1426
1622
  return {
1427
1623
  markdown,
@@ -1433,9 +1629,17 @@ async function load(
1433
1629
  };
1434
1630
  }
1435
1631
  const pages = pagesOf(ref, finishedChunks);
1436
- const after = options.cursor === undefined ? undefined : cursorAfter(options.cursor);
1437
- const index = pages.findIndex((page) => page.after === after);
1438
- const selected = pages[index < 0 ? 0 : index] ?? pages[0];
1632
+ const starts = segmentStarts(finishedChunks, segments);
1633
+ const asked = options.cursor === undefined ? undefined : startOf(options.cursor, finishedChunks, segments, starts);
1634
+ const after = options.cursor === undefined || asked !== undefined ? undefined : cursorAfter(options.cursor);
1635
+ const aligned = pages.findIndex((page) => page.after === after);
1636
+ // A page of the table of contents; or one that starts where a segment, a day or
1637
+ // a message is, or right after such a page.
1638
+ const through = after === undefined ? -1 : finishedChunks.findIndex((chunk) => chunk.last === after);
1639
+ const from = asked ?? (aligned < 0 && through >= 0 ? through + 1 : undefined);
1640
+ const free = from === undefined ? undefined : pageFrom(ref, finishedChunks, from);
1641
+ const index = free === undefined ? aligned : -1;
1642
+ const selected = free ?? pages[index < 0 ? 0 : index] ?? pages[0];
1439
1643
  const pageIndex = index < 0 ? 0 : index;
1440
1644
  const pageChunks = selected?.chunks ?? [];
1441
1645
  const firstOnPage = pageChunks[0]?.facts[0]?.sequence ?? Number.MAX_SAFE_INTEGER;
@@ -1445,20 +1649,30 @@ async function load(
1445
1649
  ctx.home,
1446
1650
  answerBefore(finishedChunks, firstOnPage),
1447
1651
  );
1448
- const pageReplies = pageIndex === pages.length - 1 && liveBlock !== undefined
1652
+ const lastPage = free === undefined ? pageIndex === pages.length - 1 : free.end >= finishedChunks.length;
1653
+ const pageReplies = lastPage && liveBlock !== undefined
1449
1654
  ? [...onPageBlocks, liveBlock]
1450
1655
  : onPageBlocks;
1451
- const blocks = (selected?.chunks ?? []).flatMap((chunk) => rendered(chunk, speaker, ctx.home, chat.harness));
1656
+ const blocks = (selected?.chunks ?? []).flatMap((chunk) => chunkBlocks(chunk, starts, speaker, ctx.home, chat.harness));
1452
1657
  const body = blocks.length === 0 && options.cursor === undefined ? "No messages yet." : blocks.join("\n\n---\n\n");
1453
1658
  // Every page says which agent answers, as the row does.
1454
- const markdown = chat.harness.length > 0
1659
+ const agentMarkdown = chat.harness.length > 0
1455
1660
  ? `Agent: ${agentLine(chat)}\n\n${body}`
1456
1661
  : body;
1457
- const nextPage = index < 0 ? undefined : pages[index + 1];
1662
+ // A stretch that is not remembered stands as a status at the top of every page.
1663
+ const markdown = chat.private === true ? `**${PRIVATE_STATUS}**\n\n${agentMarkdown}` : agentMarkdown;
1664
+ const nextCursor =
1665
+ free === undefined
1666
+ ? index < 0
1667
+ ? undefined
1668
+ : pages[index + 1]?.cursor
1669
+ : free.end < finishedChunks.length
1670
+ ? factsCursor(ref, free.chunks.at(-1)?.last ?? 0)
1671
+ : undefined;
1458
1672
  const data = replyData(
1459
1673
  pageReplies.map((reply) => reply.block),
1460
1674
  Math.max(0, limit - Buffer.byteLength(markdown, "utf8") - Buffer.byteLength(liveContent.tail ?? "", "utf8")),
1461
- queueData,
1675
+ withDeliveries(queueData, pageChunks),
1462
1676
  );
1463
1677
 
1464
1678
  // The table of contents: the cursor each page starts at, the first one without.
@@ -1470,7 +1684,7 @@ async function load(
1470
1684
  return {
1471
1685
  markdown,
1472
1686
  mark: markOf(selected?.chunks.at(-1)?.last ?? 0),
1473
- ...(nextPage?.cursor === undefined ? {} : { next: nextPage.cursor }),
1687
+ ...(nextCursor === undefined ? {} : { next: nextCursor }),
1474
1688
  ...(toc.length > 1 ? { pages: toc } : {}),
1475
1689
  ...liveContent,
1476
1690
  ...(context === undefined ? {} : { context }),