@operad-io/chat 0.0.0-stage → 0.0.1
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/LICENSE +21 -0
- package/README.md +95 -2
- package/package.json +22 -4
- package/src/index.ts +372 -0
- package/src/model.ts +717 -0
- package/src/reply.ts +687 -0
- package/src/tail.ts +107 -0
- package/src/views.ts +444 -0
package/src/tail.ts
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The part of an answer that is not finished: read from the log of the step
|
|
3
|
+
* that runs the agent. The run is not in the serve process; the log file is the
|
|
4
|
+
* way to it. The log is append-only, so it is folded once and then only what
|
|
5
|
+
* was appended is read: the state is always exact (for claude, pi and radian
|
|
6
|
+
* alike) and a read costs what was added since the last one.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { closeSync, fstatSync, openSync, readSync } from "node:fs";
|
|
10
|
+
import { join } from "node:path";
|
|
11
|
+
import { emptyFold, foldLines, type FoldState } from "@operad-io/harness-process";
|
|
12
|
+
|
|
13
|
+
/** How many bytes one read call takes from the file. */
|
|
14
|
+
export const TAIL_READ_CHUNK = 1024 * 1024;
|
|
15
|
+
|
|
16
|
+
/** How many logs keep their folded state; the least recently read is dropped first. */
|
|
17
|
+
export const TAIL_CACHE_LOGS = 32;
|
|
18
|
+
|
|
19
|
+
/** Keeps a name usable as one path segment, as the step's logger does. */
|
|
20
|
+
function segment(value: string): string {
|
|
21
|
+
const cleaned = value.replace(/[^A-Za-z0-9._-]/g, "_");
|
|
22
|
+
return cleaned.length === 0 || cleaned === "." || cleaned === ".." ? "_" : cleaned;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Where a harness's agent step writes the log of one run. */
|
|
26
|
+
export function agentLogPath(storeRoot: string, harness: string, runId: string): string {
|
|
27
|
+
return join(storeRoot, "logs", segment(harness), "runs", segment(runId), "agent.log");
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** What was read of a log: the fold of all of it, and how many bytes this read took. */
|
|
31
|
+
export interface TailRead {
|
|
32
|
+
readonly state: FoldState;
|
|
33
|
+
readonly bytesRead: number;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
interface Saved {
|
|
37
|
+
readonly dev: number;
|
|
38
|
+
readonly ino: number;
|
|
39
|
+
/** How many bytes of the log were read: the folded lines and the partial line after them. */
|
|
40
|
+
readonly offset: number;
|
|
41
|
+
/** The partial last line read so far, kept so it is not read again. */
|
|
42
|
+
readonly pending: Buffer;
|
|
43
|
+
readonly state: FoldState;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* The folded state per log path. A Map keeps insertion order; a read moves its
|
|
48
|
+
* entry to the end, so the first entry is the least recently read and goes when
|
|
49
|
+
* there are more than `TAIL_CACHE_LOGS`. A log nobody asks about any more (its
|
|
50
|
+
* run ended) is therefore dropped as others are read.
|
|
51
|
+
*/
|
|
52
|
+
const saved = new Map<string, Saved>();
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* The fold of a whole log file, reading only what was appended since the last
|
|
56
|
+
* call for the path; undefined when there is no file. A file that is shorter
|
|
57
|
+
* than what was read, or is another file, is read again from its start. A line
|
|
58
|
+
* still being written is kept as it is and completed by the next call. Finished entries are not kept:
|
|
59
|
+
* only the unfinished text, thinking and calls matter here.
|
|
60
|
+
*/
|
|
61
|
+
export function foldLogTail(path: string): TailRead | undefined {
|
|
62
|
+
let fd: number;
|
|
63
|
+
try {
|
|
64
|
+
fd = openSync(path, "r");
|
|
65
|
+
} catch {
|
|
66
|
+
return undefined;
|
|
67
|
+
}
|
|
68
|
+
try {
|
|
69
|
+
const stat = fstatSync(fd);
|
|
70
|
+
const before = saved.get(path);
|
|
71
|
+
const keep = before !== undefined && before.dev === stat.dev && before.ino === stat.ino && before.offset <= stat.size;
|
|
72
|
+
let state = keep ? before.state : emptyFold;
|
|
73
|
+
let pending = keep ? before.pending : Buffer.alloc(0);
|
|
74
|
+
let bytesRead = 0;
|
|
75
|
+
let position = keep ? before.offset : 0;
|
|
76
|
+
while (position < stat.size) {
|
|
77
|
+
const chunk = Buffer.allocUnsafe(Math.min(TAIL_READ_CHUNK, stat.size - position));
|
|
78
|
+
const count = readSync(fd, chunk, 0, chunk.length, position);
|
|
79
|
+
if (count === 0) break;
|
|
80
|
+
position += count;
|
|
81
|
+
bytesRead += count;
|
|
82
|
+
pending = Buffer.concat([pending, chunk.subarray(0, count)]);
|
|
83
|
+
const end = pending.lastIndexOf(0x0a);
|
|
84
|
+
if (end < 0) continue;
|
|
85
|
+
const values: unknown[] = [];
|
|
86
|
+
for (const line of pending.subarray(0, end).toString("utf8").split("\n")) {
|
|
87
|
+
if (line.length === 0) continue;
|
|
88
|
+
try {
|
|
89
|
+
values.push(JSON.parse(line));
|
|
90
|
+
} catch {
|
|
91
|
+
// Not one of ours.
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
state = { ...foldLines(values, state), entries: [] };
|
|
95
|
+
pending = pending.subarray(end + 1);
|
|
96
|
+
}
|
|
97
|
+
saved.delete(path);
|
|
98
|
+
saved.set(path, { dev: stat.dev, ino: stat.ino, offset: position, pending, state });
|
|
99
|
+
for (const old of saved.keys()) {
|
|
100
|
+
if (saved.size <= TAIL_CACHE_LOGS) break;
|
|
101
|
+
saved.delete(old);
|
|
102
|
+
}
|
|
103
|
+
return { state, bytesRead };
|
|
104
|
+
} finally {
|
|
105
|
+
closeSync(fd);
|
|
106
|
+
}
|
|
107
|
+
}
|
package/src/views.ts
ADDED
|
@@ -0,0 +1,444 @@
|
|
|
1
|
+
/** How a chat shows in a list and on its page: a row and a transcript. */
|
|
2
|
+
|
|
3
|
+
import { attachmentUrl, decodeCursor, encodeCursor } from "@operad-io/engine";
|
|
4
|
+
import type {
|
|
5
|
+
ObjectRef,
|
|
6
|
+
ObjectRow,
|
|
7
|
+
ObjectViews,
|
|
8
|
+
PluginFact,
|
|
9
|
+
SectionContent,
|
|
10
|
+
SectionPage,
|
|
11
|
+
StoredObject,
|
|
12
|
+
ViewContext,
|
|
13
|
+
ViewSection,
|
|
14
|
+
} from "@operad-io/engine";
|
|
15
|
+
import { maskSecrets } from "@operad-io/harness-process";
|
|
16
|
+
import { secretValues } from "./reply.ts";
|
|
17
|
+
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";
|
|
19
|
+
|
|
20
|
+
/** How many messages of a chat one page of the transcript holds. */
|
|
21
|
+
export const TRANSCRIPT_PAGE = 50;
|
|
22
|
+
|
|
23
|
+
/** How a transcript labels the model's messages when nothing sets a speaker. */
|
|
24
|
+
export const DEFAULT_SPEAKER = "Operad Bot";
|
|
25
|
+
|
|
26
|
+
/** The one section of a chat. */
|
|
27
|
+
export const TRANSCRIPT = "transcript";
|
|
28
|
+
|
|
29
|
+
function row(object: StoredObject): ObjectRow {
|
|
30
|
+
const chat = chatData(object.data);
|
|
31
|
+
return {
|
|
32
|
+
id: object.id,
|
|
33
|
+
title: chat.title.length > 0 ? chat.title : object.id,
|
|
34
|
+
state: chat.closed ? "closed" : "open",
|
|
35
|
+
...(chat.harness.length > 0 ? { note: agentLine(chat) } : {}),
|
|
36
|
+
...(chat.closed ? { final: true } : {}),
|
|
37
|
+
...(typeof chat.parent === "string" && chat.parent.length > 0 ? { parent: chat.parent } : {}),
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function sections(): readonly ViewSection[] {
|
|
42
|
+
return [{ id: TRANSCRIPT, title: "Transcript", live: true }];
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function minute(at: number): string {
|
|
46
|
+
return new Date(at).toISOString().slice(0, 16).replace("T", " ");
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** A path as a Markdown link destination: spaces and parentheses are escaped. */
|
|
50
|
+
function destination(path: string, home: string | undefined): string {
|
|
51
|
+
// A client fetches the file from the server, so the link is the server's attachment address.
|
|
52
|
+
const url = home === undefined ? undefined : attachmentUrl(home, path);
|
|
53
|
+
return (url ?? encodeURI(path)).replace(/\(/g, "%28").replace(/\)/g, "%29");
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** One attachment as a line: an image is shown as an image, another file as a link. */
|
|
57
|
+
function attachmentMarkdown(file: Attachment, home: string | undefined): string {
|
|
58
|
+
const target = destination(file.path, home);
|
|
59
|
+
if ((IMAGE_TYPES as readonly string[]).includes(file.type)) return ``;
|
|
60
|
+
return `Attachment: [${file.name}](${target})`;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** One message as Markdown: who, when and where from, then the text. */
|
|
64
|
+
export function messageMarkdown(message: Message, speaker: string = DEFAULT_SPEAKER, home?: string): string {
|
|
65
|
+
const who = message.role === "assistant" ? speaker : "you";
|
|
66
|
+
const via = message.role === "user" && message.source.kind.length > 0 ? ` via ${message.source.kind}` : "";
|
|
67
|
+
const head = `**${who}**${via} · ${minute(message.at)}`;
|
|
68
|
+
const used = message.role === "assistant" ? modelAndCost(message.model, message.costMicros, message.costQuality) : [];
|
|
69
|
+
const under = used.length > 0 ? `*${used.join(" · ")}*` : "";
|
|
70
|
+
const body = [message.text, ...message.attachments.map((file) => attachmentMarkdown(file, home)), under].filter((part) => part.length > 0);
|
|
71
|
+
return [head, ...body].join("\n\n");
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* How the transcript labels the model's messages now. The chat's own setting
|
|
76
|
+
* applies; a parent object that names a speaker (a bot) speaks for its chats.
|
|
77
|
+
* It is read at every draw, so a changed name shows on the messages already
|
|
78
|
+
* recorded too.
|
|
79
|
+
*/
|
|
80
|
+
async function speakerOf(ctx: ViewContext, object: StoredObject): Promise<string> {
|
|
81
|
+
const parent = chatData(object.data).parent;
|
|
82
|
+
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));
|
|
88
|
+
const speaker = owner?.data.speaker;
|
|
89
|
+
if (typeof speaker === "string" && speaker.length > 0) return speaker;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
const settings = ctx.settingsInForce === undefined
|
|
93
|
+
? ctx.settings
|
|
94
|
+
: ctx.settingsInForce(ctx.plugin);
|
|
95
|
+
const speaker = settings.speaker;
|
|
96
|
+
return typeof speaker === "string" && speaker.length > 0 ? speaker : DEFAULT_SPEAKER;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function messageFrom(fact: {
|
|
100
|
+
readonly data: Readonly<Record<string, unknown>>;
|
|
101
|
+
readonly at: number;
|
|
102
|
+
readonly sequence: number;
|
|
103
|
+
}): Message | undefined {
|
|
104
|
+
const data = fact.data;
|
|
105
|
+
if (typeof data.id !== "string" || typeof data.text !== "string") return undefined;
|
|
106
|
+
if (data.role !== "user" && data.role !== "assistant") return undefined;
|
|
107
|
+
const source = typeof data.source === "object" && data.source !== null ? (data.source as Record<string, unknown>) : {};
|
|
108
|
+
return {
|
|
109
|
+
id: data.id,
|
|
110
|
+
role: data.role,
|
|
111
|
+
from: { via: "", id: "" },
|
|
112
|
+
text: data.text,
|
|
113
|
+
attachments: attachmentsOf(data.attachments),
|
|
114
|
+
source: {
|
|
115
|
+
kind: typeof source.kind === "string" ? source.kind : "",
|
|
116
|
+
ref: typeof source.ref === "string" ? source.ref : null,
|
|
117
|
+
},
|
|
118
|
+
...(typeof data.runId === "string" && data.runId.length > 0 ? { runId: data.runId } : {}),
|
|
119
|
+
...(typeof data.model === "string" && data.model.length > 0 ? { model: data.model } : {}),
|
|
120
|
+
...(typeof data.costMicros === "number" && Number.isFinite(data.costMicros) ? { costMicros: data.costMicros } : {}),
|
|
121
|
+
...(data.costQuality === "exact" || data.costQuality === "estimated" || data.costQuality === "incomplete"
|
|
122
|
+
? { costQuality: data.costQuality }
|
|
123
|
+
: {}),
|
|
124
|
+
at: fact.at,
|
|
125
|
+
sequence: fact.sequence,
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
|
|
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
|
+
function flat(text: string): string {
|
|
137
|
+
return text.replace(/\s+/g, " ").trim();
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function inlineCode(text: string): string {
|
|
141
|
+
const longest = Math.max(0, ...(text.match(/`+/g) ?? []).map((run) => run.length));
|
|
142
|
+
const fence = "`".repeat(longest + 1);
|
|
143
|
+
return longest > 0 ? `${fence} ${text} ${fence}` : `${fence}${text}${fence}`;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function firstLine(text: string | null | undefined): string | undefined {
|
|
147
|
+
const line = text?.split("\n")[0]?.trim();
|
|
148
|
+
return line === undefined || line.length === 0 ? undefined : line;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** One tool call as a log line: what ran, how long it took and how it ended. */
|
|
152
|
+
function toolMarkdown(entry: Entry): string {
|
|
153
|
+
const name = entry.toolName ?? "tool";
|
|
154
|
+
const took = entry.durationMs === undefined ? "" : ` ${seconds(entry.durationMs)}`;
|
|
155
|
+
const input = entry.input === undefined || entry.input === null ? "" : flat(entry.input);
|
|
156
|
+
const what = input.length === 0 ? "" : ` ${inlineCode(input.length <= 160 ? input : `${input.slice(0, 159)}…`)}`;
|
|
157
|
+
const head = `tool ${name}${took}${what}`;
|
|
158
|
+
if (entry.result === "failed") {
|
|
159
|
+
const error = firstLine(entry.error);
|
|
160
|
+
return error === undefined ? `${head} failed` : `${head} failed: ${error}`;
|
|
161
|
+
}
|
|
162
|
+
if (entry.result === "blocked") {
|
|
163
|
+
const reason = firstLine(entry.error);
|
|
164
|
+
return reason === undefined ? `${head} blocked` : `${head} blocked: ${reason}`;
|
|
165
|
+
}
|
|
166
|
+
if (entry.result === "denied") return `${head} denied`;
|
|
167
|
+
return head;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** 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 {
|
|
172
|
+
// Radian gives no text or thinking increments; its chats show the tool lines only.
|
|
173
|
+
if (entry.kind !== "tool" && harness === "radian") return undefined;
|
|
174
|
+
if (entry.kind === "tool") return toolMarkdown(entry);
|
|
175
|
+
if (entry.text === undefined) return undefined;
|
|
176
|
+
if (entry.kind === "thinking") {
|
|
177
|
+
return entry.text
|
|
178
|
+
.split(/\r?\n/)
|
|
179
|
+
.map((line) => `> ${line}`)
|
|
180
|
+
.join("\n");
|
|
181
|
+
}
|
|
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;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
interface Chunk {
|
|
201
|
+
readonly facts: readonly PluginFact[];
|
|
202
|
+
/** How many messages, not entries, the chunk holds. */
|
|
203
|
+
readonly messages: number;
|
|
204
|
+
readonly last: number;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function chunkOf(facts: readonly PluginFact[]): Chunk {
|
|
208
|
+
return {
|
|
209
|
+
facts,
|
|
210
|
+
messages: facts.filter((fact) => fact.type === MESSAGE_FACT).length,
|
|
211
|
+
last: facts.at(-1)?.sequence ?? 0,
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** 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[] {
|
|
217
|
+
const replies = new Map<string, number[]>();
|
|
218
|
+
const indexes = new Map<number, number>();
|
|
219
|
+
facts.forEach((fact, index) => {
|
|
220
|
+
indexes.set(fact.sequence, index);
|
|
221
|
+
if (fact.type !== MESSAGE_FACT || fact.data.role !== "assistant" || typeof fact.data.runId !== "string") return;
|
|
222
|
+
const list = replies.get(fact.data.runId) ?? [];
|
|
223
|
+
list.push(fact.sequence);
|
|
224
|
+
replies.set(fact.data.runId, list);
|
|
225
|
+
});
|
|
226
|
+
const nextReply = (runId: string, after: number): number | undefined =>
|
|
227
|
+
replies.get(runId)?.find((sequence) => sequence > after);
|
|
228
|
+
const chunks: Chunk[] = [];
|
|
229
|
+
let index = 0;
|
|
230
|
+
while (index < facts.length) {
|
|
231
|
+
const fact = facts[index];
|
|
232
|
+
if (fact === undefined) break;
|
|
233
|
+
if (fact.type === ENTRY_FACT) {
|
|
234
|
+
const runId = typeof fact.data.runId === "string" ? fact.data.runId : undefined;
|
|
235
|
+
const reply = runId === undefined ? undefined : nextReply(runId, fact.sequence);
|
|
236
|
+
if (reply !== undefined) {
|
|
237
|
+
const end = indexes.get(reply) ?? facts.length - 1;
|
|
238
|
+
chunks.push(chunkOf(facts.slice(index, end + 1)));
|
|
239
|
+
index = end + 1;
|
|
240
|
+
continue;
|
|
241
|
+
}
|
|
242
|
+
let end = index + 1;
|
|
243
|
+
while (
|
|
244
|
+
end < facts.length &&
|
|
245
|
+
facts[end]?.type === ENTRY_FACT &&
|
|
246
|
+
(runId === undefined || facts[end]?.data.runId === runId)
|
|
247
|
+
) {
|
|
248
|
+
end += 1;
|
|
249
|
+
}
|
|
250
|
+
chunks.push(chunkOf(facts.slice(index, end)));
|
|
251
|
+
index = end;
|
|
252
|
+
continue;
|
|
253
|
+
}
|
|
254
|
+
if (fact.type === MESSAGE_FACT) chunks.push(chunkOf([fact]));
|
|
255
|
+
index += 1;
|
|
256
|
+
}
|
|
257
|
+
return chunks;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
interface Page {
|
|
261
|
+
readonly chunks: readonly Chunk[];
|
|
262
|
+
readonly after: number | undefined;
|
|
263
|
+
readonly cursor: string | undefined;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function factsCursor(ref: ObjectRef, after: number): string {
|
|
267
|
+
return encodeCursor({ kind: "facts", type: ref.type, id: ref.id, after });
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** Pages count messages; a turn is one item, so its entries stay with its reply. */
|
|
271
|
+
function pagesOf(ref: ObjectRef, chunks: readonly Chunk[]): readonly Page[] {
|
|
272
|
+
const pages: Page[] = [];
|
|
273
|
+
let index = 0;
|
|
274
|
+
let after: number | undefined;
|
|
275
|
+
while (index < chunks.length) {
|
|
276
|
+
const pageChunks: Chunk[] = [];
|
|
277
|
+
let messages = 0;
|
|
278
|
+
while (index < chunks.length) {
|
|
279
|
+
const chunk = chunks[index];
|
|
280
|
+
if (chunk === undefined) break;
|
|
281
|
+
if (pageChunks.length > 0 && messages + chunk.messages > TRANSCRIPT_PAGE) break;
|
|
282
|
+
pageChunks.push(chunk);
|
|
283
|
+
messages += chunk.messages;
|
|
284
|
+
index += 1;
|
|
285
|
+
if (messages >= TRANSCRIPT_PAGE) break;
|
|
286
|
+
}
|
|
287
|
+
const last = pageChunks.at(-1);
|
|
288
|
+
if (last === undefined) break;
|
|
289
|
+
pages.push({
|
|
290
|
+
chunks: pageChunks,
|
|
291
|
+
after,
|
|
292
|
+
cursor: after === undefined ? undefined : factsCursor(ref, after),
|
|
293
|
+
});
|
|
294
|
+
after = last.last;
|
|
295
|
+
}
|
|
296
|
+
if (pages.length === 0) pages.push({ chunks: [], after: undefined, cursor: undefined });
|
|
297
|
+
return pages;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
function cursorAfter(cursor: string): number | undefined {
|
|
301
|
+
const value = decodeCursor(cursor, "chat transcript");
|
|
302
|
+
return value.kind === "facts" && typeof value.after === "number" ? value.after : undefined;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
function rendered(chunk: Chunk, speaker: string, home: string | undefined, harness: string): readonly string[] {
|
|
306
|
+
const blocks: string[] = [];
|
|
307
|
+
let lines: string[] = [];
|
|
308
|
+
const flush = (): void => {
|
|
309
|
+
if (lines.length > 0) blocks.push(lines.join("\n"));
|
|
310
|
+
lines = [];
|
|
311
|
+
};
|
|
312
|
+
for (const fact of chunk.facts) {
|
|
313
|
+
if (fact.type === ENTRY_FACT) {
|
|
314
|
+
const entry = entryOfFact(fact);
|
|
315
|
+
const markdown = entry === undefined ? undefined : entryMarkdown(entry, speaker, harness);
|
|
316
|
+
if (markdown !== undefined) lines.push(...markdown.split("\n"));
|
|
317
|
+
continue;
|
|
318
|
+
}
|
|
319
|
+
if (fact.type !== MESSAGE_FACT) continue;
|
|
320
|
+
flush();
|
|
321
|
+
const message = messageFrom(fact);
|
|
322
|
+
if (message !== undefined) blocks.push(messageMarkdown(message, speaker, home));
|
|
323
|
+
}
|
|
324
|
+
flush();
|
|
325
|
+
return blocks;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/** The position after the last fact a read showed, as the opaque mark. */
|
|
329
|
+
function markOf(sequence: number): string {
|
|
330
|
+
return String(sequence);
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
function markAfter(value: string | undefined): number | undefined {
|
|
334
|
+
return value !== undefined && /^\d{1,15}$/.test(value) ? Number(value) : undefined;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
function clock(at: number): string {
|
|
338
|
+
return new Date(at).toISOString().slice(11, 19);
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/**
|
|
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.
|
|
345
|
+
*/
|
|
346
|
+
async function tailOf(
|
|
347
|
+
ctx: ViewContext,
|
|
348
|
+
object: StoredObject,
|
|
349
|
+
facts: readonly PluginFact[],
|
|
350
|
+
speaker: string,
|
|
351
|
+
): Promise<string | undefined> {
|
|
352
|
+
const chat = chatData(object.data);
|
|
353
|
+
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());
|
|
366
|
+
}
|
|
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
|
+
}
|
|
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;
|
|
374
|
+
};
|
|
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
|
+
}
|
|
391
|
+
|
|
392
|
+
async function load(
|
|
393
|
+
ctx: ViewContext,
|
|
394
|
+
object: StoredObject,
|
|
395
|
+
sectionId: string,
|
|
396
|
+
options: { readonly cursor?: string | undefined; readonly after?: string | undefined },
|
|
397
|
+
): Promise<SectionContent> {
|
|
398
|
+
if (sectionId !== TRANSCRIPT) return { markdown: "" };
|
|
399
|
+
const ref = chatRef(object.id);
|
|
400
|
+
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);
|
|
404
|
+
const since = markAfter(options.after);
|
|
405
|
+
if (since !== undefined) {
|
|
406
|
+
// 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));
|
|
408
|
+
const blocks = chunks.flatMap((chunk) => rendered(chunk, speaker, ctx.home, chat.harness));
|
|
409
|
+
return {
|
|
410
|
+
markdown: blocks.join("\n\n---\n\n"),
|
|
411
|
+
mark: markOf(Math.max(since, chunks.at(-1)?.last ?? 0)),
|
|
412
|
+
delta: true,
|
|
413
|
+
...(tail === undefined ? {} : { tail }),
|
|
414
|
+
};
|
|
415
|
+
}
|
|
416
|
+
const pages = pagesOf(ref, chunksOf(facts));
|
|
417
|
+
const after = options.cursor === undefined ? undefined : cursorAfter(options.cursor);
|
|
418
|
+
const index = pages.findIndex((page) => page.after === after);
|
|
419
|
+
const selected = pages[index < 0 ? 0 : index] ?? pages[0];
|
|
420
|
+
const blocks = (selected?.chunks ?? []).flatMap((chunk) => rendered(chunk, speaker, ctx.home, chat.harness));
|
|
421
|
+
const body = blocks.length === 0 && options.cursor === undefined ? "No messages yet." : blocks.join("\n\n---\n\n");
|
|
422
|
+
// Every page says which agent answers, as the row does.
|
|
423
|
+
const markdown = chat.harness.length > 0
|
|
424
|
+
? `Agent: ${agentLine(chat)}\n\n${body}`
|
|
425
|
+
: body;
|
|
426
|
+
const nextPage = index < 0 ? undefined : pages[index + 1];
|
|
427
|
+
|
|
428
|
+
// The table of contents: the cursor each page starts at, the first one without.
|
|
429
|
+
const toc: SectionPage[] = pages.map((page, at) =>
|
|
430
|
+
at === 0 || page.cursor === undefined
|
|
431
|
+
? { label: `Page ${at + 1}` }
|
|
432
|
+
: { label: `Page ${at + 1}`, cursor: page.cursor },
|
|
433
|
+
);
|
|
434
|
+
return {
|
|
435
|
+
markdown,
|
|
436
|
+
mark: markOf(selected?.chunks.at(-1)?.last ?? 0),
|
|
437
|
+
...(nextPage?.cursor === undefined ? {} : { next: nextPage.cursor }),
|
|
438
|
+
...(toc.length > 1 ? { pages: toc } : {}),
|
|
439
|
+
...(tail === undefined ? {} : { tail }),
|
|
440
|
+
};
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
/** The views of the chat type. */
|
|
444
|
+
export const chatViews: ObjectViews = { row, sections, load };
|