@operad-io/chat 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +12 -2
- package/package.json +22 -4
- package/src/index.ts +373 -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/model.ts
ADDED
|
@@ -0,0 +1,717 @@
|
|
|
1
|
+
/** The shape of a chat and its messages, and how a chat is read from its facts. */
|
|
2
|
+
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
import { statSync } from "node:fs";
|
|
5
|
+
import { basename, extname } from "node:path";
|
|
6
|
+
import type { ActionArgSchema, JsonValue, ObjectRef, ObjectStore, PluginFact } from "@operad-io/engine";
|
|
7
|
+
import { isRecord, storedType, stringList } from "@operad-io/engine";
|
|
8
|
+
|
|
9
|
+
/** The object type of a chat. */
|
|
10
|
+
export const CHAT_TYPE = "chat";
|
|
11
|
+
|
|
12
|
+
/** The fact type of one message on a chat; a person's and the assistant's alike. */
|
|
13
|
+
export const MESSAGE_FACT = "chat.message";
|
|
14
|
+
|
|
15
|
+
/** The fact type of one finished part of an answer: text, thinking or a tool call. */
|
|
16
|
+
export const ENTRY_FACT = "chat.entry";
|
|
17
|
+
|
|
18
|
+
/** The fact type of a reply run that began on a chat: the run id, so a view can find the step's log. */
|
|
19
|
+
export const RUN_FACT = "chat.run";
|
|
20
|
+
|
|
21
|
+
/** How a tool call ended. */
|
|
22
|
+
export type ToolResult = "done" | "failed" | "blocked" | "denied";
|
|
23
|
+
|
|
24
|
+
/** The kinds of part an answer is recorded as. */
|
|
25
|
+
export type EntryKind = "text" | "thinking" | "tool" | "stopped";
|
|
26
|
+
|
|
27
|
+
/** The event type a new message is: its source is `ios`, `telegram`, `cli`, `tui` or `other`. */
|
|
28
|
+
export const MESSAGE_EVENT = "message";
|
|
29
|
+
|
|
30
|
+
/** The fact type of a change of a chat's model: who changed it, from what, to what. */
|
|
31
|
+
export const MODEL_FACT = "chat.model";
|
|
32
|
+
|
|
33
|
+
/** The fact type of a change of a chat's effort: who changed it, from what, to what. */
|
|
34
|
+
export const EFFORT_FACT = "chat.effort";
|
|
35
|
+
|
|
36
|
+
/** The fact type of a chat that was closed. */
|
|
37
|
+
export const CLOSED_FACT = "chat.closed";
|
|
38
|
+
|
|
39
|
+
/** The list filters of chats: closed ones are hidden unless asked for. */
|
|
40
|
+
export const CHAT_FILTERS = [
|
|
41
|
+
{ name: "open", default: true, states: ["open"] },
|
|
42
|
+
{ name: "closed", states: ["closed"] },
|
|
43
|
+
] as const;
|
|
44
|
+
|
|
45
|
+
/** Where a message can come from. */
|
|
46
|
+
export const CHAT_SOURCES = ["ios", "telegram", "cli", "tui"] as const;
|
|
47
|
+
|
|
48
|
+
/** The event source of a message from a client the chat does not know by name. */
|
|
49
|
+
export const OTHER_SOURCE = "other";
|
|
50
|
+
|
|
51
|
+
export type ChatSource = (typeof CHAT_SOURCES)[number];
|
|
52
|
+
|
|
53
|
+
/** Who wrote a message: the person, or the assistant. */
|
|
54
|
+
export type MessageRole = "user" | "assistant";
|
|
55
|
+
|
|
56
|
+
/** What a chat stores. The creating plugin gives every field but `session`. */
|
|
57
|
+
export interface ChatData {
|
|
58
|
+
readonly [key: string]: unknown;
|
|
59
|
+
/** The object one level up (a repository, a bot); a full object id. */
|
|
60
|
+
readonly parent?: string | undefined;
|
|
61
|
+
/** The harness plugin that answers, such as `claude`; fixed once the chat exists. */
|
|
62
|
+
readonly harness: string;
|
|
63
|
+
/** Where the harness works. */
|
|
64
|
+
readonly cwd: string;
|
|
65
|
+
/** The access profile the harness applies; opaque here. */
|
|
66
|
+
readonly access: Readonly<Record<string, JsonValue>>;
|
|
67
|
+
readonly skills: readonly string[];
|
|
68
|
+
readonly title: string;
|
|
69
|
+
/** Whether the chat was closed; a closed chat takes no messages. */
|
|
70
|
+
readonly closed: boolean;
|
|
71
|
+
/** The harness's own reference to its conversation; never shown. */
|
|
72
|
+
readonly session?: string | null | undefined;
|
|
73
|
+
/** The channels (`telegram:<chat>`) whose messages land here. */
|
|
74
|
+
readonly channels: readonly string[];
|
|
75
|
+
/**
|
|
76
|
+
* A step (`<plugin>/<step>`) that gives the working directory, access profile
|
|
77
|
+
* and skills as they are now; the reply asks it every time, so a chat whose
|
|
78
|
+
* settings live elsewhere (a bot) follows them. The fields
|
|
79
|
+
* above are then what the chat started with.
|
|
80
|
+
*/
|
|
81
|
+
readonly refresh?: string | undefined;
|
|
82
|
+
/** The model the next reply uses; one the agent's plugin lists. Absent for an agent that lists none. */
|
|
83
|
+
readonly model?: string | undefined;
|
|
84
|
+
/** The effort the next reply uses; one the agent's plugin lists. Absent for an agent that lists none. */
|
|
85
|
+
readonly effort?: string | undefined;
|
|
86
|
+
/** The agent's default effort when this chat was made, so the row can tell a choice from the default. */
|
|
87
|
+
readonly effortDefault?: string | undefined;
|
|
88
|
+
/** The model that gave the last reply, when its harness reported one. */
|
|
89
|
+
readonly lastModel?: string | undefined;
|
|
90
|
+
/** What the replies cost so far, in millionths of a dollar; absent while no reply reported a cost. */
|
|
91
|
+
readonly costMicros?: number | undefined;
|
|
92
|
+
/** How far to trust `costMicros`: the least exact of the replies counted. */
|
|
93
|
+
readonly costQuality?: CostQuality | undefined;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** How far to trust a cost: the harness's own words. */
|
|
97
|
+
export type CostQuality = "exact" | "estimated" | "incomplete";
|
|
98
|
+
|
|
99
|
+
/** What a plugin gives to create a chat. */
|
|
100
|
+
export interface NewChat {
|
|
101
|
+
readonly parent?: string | undefined;
|
|
102
|
+
readonly harness: string;
|
|
103
|
+
readonly cwd: string;
|
|
104
|
+
readonly access?: Readonly<Record<string, JsonValue>> | undefined;
|
|
105
|
+
readonly skills?: readonly string[] | undefined;
|
|
106
|
+
readonly title: string;
|
|
107
|
+
readonly channels?: readonly string[] | undefined;
|
|
108
|
+
/** See {@link ChatData.model}. */
|
|
109
|
+
readonly model?: string | undefined;
|
|
110
|
+
/** See {@link ChatData.effort}. */
|
|
111
|
+
readonly effort?: string | undefined;
|
|
112
|
+
/** See {@link ChatData.effortDefault}. */
|
|
113
|
+
readonly effortDefault?: string | undefined;
|
|
114
|
+
/** See {@link ChatData.refresh}. */
|
|
115
|
+
readonly refresh?: string | undefined;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** One file attached to a message: where it is stored, and what a client shows of it. */
|
|
119
|
+
export interface Attachment {
|
|
120
|
+
readonly [key: string]: unknown;
|
|
121
|
+
readonly path: string;
|
|
122
|
+
readonly name: string;
|
|
123
|
+
readonly type: string;
|
|
124
|
+
readonly size: number;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** The image types claude and pi take as image input. */
|
|
128
|
+
export const IMAGE_TYPES = ["image/png", "image/jpeg", "image/gif", "image/webp"] as const;
|
|
129
|
+
|
|
130
|
+
const MEDIA_TYPES: Readonly<Record<string, string>> = {
|
|
131
|
+
".png": "image/png",
|
|
132
|
+
".jpg": "image/jpeg",
|
|
133
|
+
".jpeg": "image/jpeg",
|
|
134
|
+
".gif": "image/gif",
|
|
135
|
+
".webp": "image/webp",
|
|
136
|
+
".heic": "image/heic",
|
|
137
|
+
".pdf": "application/pdf",
|
|
138
|
+
".txt": "text/plain",
|
|
139
|
+
".md": "text/markdown",
|
|
140
|
+
".json": "application/json",
|
|
141
|
+
".csv": "text/csv",
|
|
142
|
+
".mp4": "video/mp4",
|
|
143
|
+
".mov": "video/quicktime",
|
|
144
|
+
".m4a": "audio/mp4",
|
|
145
|
+
".mp3": "audio/mpeg",
|
|
146
|
+
".zip": "application/zip",
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
/** The media type a file name's extension says; `application/octet-stream` when it says none. */
|
|
150
|
+
export function mediaTypeOf(name: string): string {
|
|
151
|
+
return MEDIA_TYPES[extname(name).toLowerCase()] ?? "application/octet-stream";
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** The attachment record of a stored file; throws when the file is not there. */
|
|
155
|
+
export function attachmentOf(path: string): Attachment {
|
|
156
|
+
let size: number;
|
|
157
|
+
try {
|
|
158
|
+
size = statSync(path).size;
|
|
159
|
+
} catch {
|
|
160
|
+
throw new Error(`the attachment ${path} is not there`);
|
|
161
|
+
}
|
|
162
|
+
const name = basename(path);
|
|
163
|
+
// The type the upload came with wins over a guess from the extension.
|
|
164
|
+
return { path, name, type: storedType(path) ?? mediaTypeOf(name), size };
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** The attachments of a message fact; an older fact that holds bare paths reads as records. */
|
|
168
|
+
export function attachmentsOf(value: unknown): readonly Attachment[] {
|
|
169
|
+
if (!Array.isArray(value)) return [];
|
|
170
|
+
const found: Attachment[] = [];
|
|
171
|
+
for (const item of value) {
|
|
172
|
+
if (typeof item === "string") {
|
|
173
|
+
found.push({ path: item, name: basename(item), type: mediaTypeOf(item), size: 0 });
|
|
174
|
+
} else if (isRecord(item) && typeof item.path === "string" && item.path.length > 0) {
|
|
175
|
+
const name = typeof item.name === "string" ? item.name : basename(item.path);
|
|
176
|
+
found.push({
|
|
177
|
+
path: item.path,
|
|
178
|
+
name,
|
|
179
|
+
type: typeof item.type === "string" ? item.type : mediaTypeOf(name),
|
|
180
|
+
size: typeof item.size === "number" ? item.size : 0,
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
return found;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** What a model-change fact holds. */
|
|
188
|
+
export interface ModelChangedData {
|
|
189
|
+
readonly [key: string]: unknown;
|
|
190
|
+
readonly by: { readonly via: string; readonly id: string };
|
|
191
|
+
readonly from: string | null;
|
|
192
|
+
readonly to: string;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** What an effort-change fact holds. */
|
|
196
|
+
export interface EffortChangedData {
|
|
197
|
+
readonly [key: string]: unknown;
|
|
198
|
+
readonly by: { readonly via: string; readonly id: string };
|
|
199
|
+
readonly from: string | null;
|
|
200
|
+
readonly to: string;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* The effort a new chat starts with: the one asked for, else the preferred one
|
|
205
|
+
* (a bot's), else the agent's default. An effort the agent does not list is
|
|
206
|
+
* refused by name; an agent that lists none takes none.
|
|
207
|
+
*/
|
|
208
|
+
export function startingEffort(
|
|
209
|
+
harness: string,
|
|
210
|
+
efforts: { readonly list: readonly string[]; readonly default: string | null } | undefined,
|
|
211
|
+
asked: string | undefined,
|
|
212
|
+
preferred?: string | undefined,
|
|
213
|
+
): string | undefined {
|
|
214
|
+
const list = efforts?.list ?? [];
|
|
215
|
+
const wanted = asked ?? preferred;
|
|
216
|
+
if (wanted !== undefined) {
|
|
217
|
+
if (!list.includes(wanted)) {
|
|
218
|
+
throw new Error(
|
|
219
|
+
`the agent "${harness}" cannot use the effort "${wanted}"; it offers: ${list.join(", ") || "none"}`,
|
|
220
|
+
);
|
|
221
|
+
}
|
|
222
|
+
return wanted;
|
|
223
|
+
}
|
|
224
|
+
return efforts?.default ?? undefined;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* The model a new chat starts with: the one asked for, else the preferred one
|
|
229
|
+
* (a bot's), else the agent's default. A model the agent does not list is refused
|
|
230
|
+
* by name; an agent that lists none takes none.
|
|
231
|
+
*/
|
|
232
|
+
export function startingModel(
|
|
233
|
+
harness: string,
|
|
234
|
+
models: { readonly list: readonly string[]; readonly default: string | null } | undefined,
|
|
235
|
+
asked: string | undefined,
|
|
236
|
+
preferred?: string | undefined,
|
|
237
|
+
): string | undefined {
|
|
238
|
+
const list = models?.list ?? [];
|
|
239
|
+
const wanted = asked ?? preferred;
|
|
240
|
+
if (wanted !== undefined) {
|
|
241
|
+
if (!list.includes(wanted)) {
|
|
242
|
+
throw new Error(
|
|
243
|
+
`the agent "${harness}" cannot use the model "${wanted}"; it offers: ${list.join(", ") || "none"}`,
|
|
244
|
+
);
|
|
245
|
+
}
|
|
246
|
+
return wanted;
|
|
247
|
+
}
|
|
248
|
+
return models?.default ?? undefined;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** What a message fact holds. Attachment paths stay empty until attachments exist. */
|
|
252
|
+
export interface MessageData {
|
|
253
|
+
readonly [key: string]: unknown;
|
|
254
|
+
readonly id: string;
|
|
255
|
+
readonly role: MessageRole;
|
|
256
|
+
readonly from: { readonly via: string; readonly id: string };
|
|
257
|
+
readonly text: string;
|
|
258
|
+
/** The files sent with it; their paths are under the chat's attachment directory. */
|
|
259
|
+
readonly attachments: readonly Attachment[];
|
|
260
|
+
/** Where it came from, and its id there (a Telegram message id), when it has one. */
|
|
261
|
+
readonly source: { readonly kind: string; readonly ref: string | null };
|
|
262
|
+
/** An assistant message: the ids of the messages it answers. */
|
|
263
|
+
readonly replyTo?: readonly string[] | undefined;
|
|
264
|
+
/** The run whose answer this message or entry belongs to. */
|
|
265
|
+
readonly runId?: string | undefined;
|
|
266
|
+
/** An assistant message: the harness session after it. */
|
|
267
|
+
readonly session?: string | undefined;
|
|
268
|
+
/** An assistant message: the model that answered, when the harness reported it. */
|
|
269
|
+
readonly model?: string | undefined;
|
|
270
|
+
/** An assistant message: what it cost in millionths of a dollar, when reported. */
|
|
271
|
+
readonly costMicros?: number | undefined;
|
|
272
|
+
readonly costQuality?: CostQuality | undefined;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** One message with when it was recorded. */
|
|
276
|
+
export interface Message extends MessageData {
|
|
277
|
+
readonly at: number;
|
|
278
|
+
readonly sequence: number;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* What one finished part of an answer holds. Tool calls carry the call's id and
|
|
283
|
+
* name, what ran, how it ended, when it started, how long it took, the start of
|
|
284
|
+
* its output and, when the output was long, the file that holds all of it.
|
|
285
|
+
*/
|
|
286
|
+
export interface EntryData {
|
|
287
|
+
readonly [key: string]: unknown;
|
|
288
|
+
readonly runId: string;
|
|
289
|
+
readonly kind: EntryKind;
|
|
290
|
+
/** Text or thinking; the half-written reply of a stopped run is `stopped`. */
|
|
291
|
+
readonly text?: string | undefined;
|
|
292
|
+
readonly callId?: string | undefined;
|
|
293
|
+
readonly toolName?: string | undefined;
|
|
294
|
+
/** What ran: the command, path or main argument, as the harness summarized it. */
|
|
295
|
+
readonly input?: string | null | undefined;
|
|
296
|
+
readonly result?: ToolResult | undefined;
|
|
297
|
+
/** Epoch milliseconds; null when the harness gave no start time. */
|
|
298
|
+
readonly startedAt?: number | null | undefined;
|
|
299
|
+
readonly durationMs?: number | undefined;
|
|
300
|
+
/** The first 4 KB of what the call printed; null when it printed nothing. */
|
|
301
|
+
readonly output?: string | null | undefined;
|
|
302
|
+
/** The file that holds the whole output, when it was longer than 4 KB. */
|
|
303
|
+
readonly outputPath?: string | undefined;
|
|
304
|
+
readonly outputTruncated?: boolean | undefined;
|
|
305
|
+
/** The first line of the error, when the call failed. */
|
|
306
|
+
readonly error?: string | null | undefined;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** One entry with when its fact was recorded. */
|
|
310
|
+
export interface Entry extends EntryData {
|
|
311
|
+
readonly at: number;
|
|
312
|
+
readonly sequence: number;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/** What a close fact holds: who closed the chat. */
|
|
316
|
+
export interface ClosedData {
|
|
317
|
+
readonly [key: string]: unknown;
|
|
318
|
+
readonly by: { readonly via: string; readonly id: string };
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/** The chat fields of a stored object, with the lists defaulted. */
|
|
322
|
+
export function chatData(data: Readonly<Record<string, unknown>>): ChatData {
|
|
323
|
+
return {
|
|
324
|
+
...data,
|
|
325
|
+
harness: typeof data.harness === "string" ? data.harness : "",
|
|
326
|
+
cwd: typeof data.cwd === "string" ? data.cwd : "",
|
|
327
|
+
access: isRecord(data.access) ? (data.access as Record<string, JsonValue>) : {},
|
|
328
|
+
skills: stringList(data.skills),
|
|
329
|
+
title: typeof data.title === "string" ? data.title : "",
|
|
330
|
+
closed: data.closed === true,
|
|
331
|
+
channels: stringList(data.channels),
|
|
332
|
+
...(typeof data.refresh === "string" && data.refresh.length > 0 ? { refresh: data.refresh } : {}),
|
|
333
|
+
...(typeof data.model === "string" && data.model.length > 0 ? { model: data.model } : {}),
|
|
334
|
+
...(typeof data.effort === "string" && data.effort.length > 0 ? { effort: data.effort } : {}),
|
|
335
|
+
...(typeof data.effortDefault === "string" && data.effortDefault.length > 0 ? { effortDefault: data.effortDefault } : {}),
|
|
336
|
+
...(typeof data.lastModel === "string" && data.lastModel.length > 0 ? { lastModel: data.lastModel } : {}),
|
|
337
|
+
...(typeof data.costMicros === "number" && Number.isFinite(data.costMicros) ? { costMicros: data.costMicros } : {}),
|
|
338
|
+
...(isCostQuality(data.costQuality) ? { costQuality: data.costQuality } : {}),
|
|
339
|
+
};
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
function isCostQuality(value: unknown): value is CostQuality {
|
|
343
|
+
return value === "exact" || value === "estimated" || value === "incomplete";
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/** A cost as text: `$0.12`, `~$0.12` when estimated, `≥$0.12` when only part was priced. */
|
|
347
|
+
export function costText(micros: number, quality: CostQuality | undefined): string {
|
|
348
|
+
const symbol = quality === "estimated" ? "~" : quality === "incomplete" ? "≥" : "";
|
|
349
|
+
return `${symbol}$${(micros / 1e6).toFixed(2)}`;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/** The model and cost parts of a line, as far as they are known. */
|
|
353
|
+
export function modelAndCost(
|
|
354
|
+
model: string | undefined,
|
|
355
|
+
micros: number | undefined,
|
|
356
|
+
quality: CostQuality | undefined,
|
|
357
|
+
): readonly string[] {
|
|
358
|
+
return [
|
|
359
|
+
...(model === undefined || model.length === 0 ? [] : [model]),
|
|
360
|
+
...(micros === undefined ? [] : [costText(micros, quality)]),
|
|
361
|
+
];
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/** What a chat uses, for its row and its page: `claude · sonnet · high · $0.12`. */
|
|
365
|
+
export function agentLine(chat: ChatData): string {
|
|
366
|
+
const model = chat.model ?? chat.lastModel;
|
|
367
|
+
const effort =
|
|
368
|
+
chat.effort !== undefined && chat.effort !== chat.effortDefault ? [chat.effort] : [];
|
|
369
|
+
return [
|
|
370
|
+
chat.harness,
|
|
371
|
+
...(model === undefined || model.length === 0 ? [] : [model]),
|
|
372
|
+
...effort,
|
|
373
|
+
...(chat.costMicros === undefined ? [] : [costText(chat.costMicros, chat.costQuality)]),
|
|
374
|
+
]
|
|
375
|
+
.filter((part) => part.length > 0)
|
|
376
|
+
.join(" · ");
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/** The model, cost and quality a harness's `usage` reports; each only when it did. */
|
|
380
|
+
export function usageOf(value: unknown): {
|
|
381
|
+
readonly model?: string;
|
|
382
|
+
readonly costMicros?: number;
|
|
383
|
+
readonly costQuality?: CostQuality;
|
|
384
|
+
} {
|
|
385
|
+
if (!isRecord(value)) return {};
|
|
386
|
+
const micros = value.costMicros;
|
|
387
|
+
const known = typeof micros === "number" && Number.isFinite(micros);
|
|
388
|
+
return {
|
|
389
|
+
...(typeof value.model === "string" && value.model.length > 0 ? { model: value.model } : {}),
|
|
390
|
+
...(known ? { costMicros: micros } : {}),
|
|
391
|
+
...(known ? { costQuality: isCostQuality(value.costQuality) ? value.costQuality : "estimated" } : {}),
|
|
392
|
+
};
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
const QUALITY_ORDER: readonly CostQuality[] = ["exact", "estimated", "incomplete"];
|
|
396
|
+
|
|
397
|
+
/** The less exact of two qualities; an absent one counts for the other. */
|
|
398
|
+
export function worseQuality(a: CostQuality | undefined, b: CostQuality | undefined): CostQuality | undefined {
|
|
399
|
+
if (a === undefined) return b;
|
|
400
|
+
if (b === undefined) return a;
|
|
401
|
+
return QUALITY_ORDER.indexOf(a) >= QUALITY_ORDER.indexOf(b) ? a : b;
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/** The longest title taken from a first message. */
|
|
405
|
+
export const TITLE_FROM_MESSAGE_MAX = 60;
|
|
406
|
+
|
|
407
|
+
/**
|
|
408
|
+
* A chat title from the start of its first message: its first non-empty line,
|
|
409
|
+
* cut at a word boundary when it is longer than {@link TITLE_FROM_MESSAGE_MAX},
|
|
410
|
+
* with an ellipsis. Undefined when the message has no text.
|
|
411
|
+
*/
|
|
412
|
+
export function titleFromMessage(message: string): string | undefined {
|
|
413
|
+
const line = message.split(/\r?\n/).map((part) => part.trim()).find((part) => part.length > 0);
|
|
414
|
+
if (line === undefined) return undefined;
|
|
415
|
+
const flat = line.replace(/\s+/g, " ");
|
|
416
|
+
if (flat.length <= TITLE_FROM_MESSAGE_MAX) return flat;
|
|
417
|
+
const cut = flat.slice(0, TITLE_FROM_MESSAGE_MAX);
|
|
418
|
+
const space = cut.lastIndexOf(" ");
|
|
419
|
+
const base = space >= TITLE_FROM_MESSAGE_MAX / 2 ? cut.slice(0, space) : cut;
|
|
420
|
+
return `${base.replace(/[\s.,;:!?]+$/, "")}…`;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
/** A new message id; the event's key. */
|
|
424
|
+
export function newMessageId(): string {
|
|
425
|
+
return `m-${randomUUID()}`;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
/** The reference of a chat in events and facts. */
|
|
429
|
+
export function chatRef(id: string): ObjectRef {
|
|
430
|
+
return { type: CHAT_TYPE, id };
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
/** The next free chat id, `C-0001` upward. */
|
|
434
|
+
async function nextChatId(store: ObjectStore): Promise<string> {
|
|
435
|
+
let highest = 0;
|
|
436
|
+
let cursor: string | undefined;
|
|
437
|
+
do {
|
|
438
|
+
const page = await store.list(CHAT_TYPE, { ...(cursor === undefined ? {} : { cursor }) });
|
|
439
|
+
for (const object of page.objects) {
|
|
440
|
+
const match = /^C-(\d+)$/.exec(object.id);
|
|
441
|
+
if (match !== null) highest = Math.max(highest, Number(match[1]));
|
|
442
|
+
}
|
|
443
|
+
cursor = page.next;
|
|
444
|
+
} while (cursor !== undefined);
|
|
445
|
+
return `C-${String(highest + 1).padStart(4, "0")}`;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
/** Creates a chat for a plugin that has every field; returns its id. */
|
|
449
|
+
export async function createChat(
|
|
450
|
+
store: ObjectStore,
|
|
451
|
+
input: NewChat,
|
|
452
|
+
cause: string,
|
|
453
|
+
): Promise<string> {
|
|
454
|
+
if (input.harness.trim().length === 0) throw new Error("a chat needs an agent");
|
|
455
|
+
if (input.cwd.trim().length === 0) throw new Error("a chat needs a working directory");
|
|
456
|
+
if (input.title.trim().length === 0) throw new Error("a chat needs a title");
|
|
457
|
+
const data: ChatData = {
|
|
458
|
+
...(input.parent === undefined ? {} : { parent: input.parent }),
|
|
459
|
+
harness: input.harness,
|
|
460
|
+
cwd: input.cwd,
|
|
461
|
+
access: input.access ?? {},
|
|
462
|
+
skills: input.skills ?? [],
|
|
463
|
+
title: input.title.trim(),
|
|
464
|
+
closed: false,
|
|
465
|
+
session: null,
|
|
466
|
+
channels: input.channels ?? [],
|
|
467
|
+
...(input.model === undefined ? {} : { model: input.model }),
|
|
468
|
+
...(input.effort === undefined ? {} : { effort: input.effort }),
|
|
469
|
+
...(input.effort === undefined || input.effortDefault === undefined ? {} : { effortDefault: input.effortDefault }),
|
|
470
|
+
...(input.refresh === undefined ? {} : { refresh: input.refresh }),
|
|
471
|
+
};
|
|
472
|
+
// The id counts up; a taken one (two chats made at once) moves on to the next.
|
|
473
|
+
for (let attempt = 0; attempt < 20; attempt += 1) {
|
|
474
|
+
const base = await nextChatId(store);
|
|
475
|
+
const id = `C-${String(Number(base.slice(2)) + attempt).padStart(4, "0")}`;
|
|
476
|
+
if ((await store.get(CHAT_TYPE, id)) !== undefined) continue;
|
|
477
|
+
await store.put(CHAT_TYPE, id, data, cause);
|
|
478
|
+
return id;
|
|
479
|
+
}
|
|
480
|
+
throw new Error("cannot find a free chat id");
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
function messageOfFact(fact: PluginFact): Message | undefined {
|
|
484
|
+
if (fact.type !== MESSAGE_FACT) return undefined;
|
|
485
|
+
const data = fact.data;
|
|
486
|
+
if (typeof data.id !== "string" || typeof data.text !== "string") return undefined;
|
|
487
|
+
if (data.role !== "user" && data.role !== "assistant") return undefined;
|
|
488
|
+
const from = isRecord(data.from) ? data.from : {};
|
|
489
|
+
const source = isRecord(data.source) ? data.source : {};
|
|
490
|
+
return {
|
|
491
|
+
id: data.id,
|
|
492
|
+
role: data.role,
|
|
493
|
+
from: {
|
|
494
|
+
via: typeof from.via === "string" ? from.via : "",
|
|
495
|
+
id: typeof from.id === "string" ? from.id : "",
|
|
496
|
+
},
|
|
497
|
+
text: data.text,
|
|
498
|
+
attachments: attachmentsOf(data.attachments),
|
|
499
|
+
source: {
|
|
500
|
+
kind: typeof source.kind === "string" ? source.kind : "",
|
|
501
|
+
ref: typeof source.ref === "string" ? source.ref : null,
|
|
502
|
+
},
|
|
503
|
+
...(Array.isArray(data.replyTo) ? { replyTo: stringList(data.replyTo) } : {}),
|
|
504
|
+
...(typeof data.runId === "string" && data.runId.length > 0 ? { runId: data.runId } : {}),
|
|
505
|
+
...(typeof data.session === "string" ? { session: data.session } : {}),
|
|
506
|
+
...(typeof data.model === "string" && data.model.length > 0 ? { model: data.model } : {}),
|
|
507
|
+
...(typeof data.costMicros === "number" && Number.isFinite(data.costMicros) ? { costMicros: data.costMicros } : {}),
|
|
508
|
+
...(isCostQuality(data.costQuality) ? { costQuality: data.costQuality } : {}),
|
|
509
|
+
at: fact.at,
|
|
510
|
+
sequence: fact.sequence,
|
|
511
|
+
};
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
function isToolResult(value: unknown): value is ToolResult {
|
|
515
|
+
return value === "done" || value === "failed" || value === "blocked" || value === "denied";
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
export function entryOfFact(fact: PluginFact): Entry | undefined {
|
|
519
|
+
if (fact.type !== ENTRY_FACT) return undefined;
|
|
520
|
+
const data = fact.data;
|
|
521
|
+
if (typeof data.runId !== "string" || data.runId.length === 0) return undefined;
|
|
522
|
+
const kind = data.kind;
|
|
523
|
+
if (kind !== "text" && kind !== "thinking" && kind !== "tool" && kind !== "stopped") return undefined;
|
|
524
|
+
const entryKind: EntryKind = kind;
|
|
525
|
+
const base = { runId: data.runId, kind: entryKind, at: fact.at, sequence: fact.sequence };
|
|
526
|
+
if (entryKind === "tool") {
|
|
527
|
+
if (typeof data.callId !== "string" || typeof data.toolName !== "string" || !isToolResult(data.result)) {
|
|
528
|
+
return undefined;
|
|
529
|
+
}
|
|
530
|
+
return {
|
|
531
|
+
...base,
|
|
532
|
+
callId: data.callId,
|
|
533
|
+
toolName: data.toolName,
|
|
534
|
+
...(typeof data.input === "string" || data.input === null ? { input: data.input } : {}),
|
|
535
|
+
result: data.result,
|
|
536
|
+
...(typeof data.startedAt === "number" || data.startedAt === null ? { startedAt: data.startedAt } : {}),
|
|
537
|
+
...(typeof data.durationMs === "number" && Number.isFinite(data.durationMs) ? { durationMs: data.durationMs } : {}),
|
|
538
|
+
...(typeof data.output === "string" || data.output === null ? { output: data.output } : {}),
|
|
539
|
+
...(typeof data.outputPath === "string" ? { outputPath: data.outputPath } : {}),
|
|
540
|
+
...(data.outputTruncated === true ? { outputTruncated: true } : {}),
|
|
541
|
+
...(typeof data.error === "string" || data.error === null ? { error: data.error } : {}),
|
|
542
|
+
};
|
|
543
|
+
}
|
|
544
|
+
return typeof data.text === "string" ? { ...base, text: data.text } : undefined;
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
/** One page of a chat's messages from `cursor`, and where the next page starts. */
|
|
548
|
+
export function messagePage(
|
|
549
|
+
store: ObjectStore,
|
|
550
|
+
chat: string,
|
|
551
|
+
cursor: string | undefined,
|
|
552
|
+
limit: number,
|
|
553
|
+
): { readonly messages: readonly Message[]; readonly next: string | undefined } {
|
|
554
|
+
const messages: Message[] = [];
|
|
555
|
+
let at = cursor;
|
|
556
|
+
for (;;) {
|
|
557
|
+
const page = store.facts(chatRef(chat), {
|
|
558
|
+
...(at === undefined ? {} : { cursor: at }),
|
|
559
|
+
limit,
|
|
560
|
+
});
|
|
561
|
+
for (const fact of page.facts) {
|
|
562
|
+
const message = messageOfFact(fact);
|
|
563
|
+
if (message !== undefined) messages.push(message);
|
|
564
|
+
}
|
|
565
|
+
if (page.next === undefined || messages.length >= limit) {
|
|
566
|
+
return { messages, next: page.next };
|
|
567
|
+
}
|
|
568
|
+
at = page.next;
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
/** Every message of a chat, oldest first. */
|
|
573
|
+
export function allMessages(store: ObjectStore, chat: string): readonly Message[] {
|
|
574
|
+
const found: Message[] = [];
|
|
575
|
+
let cursor: string | undefined;
|
|
576
|
+
do {
|
|
577
|
+
const page = messagePage(store, chat, cursor, 500);
|
|
578
|
+
found.push(...page.messages);
|
|
579
|
+
cursor = page.next;
|
|
580
|
+
} while (cursor !== undefined);
|
|
581
|
+
return found;
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
/** Every entry of a chat, oldest first. */
|
|
585
|
+
export function allEntries(store: ObjectStore, chat: string): readonly Entry[] {
|
|
586
|
+
const found: Entry[] = [];
|
|
587
|
+
let cursor: string | undefined;
|
|
588
|
+
do {
|
|
589
|
+
const page = store.facts(chatRef(chat), {
|
|
590
|
+
...(cursor === undefined ? {} : { cursor }),
|
|
591
|
+
limit: 500,
|
|
592
|
+
});
|
|
593
|
+
for (const fact of page.facts) {
|
|
594
|
+
const entry = entryOfFact(fact);
|
|
595
|
+
if (entry !== undefined) found.push(entry);
|
|
596
|
+
}
|
|
597
|
+
cursor = page.next;
|
|
598
|
+
} while (cursor !== undefined);
|
|
599
|
+
return found;
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
/** Every fact of a chat, oldest first. */
|
|
603
|
+
export function chatFacts(store: ObjectStore, chat: string): readonly PluginFact[] {
|
|
604
|
+
const facts: PluginFact[] = [];
|
|
605
|
+
let cursor: string | undefined;
|
|
606
|
+
do {
|
|
607
|
+
const page = store.facts(chatRef(chat), { ...(cursor === undefined ? {} : { cursor }), limit: 500 });
|
|
608
|
+
facts.push(...page.facts);
|
|
609
|
+
cursor = page.next;
|
|
610
|
+
} while (cursor !== undefined);
|
|
611
|
+
return facts;
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
/** The run id of the latest reply run recorded on a chat, if any. */
|
|
615
|
+
export function latestRunOf(facts: readonly PluginFact[]): string | undefined {
|
|
616
|
+
let found: string | undefined;
|
|
617
|
+
for (const fact of facts) {
|
|
618
|
+
if (fact.type === RUN_FACT && typeof fact.data.runId === "string" && fact.data.runId.length > 0) {
|
|
619
|
+
found = fact.data.runId;
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
return found;
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
/** The person's messages no assistant message answers yet, oldest first. */
|
|
626
|
+
export function unanswered(messages: readonly Message[]): readonly Message[] {
|
|
627
|
+
const answered = new Set<string>();
|
|
628
|
+
for (const message of messages) {
|
|
629
|
+
if (message.role === "assistant") {
|
|
630
|
+
for (const id of message.replyTo ?? []) answered.add(id);
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
return messages.filter((message) => message.role === "user" && !answered.has(message.id));
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
/** The harness session after the last reply, else the chat's own reference. */
|
|
637
|
+
export function currentSession(
|
|
638
|
+
chat: ChatData,
|
|
639
|
+
messages: readonly Message[],
|
|
640
|
+
): string | undefined {
|
|
641
|
+
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
642
|
+
const message = messages[index];
|
|
643
|
+
if (message?.role === "assistant" && message.session !== undefined) return message.session;
|
|
644
|
+
}
|
|
645
|
+
return typeof chat.session === "string" && chat.session.length > 0 ? chat.session : undefined;
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
function sizeText(size: number): string {
|
|
649
|
+
if (size < 1024) return `${size} B`;
|
|
650
|
+
if (size < 1024 * 1024) return `${Math.round(size / 1024)} KB`;
|
|
651
|
+
return `${(size / (1024 * 1024)).toFixed(1)} MB`;
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
/** The lines that give a message's files to an agent as paths; `shown` marks those it also gets as images. */
|
|
655
|
+
function attachmentLines(message: Message, shown: ReadonlySet<string>): string {
|
|
656
|
+
if (message.attachments.length === 0) return "";
|
|
657
|
+
const lines = message.attachments.map(
|
|
658
|
+
(file) =>
|
|
659
|
+
`- ${file.path} (${file.name}, ${file.type}, ${sizeText(file.size)}${shown.has(file.path) ? "; also given to you as an image" : ""})`,
|
|
660
|
+
);
|
|
661
|
+
return `Attached files:\n${lines.join("\n")}`;
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
/**
|
|
665
|
+
* The prompt for the messages to answer, built from facts alone. A message's
|
|
666
|
+
* files follow its text as paths; `images` are the paths also given as image input.
|
|
667
|
+
*/
|
|
668
|
+
export function promptFor(pending: readonly Message[], images: ReadonlySet<string> = new Set()): string {
|
|
669
|
+
const parts = pending.map((message) =>
|
|
670
|
+
[message.text, attachmentLines(message, images)].filter((part) => part.length > 0).join("\n\n"),
|
|
671
|
+
);
|
|
672
|
+
return parts.join("\n\n");
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
/** One agent's choices for a new chat: what it lists, and what a chat starts with when none is asked for. */
|
|
676
|
+
export interface AgentChoices {
|
|
677
|
+
readonly name: string;
|
|
678
|
+
readonly models: { readonly list: readonly string[]; readonly default: string | null } | undefined;
|
|
679
|
+
readonly efforts: { readonly list: readonly string[]; readonly default: string | null } | undefined;
|
|
680
|
+
/** A configured model (a bot's); it is the default only for the agent that lists it. */
|
|
681
|
+
readonly preferredModel?: string | null | undefined;
|
|
682
|
+
/** A configured effort (a bot's); it is the default only for the agent that lists it. */
|
|
683
|
+
readonly preferredEffort?: string | null | undefined;
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
/**
|
|
687
|
+
* The conditionals of a new-chat form: one `if agent is X then model and effort
|
|
688
|
+
* are X's` per agent, in standard JSON Schema (`allOf` of `if`/`then`). The
|
|
689
|
+
* default is the configured value when the agent lists it, else the agent's
|
|
690
|
+
* default. An agent that lists none gets no property in its `then`: nothing can
|
|
691
|
+
* be picked for it. The kernel does not evaluate them; the action refuses a
|
|
692
|
+
* value the agent does not list by name when it runs.
|
|
693
|
+
*/
|
|
694
|
+
export function agentConditionals(agents: readonly AgentChoices[]): ActionArgSchema[] {
|
|
695
|
+
const pick = (
|
|
696
|
+
list: readonly string[],
|
|
697
|
+
preferred: string | null | undefined,
|
|
698
|
+
fallback: string | null | undefined,
|
|
699
|
+
): Record<string, unknown> => {
|
|
700
|
+
if (list.length === 0) return {};
|
|
701
|
+
const chosen = preferred !== null && preferred !== undefined && list.includes(preferred) ? preferred : fallback;
|
|
702
|
+
return { enum: [...list], ...(chosen === null || chosen === undefined ? {} : { default: chosen }) };
|
|
703
|
+
};
|
|
704
|
+
return agents.map((agent) => {
|
|
705
|
+
const model = pick(agent.models?.list ?? [], agent.preferredModel, agent.models?.default);
|
|
706
|
+
const effort = pick(agent.efforts?.list ?? [], agent.preferredEffort, agent.efforts?.default);
|
|
707
|
+
return {
|
|
708
|
+
if: { properties: { agent: { const: agent.name } }, required: ["agent"] },
|
|
709
|
+
then: {
|
|
710
|
+
properties: {
|
|
711
|
+
...(Object.keys(model).length === 0 ? {} : { model: { type: "string", ...model } }),
|
|
712
|
+
...(Object.keys(effort).length === 0 ? {} : { effort: { type: "string", ...effort } }),
|
|
713
|
+
},
|
|
714
|
+
},
|
|
715
|
+
} as ActionArgSchema;
|
|
716
|
+
});
|
|
717
|
+
}
|