@operad-io/chat 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +8 -3
- package/src/command.ts +198 -0
- package/src/index.ts +595 -66
- package/src/model.ts +791 -83
- package/src/notes.ts +194 -0
- package/src/queue.ts +93 -0
- package/src/reply.ts +1144 -122
- package/src/skills.ts +173 -0
- package/src/tail.ts +33 -8
- package/src/views.ts +1177 -90
package/src/model.ts
CHANGED
|
@@ -2,9 +2,21 @@
|
|
|
2
2
|
|
|
3
3
|
import { randomUUID } from "node:crypto";
|
|
4
4
|
import { statSync } from "node:fs";
|
|
5
|
-
import { basename, extname } from "node:path";
|
|
6
|
-
import type {
|
|
7
|
-
|
|
5
|
+
import { basename, extname, join } from "node:path";
|
|
6
|
+
import type {
|
|
7
|
+
ActionArgSchema,
|
|
8
|
+
AgentTimings,
|
|
9
|
+
CostQuality,
|
|
10
|
+
HarnessModels,
|
|
11
|
+
JsonValue,
|
|
12
|
+
ObjectRef,
|
|
13
|
+
ObjectStore,
|
|
14
|
+
PluginFact,
|
|
15
|
+
RunControl,
|
|
16
|
+
UsageTokens,
|
|
17
|
+
} from "@operad-io/engine";
|
|
18
|
+
import { isRecord, modelIds, safeFileName, storedType, stringList } from "@operad-io/engine";
|
|
19
|
+
import { isAccessLevel, type AccessLevel } from "@operad-io/access-match";
|
|
8
20
|
|
|
9
21
|
/** The object type of a chat. */
|
|
10
22
|
export const CHAT_TYPE = "chat";
|
|
@@ -18,11 +30,36 @@ export const ENTRY_FACT = "chat.entry";
|
|
|
18
30
|
/** 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
31
|
export const RUN_FACT = "chat.run";
|
|
20
32
|
|
|
33
|
+
/** The fact type of a run a `/stop` cancelled, so status and retry need not read the command's words. */
|
|
34
|
+
export const STOP_FACT = "chat.stop";
|
|
35
|
+
|
|
36
|
+
/** The fact type of messages an attempt took, when no reply message can name them. */
|
|
37
|
+
export const ANSWER_FACT = "chat.answered";
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The fact type of messages a run took: the messages of its first prompt, and
|
|
41
|
+
* each message an agent took while the run was going. A message in one is never
|
|
42
|
+
* queued again, even when the attempt fails and a later run answers it.
|
|
43
|
+
*/
|
|
44
|
+
export const TAKEN_FACT = "chat.taken";
|
|
45
|
+
|
|
46
|
+
/** The fact type of a change to a message that had not been taken: its text, or its withdrawal. */
|
|
47
|
+
export const MESSAGE_CHANGE_FACT = "chat.message_change";
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The fact type of an attempt that ended on its own. A recovered reply step
|
|
51
|
+
* reads it to tell a step that returned `interrupted` from one a crash left.
|
|
52
|
+
*/
|
|
53
|
+
export const ATTEMPT_END_FACT = "chat.attempt_end";
|
|
54
|
+
|
|
21
55
|
/** How a tool call ended. */
|
|
22
56
|
export type ToolResult = "done" | "failed" | "blocked" | "denied";
|
|
23
57
|
|
|
24
|
-
/** The kinds of part an answer is recorded as. */
|
|
25
|
-
export type EntryKind = "text" | "thinking" | "tool" | "stopped";
|
|
58
|
+
/** The kinds of part an answer is recorded as; `failure` is why a reply did not arrive. */
|
|
59
|
+
export type EntryKind = "text" | "thinking" | "tool" | "stopped" | "failure" | "worktree";
|
|
60
|
+
|
|
61
|
+
/** What the transcript says when a repository chat moves into its worktree. */
|
|
62
|
+
export const WORKTREE_NOTE = "This chat now works in a worktree.";
|
|
26
63
|
|
|
27
64
|
/** The event type a new message is: its source is `ios`, `telegram`, `cli`, `tui` or `other`. */
|
|
28
65
|
export const MESSAGE_EVENT = "message";
|
|
@@ -33,9 +70,46 @@ export const MODEL_FACT = "chat.model";
|
|
|
33
70
|
/** The fact type of a change of a chat's effort: who changed it, from what, to what. */
|
|
34
71
|
export const EFFORT_FACT = "chat.effort";
|
|
35
72
|
|
|
73
|
+
/** The fact type of a change of a chat's access level: who changed it, from what, to what. */
|
|
74
|
+
export const ACCESS_FACT = "chat.access";
|
|
75
|
+
|
|
76
|
+
/** What each level means, in the chat action's information and a question its change lifts. */
|
|
77
|
+
export const ACCESS_LEVEL_INFO: Readonly<Record<AccessLevel, { readonly title: string; readonly description: string }>> = {
|
|
78
|
+
plan: {
|
|
79
|
+
title: "Plan only",
|
|
80
|
+
description: "Read and run commands known to only read; a write asks.",
|
|
81
|
+
},
|
|
82
|
+
ask: {
|
|
83
|
+
title: "Ask each time",
|
|
84
|
+
description: "Every write and every command not known to only read asks.",
|
|
85
|
+
},
|
|
86
|
+
edits: {
|
|
87
|
+
title: "Accept edits",
|
|
88
|
+
description: "Write files in the working directory; a command not known to only read asks.",
|
|
89
|
+
},
|
|
90
|
+
full: {
|
|
91
|
+
title: "Full access",
|
|
92
|
+
description: "Skip every question; a deny still refuses and a read-only working directory still asks.",
|
|
93
|
+
},
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
/** The file a chat keeps its live level in, read again by a harness for each call. */
|
|
97
|
+
export function accessLevelPath(home: string, chat: string): string {
|
|
98
|
+
return join(home, "chat", safeFileName(chat), "access.json");
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* The field the access action puts on the in-memory chat while it runs the
|
|
103
|
+
* chat's `accessAction`; that action is out of every client list except then.
|
|
104
|
+
*/
|
|
105
|
+
export const ACCESS_ACTION_REQUEST = "accessActionRequest";
|
|
106
|
+
|
|
36
107
|
/** The fact type of a chat that was closed. */
|
|
37
108
|
export const CLOSED_FACT = "chat.closed";
|
|
38
109
|
|
|
110
|
+
/** The fact type of one command a person typed in a chat, and how it went. */
|
|
111
|
+
export const COMMAND_FACT = "chat.command";
|
|
112
|
+
|
|
39
113
|
/** The list filters of chats: closed ones are hidden unless asked for. */
|
|
40
114
|
export const CHAT_FILTERS = [
|
|
41
115
|
{ name: "open", default: true, states: ["open"] },
|
|
@@ -48,11 +122,31 @@ export const CHAT_SOURCES = ["ios", "telegram", "cli", "tui"] as const;
|
|
|
48
122
|
/** The event source of a message from a client the chat does not know by name. */
|
|
49
123
|
export const OTHER_SOURCE = "other";
|
|
50
124
|
|
|
51
|
-
export type ChatSource = (typeof CHAT_SOURCES)[number];
|
|
52
|
-
|
|
53
125
|
/** Who wrote a message: the person, or the assistant. */
|
|
54
126
|
export type MessageRole = "user" | "assistant";
|
|
55
127
|
|
|
128
|
+
/** The scheduled prompt that opened a chat: its bot and the entry's name. */
|
|
129
|
+
export interface ScheduledChat {
|
|
130
|
+
readonly [key: string]: string;
|
|
131
|
+
readonly bot: string;
|
|
132
|
+
readonly entry: string;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** The scheduled origin a stored chat names, if it has one. */
|
|
136
|
+
export function scheduledChatOf(value: unknown): ScheduledChat | undefined {
|
|
137
|
+
if (!isRecord(value)) return undefined;
|
|
138
|
+
if (typeof value.bot !== "string" || value.bot.length === 0) return undefined;
|
|
139
|
+
if (typeof value.entry !== "string" || value.entry.length === 0) return undefined;
|
|
140
|
+
return { bot: value.bot, entry: value.entry };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** The hashes of the notes a chat's session last saw, keyed by the note's name. */
|
|
144
|
+
export interface ChatNoteHashes {
|
|
145
|
+
/** The harness session the hashes belong to; absent for a session with no reference yet. */
|
|
146
|
+
readonly session?: string | undefined;
|
|
147
|
+
readonly files: Readonly<Record<string, string>>;
|
|
148
|
+
}
|
|
149
|
+
|
|
56
150
|
/** What a chat stores. The creating plugin gives every field but `session`. */
|
|
57
151
|
export interface ChatData {
|
|
58
152
|
readonly [key: string]: unknown;
|
|
@@ -64,12 +158,25 @@ export interface ChatData {
|
|
|
64
158
|
readonly cwd: string;
|
|
65
159
|
/** The access profile the harness applies; opaque here. */
|
|
66
160
|
readonly access: Readonly<Record<string, JsonValue>>;
|
|
161
|
+
/** The level the next reply uses: `plan`, `ask`, `edits` or `full`. */
|
|
162
|
+
readonly accessLevel?: AccessLevel | undefined;
|
|
163
|
+
/** The level this chat started at, so the row can tell a choice from the default. */
|
|
164
|
+
readonly accessDefault?: AccessLevel | undefined;
|
|
165
|
+
/**
|
|
166
|
+
* Whether a person chose the level with `chat:access`. A chat that did not
|
|
167
|
+
* choose follows its plugin's starting level when that changes.
|
|
168
|
+
*/
|
|
169
|
+
readonly accessChosen?: boolean | undefined;
|
|
67
170
|
readonly skills: readonly string[];
|
|
68
171
|
readonly title: string;
|
|
69
172
|
/** Whether the chat was closed; a closed chat takes no messages. */
|
|
70
173
|
readonly closed: boolean;
|
|
71
174
|
/** The harness's own reference to its conversation; never shown. */
|
|
72
175
|
readonly session?: string | null | undefined;
|
|
176
|
+
/** The working directory the session's starting text was built for; never shown. */
|
|
177
|
+
readonly contextCwd?: string | undefined;
|
|
178
|
+
/** The hashes of the notes this session last saw; never shown. */
|
|
179
|
+
readonly noteHashes?: ChatNoteHashes | undefined;
|
|
73
180
|
/** The channels (`telegram:<chat>`) whose messages land here. */
|
|
74
181
|
readonly channels: readonly string[];
|
|
75
182
|
/**
|
|
@@ -79,11 +186,17 @@ export interface ChatData {
|
|
|
79
186
|
* above are then what the chat started with.
|
|
80
187
|
*/
|
|
81
188
|
readonly refresh?: string | undefined;
|
|
189
|
+
/**
|
|
190
|
+
* An action (`<plugin>/<action>`) that prepares a change of the access level,
|
|
191
|
+
* such as opening a repository chat's worktree before it becomes writable;
|
|
192
|
+
* the access action runs it before it records the new level.
|
|
193
|
+
*/
|
|
194
|
+
readonly accessAction?: string | undefined;
|
|
82
195
|
/** The model the next reply uses; one the agent's plugin lists. Absent for an agent that lists none. */
|
|
83
196
|
readonly model?: string | undefined;
|
|
84
197
|
/** The effort the next reply uses; one the agent's plugin lists. Absent for an agent that lists none. */
|
|
85
198
|
readonly effort?: string | undefined;
|
|
86
|
-
/** The agent's default effort when this chat was made
|
|
199
|
+
/** The agent's default effort when this chat was made; a fallback only when the agent declares none now. */
|
|
87
200
|
readonly effortDefault?: string | undefined;
|
|
88
201
|
/** The model that gave the last reply, when its harness reported one. */
|
|
89
202
|
readonly lastModel?: string | undefined;
|
|
@@ -91,17 +204,24 @@ export interface ChatData {
|
|
|
91
204
|
readonly costMicros?: number | undefined;
|
|
92
205
|
/** How far to trust `costMicros`: the least exact of the replies counted. */
|
|
93
206
|
readonly costQuality?: CostQuality | undefined;
|
|
207
|
+
/** The tokens the replies used so far; absent while no reply reported any. */
|
|
208
|
+
readonly tokens?: UsageTokens | undefined;
|
|
209
|
+
/** True when some replies reported no tokens, so `tokens` is a partial total. */
|
|
210
|
+
readonly tokensIncomplete?: true | undefined;
|
|
211
|
+
/** The scheduled prompt that opened this chat; absent for every other chat. */
|
|
212
|
+
readonly scheduled?: ScheduledChat | undefined;
|
|
94
213
|
}
|
|
95
214
|
|
|
96
|
-
/** How far to trust a cost: the harness's own words. */
|
|
97
|
-
export type CostQuality = "exact" | "estimated" | "incomplete";
|
|
98
|
-
|
|
99
215
|
/** What a plugin gives to create a chat. */
|
|
100
216
|
export interface NewChat {
|
|
101
217
|
readonly parent?: string | undefined;
|
|
102
218
|
readonly harness: string;
|
|
103
219
|
readonly cwd: string;
|
|
104
220
|
readonly access?: Readonly<Record<string, JsonValue>> | undefined;
|
|
221
|
+
/** The level the chat starts at; when absent, `plan` for a read-only profile and `ask` otherwise. */
|
|
222
|
+
readonly accessLevel?: AccessLevel | undefined;
|
|
223
|
+
/** See {@link ChatData.accessDefault}. Defaults to the starting level. */
|
|
224
|
+
readonly accessDefault?: AccessLevel | undefined;
|
|
105
225
|
readonly skills?: readonly string[] | undefined;
|
|
106
226
|
readonly title: string;
|
|
107
227
|
readonly channels?: readonly string[] | undefined;
|
|
@@ -113,6 +233,10 @@ export interface NewChat {
|
|
|
113
233
|
readonly effortDefault?: string | undefined;
|
|
114
234
|
/** See {@link ChatData.refresh}. */
|
|
115
235
|
readonly refresh?: string | undefined;
|
|
236
|
+
/** See {@link ChatData.accessAction}. */
|
|
237
|
+
readonly accessAction?: string | undefined;
|
|
238
|
+
/** See {@link ChatData.scheduled}. */
|
|
239
|
+
readonly scheduled?: ScheduledChat | undefined;
|
|
116
240
|
}
|
|
117
241
|
|
|
118
242
|
/** One file attached to a message: where it is stored, and what a client shows of it. */
|
|
@@ -200,6 +324,14 @@ export interface EffortChangedData {
|
|
|
200
324
|
readonly to: string;
|
|
201
325
|
}
|
|
202
326
|
|
|
327
|
+
/** What an access-level change fact holds. */
|
|
328
|
+
export interface AccessChangedData {
|
|
329
|
+
readonly [key: string]: unknown;
|
|
330
|
+
readonly by: { readonly via: string; readonly id: string };
|
|
331
|
+
readonly from: AccessLevel;
|
|
332
|
+
readonly to: AccessLevel;
|
|
333
|
+
}
|
|
334
|
+
|
|
203
335
|
/**
|
|
204
336
|
* The effort a new chat starts with: the one asked for, else the preferred one
|
|
205
337
|
* (a bot's), else the agent's default. An effort the agent does not list is
|
|
@@ -224,6 +356,35 @@ export function startingEffort(
|
|
|
224
356
|
return efforts?.default ?? undefined;
|
|
225
357
|
}
|
|
226
358
|
|
|
359
|
+
/**
|
|
360
|
+
* The effort the chat itself chose, or undefined when it only inherits the
|
|
361
|
+
* agent's default. An effort equal to the one stored when the chat was made is
|
|
362
|
+
* inherited, so a harness whose default changed is followed.
|
|
363
|
+
*/
|
|
364
|
+
export function chosenEffort(
|
|
365
|
+
chat: Pick<ChatData, "effort" | "effortDefault">,
|
|
366
|
+
): string | undefined {
|
|
367
|
+
return chat.effort !== undefined && chat.effort !== chat.effortDefault
|
|
368
|
+
? chat.effort
|
|
369
|
+
: undefined;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/**
|
|
373
|
+
* The effort in force for a chat: its own choice, else the agent's live declared
|
|
374
|
+
* default, else the default stored when the chat was made. The stored default is
|
|
375
|
+
* only a fallback for an agent that declares none now, so a harness whose
|
|
376
|
+
* default changed is followed.
|
|
377
|
+
*/
|
|
378
|
+
export function effectiveEffort(
|
|
379
|
+
chat: Pick<ChatData, "effort" | "effortDefault">,
|
|
380
|
+
efforts: { readonly default: string | null } | undefined,
|
|
381
|
+
): string | undefined {
|
|
382
|
+
const chosen = chosenEffort(chat);
|
|
383
|
+
if (chosen !== undefined) return chosen;
|
|
384
|
+
const declared = efforts?.default;
|
|
385
|
+
return declared !== null && declared !== undefined ? declared : chat.effortDefault;
|
|
386
|
+
}
|
|
387
|
+
|
|
227
388
|
/**
|
|
228
389
|
* The model a new chat starts with: the one asked for, else the preferred one
|
|
229
390
|
* (a bot's), else the agent's default. A model the agent does not list is refused
|
|
@@ -231,11 +392,11 @@ export function startingEffort(
|
|
|
231
392
|
*/
|
|
232
393
|
export function startingModel(
|
|
233
394
|
harness: string,
|
|
234
|
-
models:
|
|
395
|
+
models: HarnessModels | undefined,
|
|
235
396
|
asked: string | undefined,
|
|
236
397
|
preferred?: string | undefined,
|
|
237
398
|
): string | undefined {
|
|
238
|
-
const list = models
|
|
399
|
+
const list = modelIds(models);
|
|
239
400
|
const wanted = asked ?? preferred;
|
|
240
401
|
if (wanted !== undefined) {
|
|
241
402
|
if (!list.includes(wanted)) {
|
|
@@ -270,6 +431,12 @@ export interface MessageData {
|
|
|
270
431
|
/** An assistant message: what it cost in millionths of a dollar, when reported. */
|
|
271
432
|
readonly costMicros?: number | undefined;
|
|
272
433
|
readonly costQuality?: CostQuality | undefined;
|
|
434
|
+
/** An assistant message: the tokens it used, when the harness reported them. */
|
|
435
|
+
readonly tokens?: UsageTokens | undefined;
|
|
436
|
+
/** An assistant message: the context it ended with, when the harness could tell. */
|
|
437
|
+
readonly context?: ReplyContext | undefined;
|
|
438
|
+
/** An assistant message: how long the step took to start, to its first line, and in all. */
|
|
439
|
+
readonly timings?: AgentTimings | undefined;
|
|
273
440
|
}
|
|
274
441
|
|
|
275
442
|
/** One message with when it was recorded. */
|
|
@@ -294,7 +461,11 @@ export interface EntryData {
|
|
|
294
461
|
/** What ran: the command, path or main argument, as the harness summarized it. */
|
|
295
462
|
readonly input?: string | null | undefined;
|
|
296
463
|
readonly result?: ToolResult | undefined;
|
|
297
|
-
/**
|
|
464
|
+
/**
|
|
465
|
+
* Epoch milliseconds: a tool call's start, or when the log received the line
|
|
466
|
+
* that finished a text or thinking part. Null for a tool call whose log had
|
|
467
|
+
* no start line; absent when the item carries no time, such as an old fact.
|
|
468
|
+
*/
|
|
298
469
|
readonly startedAt?: number | null | undefined;
|
|
299
470
|
readonly durationMs?: number | undefined;
|
|
300
471
|
/** The first 4 KB of what the call printed; null when it printed nothing. */
|
|
@@ -304,6 +475,12 @@ export interface EntryData {
|
|
|
304
475
|
readonly outputTruncated?: boolean | undefined;
|
|
305
476
|
/** The first line of the error, when the call failed. */
|
|
306
477
|
readonly error?: string | null | undefined;
|
|
478
|
+
/** On `failure`: why the reply failed (`empty`, `model_error`, ...). */
|
|
479
|
+
readonly reason?: string | undefined;
|
|
480
|
+
/** On `failure`: the oldest message the failed reply was for. */
|
|
481
|
+
readonly messageId?: string | undefined;
|
|
482
|
+
/** On `stopped`: the one line that says a crash or restart interrupted the reply. */
|
|
483
|
+
readonly interrupted?: boolean | undefined;
|
|
307
484
|
}
|
|
308
485
|
|
|
309
486
|
/** One entry with when its fact was recorded. */
|
|
@@ -312,30 +489,313 @@ export interface Entry extends EntryData {
|
|
|
312
489
|
readonly sequence: number;
|
|
313
490
|
}
|
|
314
491
|
|
|
492
|
+
/** What a stop fact holds: the reply run the command cancelled, and who stopped it. */
|
|
493
|
+
export interface StopData {
|
|
494
|
+
readonly [key: string]: unknown;
|
|
495
|
+
readonly runId: string;
|
|
496
|
+
readonly by: { readonly via: string; readonly id: string };
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
/** The stop a fact records, or undefined for another fact. */
|
|
500
|
+
export function stopOfFact(fact: PluginFact): StopData | undefined {
|
|
501
|
+
if (fact.type !== STOP_FACT) return undefined;
|
|
502
|
+
const data = fact.data;
|
|
503
|
+
if (typeof data.runId !== "string" || data.runId.length === 0) return undefined;
|
|
504
|
+
const from = isRecord(data.by) ? data.by : {};
|
|
505
|
+
return {
|
|
506
|
+
runId: data.runId,
|
|
507
|
+
by: {
|
|
508
|
+
via: typeof from.via === "string" ? from.via : "",
|
|
509
|
+
id: typeof from.id === "string" ? from.id : "",
|
|
510
|
+
},
|
|
511
|
+
};
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
/** The run a stop fact cancelled after a sequence, newest first, or undefined. */
|
|
515
|
+
export function stoppedRunAfter(
|
|
516
|
+
facts: readonly PluginFact[],
|
|
517
|
+
after: number,
|
|
518
|
+
): string | undefined {
|
|
519
|
+
let found: string | undefined;
|
|
520
|
+
for (const fact of facts) {
|
|
521
|
+
if (fact.sequence <= after) continue;
|
|
522
|
+
const stop = stopOfFact(fact);
|
|
523
|
+
if (stop !== undefined) found = stop.runId;
|
|
524
|
+
}
|
|
525
|
+
return found;
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
/** The ids a `chat.answered` fact records as taken by one run. */
|
|
529
|
+
export function answeredOfFact(fact: PluginFact): readonly string[] {
|
|
530
|
+
if (fact.type !== ANSWER_FACT || !Array.isArray(fact.data.ids)) return [];
|
|
531
|
+
return fact.data.ids.filter((id): id is string => typeof id === "string" && id.length > 0);
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
/** The ids a `chat.answered` or `chat.taken` fact records as taken by one run. */
|
|
535
|
+
export function takenOfFact(fact: PluginFact): readonly string[] {
|
|
536
|
+
if ((fact.type !== ANSWER_FACT && fact.type !== TAKEN_FACT) || !Array.isArray(fact.data.ids)) return [];
|
|
537
|
+
return fact.data.ids.filter((id): id is string => typeof id === "string" && id.length > 0);
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
/** Every message a run has taken: in its first prompt, handed over mid-run, or answered. */
|
|
541
|
+
export function takenIds(facts: readonly PluginFact[]): ReadonlySet<string> {
|
|
542
|
+
const taken = new Set<string>();
|
|
543
|
+
for (const fact of facts) {
|
|
544
|
+
for (const id of takenOfFact(fact)) taken.add(id);
|
|
545
|
+
if (fact.type === MESSAGE_FACT && fact.data.role === "assistant" && Array.isArray(fact.data.replyTo)) {
|
|
546
|
+
for (const id of fact.data.replyTo) {
|
|
547
|
+
if (typeof id === "string" && id.length > 0) taken.add(id);
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
return taken;
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
/** What a message change fact holds: who changed which message, and how. */
|
|
555
|
+
export interface MessageChangeData {
|
|
556
|
+
readonly [key: string]: unknown;
|
|
557
|
+
readonly id: string;
|
|
558
|
+
readonly kind: "text" | "withdraw";
|
|
559
|
+
readonly by: { readonly via: string; readonly id: string };
|
|
560
|
+
/** The new text, on a `text` change. */
|
|
561
|
+
readonly text?: string | undefined;
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
/** One message change with when its fact was recorded. */
|
|
565
|
+
export interface MessageChange extends MessageChangeData {
|
|
566
|
+
readonly at: number;
|
|
567
|
+
readonly sequence: number;
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
/** The change a fact records, or undefined for another fact. */
|
|
571
|
+
export function messageChangeOfFact(fact: PluginFact): MessageChange | undefined {
|
|
572
|
+
if (fact.type !== MESSAGE_CHANGE_FACT) return undefined;
|
|
573
|
+
const data = fact.data;
|
|
574
|
+
if (typeof data.id !== "string" || data.id.length === 0) return undefined;
|
|
575
|
+
if (data.kind !== "text" && data.kind !== "withdraw") return undefined;
|
|
576
|
+
if (data.kind === "text" && typeof data.text !== "string") return undefined;
|
|
577
|
+
const from = isRecord(data.by) ? data.by : {};
|
|
578
|
+
return {
|
|
579
|
+
id: data.id,
|
|
580
|
+
kind: data.kind,
|
|
581
|
+
by: {
|
|
582
|
+
via: typeof from.via === "string" ? from.via : "",
|
|
583
|
+
id: typeof from.id === "string" ? from.id : "",
|
|
584
|
+
},
|
|
585
|
+
...(typeof data.text === "string" ? { text: data.text } : {}),
|
|
586
|
+
at: fact.at,
|
|
587
|
+
sequence: fact.sequence,
|
|
588
|
+
};
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
/** The changes to each message, oldest first: its latest text and its withdrawal. */
|
|
592
|
+
export interface MessageChangeState {
|
|
593
|
+
readonly withdrawn?: MessageChange | undefined;
|
|
594
|
+
readonly text?: string | undefined;
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
export function messageChangesOf(facts: readonly PluginFact[]): ReadonlyMap<string, MessageChangeState> {
|
|
598
|
+
const changes = new Map<string, MessageChangeState>();
|
|
599
|
+
for (const fact of facts) {
|
|
600
|
+
const change = messageChangeOfFact(fact);
|
|
601
|
+
if (change === undefined) continue;
|
|
602
|
+
const before = changes.get(change.id) ?? {};
|
|
603
|
+
changes.set(
|
|
604
|
+
change.id,
|
|
605
|
+
change.kind === "withdraw"
|
|
606
|
+
? { ...before, withdrawn: change }
|
|
607
|
+
: { ...before, text: change.text },
|
|
608
|
+
);
|
|
609
|
+
}
|
|
610
|
+
return changes;
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
/** The messages with their latest text, without the ones a person withdrew. */
|
|
614
|
+
export function applyMessageChanges(
|
|
615
|
+
messages: readonly Message[],
|
|
616
|
+
changes: ReadonlyMap<string, MessageChangeState>,
|
|
617
|
+
): readonly Message[] {
|
|
618
|
+
const found: Message[] = [];
|
|
619
|
+
for (const message of messages) {
|
|
620
|
+
const change = changes.get(message.id);
|
|
621
|
+
if (change?.withdrawn !== undefined) continue;
|
|
622
|
+
found.push(change?.text === undefined ? message : { ...message, text: change.text });
|
|
623
|
+
}
|
|
624
|
+
return found;
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
/** The message facts with their latest text, without the messages a person withdrew. */
|
|
628
|
+
export function messageFactsInForce(
|
|
629
|
+
facts: readonly PluginFact[],
|
|
630
|
+
changes: ReadonlyMap<string, MessageChangeState> = messageChangesOf(facts),
|
|
631
|
+
): readonly PluginFact[] {
|
|
632
|
+
const found: PluginFact[] = [];
|
|
633
|
+
for (const fact of facts) {
|
|
634
|
+
if (fact.type !== MESSAGE_FACT || fact.data.role !== "user") {
|
|
635
|
+
found.push(fact);
|
|
636
|
+
continue;
|
|
637
|
+
}
|
|
638
|
+
const id = typeof fact.data.id === "string" ? fact.data.id : undefined;
|
|
639
|
+
const change = id === undefined ? undefined : changes.get(id);
|
|
640
|
+
if (change?.withdrawn !== undefined) continue;
|
|
641
|
+
found.push(
|
|
642
|
+
change?.text === undefined ? fact : { ...fact, data: { ...fact.data, text: change.text } },
|
|
643
|
+
);
|
|
644
|
+
}
|
|
645
|
+
return found;
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
/** A queued message, in the shape a chat's row and section carry. */
|
|
649
|
+
export interface QueuedMessage {
|
|
650
|
+
readonly id: string;
|
|
651
|
+
readonly text: string;
|
|
652
|
+
readonly at: number;
|
|
653
|
+
readonly attachments: readonly Attachment[];
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
/** The queued messages a chat shows a client, oldest first. */
|
|
657
|
+
export function queuedMessages(
|
|
658
|
+
messages: readonly Message[],
|
|
659
|
+
facts: readonly PluginFact[],
|
|
660
|
+
): readonly Message[] {
|
|
661
|
+
const taken = takenIds(facts);
|
|
662
|
+
return unanswered(messages, facts).filter((message) => !taken.has(message.id));
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
/** The queued messages as a client reads them. */
|
|
666
|
+
export function queuedData(messages: readonly Message[]): readonly QueuedMessage[] {
|
|
667
|
+
return messages.map((message) => ({
|
|
668
|
+
id: message.id,
|
|
669
|
+
text: message.text,
|
|
670
|
+
at: message.at,
|
|
671
|
+
attachments: message.attachments,
|
|
672
|
+
}));
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
/** The queued messages a stored chat object carries, when it has them. */
|
|
676
|
+
export function queuedOf(value: unknown): readonly QueuedMessage[] {
|
|
677
|
+
if (!Array.isArray(value)) return [];
|
|
678
|
+
const found: QueuedMessage[] = [];
|
|
679
|
+
for (const item of value) {
|
|
680
|
+
if (!isRecord(item)) continue;
|
|
681
|
+
if (typeof item.id !== "string" || item.id.length === 0) continue;
|
|
682
|
+
if (typeof item.text !== "string") continue;
|
|
683
|
+
const at = item.at;
|
|
684
|
+
if (typeof at !== "number" || !Number.isFinite(at)) continue;
|
|
685
|
+
found.push({ id: item.id, text: item.text, at, attachments: attachmentsOf(item.attachments) });
|
|
686
|
+
}
|
|
687
|
+
return found;
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
/** The run an attempt fact says ended on its own, or undefined for another fact. */
|
|
691
|
+
export function attemptEndedOfFact(fact: PluginFact): string | undefined {
|
|
692
|
+
if (fact.type !== ATTEMPT_END_FACT) return undefined;
|
|
693
|
+
return typeof fact.data.runId === "string" && fact.data.runId.length > 0
|
|
694
|
+
? fact.data.runId
|
|
695
|
+
: undefined;
|
|
696
|
+
}
|
|
697
|
+
|
|
315
698
|
/** What a close fact holds: who closed the chat. */
|
|
316
699
|
export interface ClosedData {
|
|
317
700
|
readonly [key: string]: unknown;
|
|
318
701
|
readonly by: { readonly via: string; readonly id: string };
|
|
319
702
|
}
|
|
320
703
|
|
|
321
|
-
/**
|
|
704
|
+
/** What a command fact holds: who typed it, the command and how it went. */
|
|
705
|
+
export interface CommandData {
|
|
706
|
+
readonly [key: string]: unknown;
|
|
707
|
+
readonly from: { readonly via: string; readonly id: string };
|
|
708
|
+
/** The command as typed, starting with `/`. */
|
|
709
|
+
readonly command: string;
|
|
710
|
+
/** What happened, or why it was refused. */
|
|
711
|
+
readonly outcome: string;
|
|
712
|
+
readonly ok: boolean;
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
/** One command with when its fact was recorded. */
|
|
716
|
+
export interface Command extends CommandData {
|
|
717
|
+
readonly at: number;
|
|
718
|
+
readonly sequence: number;
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
/** The command a fact records, or undefined for another fact. */
|
|
722
|
+
export function commandOfFact(fact: PluginFact): Command | undefined {
|
|
723
|
+
if (fact.type !== COMMAND_FACT) return undefined;
|
|
724
|
+
const data = fact.data;
|
|
725
|
+
if (
|
|
726
|
+
typeof data.command !== "string" ||
|
|
727
|
+
typeof data.outcome !== "string" ||
|
|
728
|
+
typeof data.ok !== "boolean"
|
|
729
|
+
) {
|
|
730
|
+
return undefined;
|
|
731
|
+
}
|
|
732
|
+
const from = isRecord(data.from) ? data.from : {};
|
|
733
|
+
return {
|
|
734
|
+
from: {
|
|
735
|
+
via: typeof from.via === "string" ? from.via : "",
|
|
736
|
+
id: typeof from.id === "string" ? from.id : "",
|
|
737
|
+
},
|
|
738
|
+
command: data.command,
|
|
739
|
+
outcome: data.outcome,
|
|
740
|
+
ok: data.ok,
|
|
741
|
+
at: fact.at,
|
|
742
|
+
sequence: fact.sequence,
|
|
743
|
+
};
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
/** The level a chat falls back to when it has none: a read-only profile starts at plan, any other at ask. */
|
|
747
|
+
function fallbackAccessLevel(data: Readonly<Record<string, unknown>>): AccessLevel {
|
|
748
|
+
return isRecord(data.access) && data.access.readOnly === true ? "plan" : "ask";
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
function noteHashesOf(value: unknown): ChatNoteHashes | undefined {
|
|
752
|
+
if (!isRecord(value) || !isRecord(value.files)) return undefined;
|
|
753
|
+
const files: Record<string, string> = {};
|
|
754
|
+
for (const [name, hash] of Object.entries(value.files)) {
|
|
755
|
+
if (name.length > 0 && typeof hash === "string" && hash.length > 0) files[name] = hash;
|
|
756
|
+
}
|
|
757
|
+
return {
|
|
758
|
+
...(typeof value.session === "string" && value.session.length > 0 ? { session: value.session } : {}),
|
|
759
|
+
files,
|
|
760
|
+
};
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
/** The chat fields of a stored object, with the lists and the access level defaulted. */
|
|
322
764
|
export function chatData(data: Readonly<Record<string, unknown>>): ChatData {
|
|
765
|
+
const tokens = usageTokensOf(data.tokens);
|
|
766
|
+
const scheduled = scheduledChatOf(data.scheduled);
|
|
767
|
+
const noteHashes = noteHashesOf(data.noteHashes);
|
|
768
|
+
const accessDefault = isAccessLevel(data.accessDefault)
|
|
769
|
+
? data.accessDefault
|
|
770
|
+
: fallbackAccessLevel(data);
|
|
771
|
+
const accessLevel = isAccessLevel(data.accessLevel) ? data.accessLevel : accessDefault;
|
|
772
|
+
// A chat stored before the flag existed chose a level when it differs from its starting one.
|
|
773
|
+
const accessChosen = data.accessChosen === true || accessLevel !== accessDefault;
|
|
323
774
|
return {
|
|
324
775
|
...data,
|
|
325
776
|
harness: typeof data.harness === "string" ? data.harness : "",
|
|
326
777
|
cwd: typeof data.cwd === "string" ? data.cwd : "",
|
|
327
778
|
access: isRecord(data.access) ? (data.access as Record<string, JsonValue>) : {},
|
|
779
|
+
accessLevel,
|
|
780
|
+
accessDefault,
|
|
781
|
+
accessChosen,
|
|
328
782
|
skills: stringList(data.skills),
|
|
329
783
|
title: typeof data.title === "string" ? data.title : "",
|
|
330
784
|
closed: data.closed === true,
|
|
331
785
|
channels: stringList(data.channels),
|
|
332
786
|
...(typeof data.refresh === "string" && data.refresh.length > 0 ? { refresh: data.refresh } : {}),
|
|
787
|
+
...(typeof data.accessAction === "string" && data.accessAction.length > 0 ? { accessAction: data.accessAction } : {}),
|
|
788
|
+
...(typeof data.contextCwd === "string" && data.contextCwd.length > 0 ? { contextCwd: data.contextCwd } : {}),
|
|
789
|
+
...(noteHashes === undefined ? {} : { noteHashes }),
|
|
333
790
|
...(typeof data.model === "string" && data.model.length > 0 ? { model: data.model } : {}),
|
|
334
791
|
...(typeof data.effort === "string" && data.effort.length > 0 ? { effort: data.effort } : {}),
|
|
335
792
|
...(typeof data.effortDefault === "string" && data.effortDefault.length > 0 ? { effortDefault: data.effortDefault } : {}),
|
|
336
793
|
...(typeof data.lastModel === "string" && data.lastModel.length > 0 ? { lastModel: data.lastModel } : {}),
|
|
337
794
|
...(typeof data.costMicros === "number" && Number.isFinite(data.costMicros) ? { costMicros: data.costMicros } : {}),
|
|
338
795
|
...(isCostQuality(data.costQuality) ? { costQuality: data.costQuality } : {}),
|
|
796
|
+
...(tokens === undefined ? {} : { tokens }),
|
|
797
|
+
...(data.tokensIncomplete === true ? { tokensIncomplete: true as const } : {}),
|
|
798
|
+
...(scheduled === undefined ? {} : { scheduled }),
|
|
339
799
|
};
|
|
340
800
|
}
|
|
341
801
|
|
|
@@ -364,31 +824,91 @@ export function modelAndCost(
|
|
|
364
824
|
/** What a chat uses, for its row and its page: `claude · sonnet · high · $0.12`. */
|
|
365
825
|
export function agentLine(chat: ChatData): string {
|
|
366
826
|
const model = chat.model ?? chat.lastModel;
|
|
367
|
-
|
|
368
|
-
|
|
827
|
+
// A row reads only the stored chat, so it shows the effort the chat itself
|
|
828
|
+
// chose; the agent's live default is not a choice and may have changed since.
|
|
829
|
+
const effort = chosenEffort(chat);
|
|
369
830
|
return [
|
|
370
831
|
chat.harness,
|
|
371
832
|
...(model === undefined || model.length === 0 ? [] : [model]),
|
|
372
|
-
...effort,
|
|
833
|
+
...(effort === undefined ? [] : [effort]),
|
|
373
834
|
...(chat.costMicros === undefined ? [] : [costText(chat.costMicros, chat.costQuality)]),
|
|
374
835
|
]
|
|
375
836
|
.filter((part) => part.length > 0)
|
|
376
837
|
.join(" · ");
|
|
377
838
|
}
|
|
378
839
|
|
|
379
|
-
/** The
|
|
840
|
+
/** The four token counts of a usage, when all are known and at least one is not zero. */
|
|
841
|
+
function usageTokensOf(value: unknown): UsageTokens | undefined {
|
|
842
|
+
if (!isRecord(value)) return undefined;
|
|
843
|
+
const count = (key: string): number | undefined => {
|
|
844
|
+
const found = value[key];
|
|
845
|
+
return typeof found === "number" && Number.isInteger(found) && found >= 0 ? found : undefined;
|
|
846
|
+
};
|
|
847
|
+
const input = count("input");
|
|
848
|
+
const output = count("output");
|
|
849
|
+
const cacheread = count("cacheread");
|
|
850
|
+
const cachewrite = count("cachewrite");
|
|
851
|
+
if (input === undefined || output === undefined || cacheread === undefined || cachewrite === undefined) {
|
|
852
|
+
return undefined;
|
|
853
|
+
}
|
|
854
|
+
// A harness that reports no token counts gives all four as zero.
|
|
855
|
+
if (input === 0 && output === 0 && cacheread === 0 && cachewrite === 0) return undefined;
|
|
856
|
+
return { input, output, cacheread, cachewrite };
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
/** What a reply records about the context it ended with. */
|
|
860
|
+
export interface ReplyContext {
|
|
861
|
+
readonly used: number;
|
|
862
|
+
readonly window?: number | undefined;
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
/** What a chat's view says about its context: the last reply's numbers and model. */
|
|
866
|
+
export interface ChatContext extends ReplyContext {
|
|
867
|
+
readonly model?: string | undefined;
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
/** The context numbers a harness or a stored reply reports, when they are whole. */
|
|
871
|
+
export function replyContextOf(value: unknown): ReplyContext | undefined {
|
|
872
|
+
if (!isRecord(value)) return undefined;
|
|
873
|
+
const used = value.used;
|
|
874
|
+
if (typeof used !== "number" || !Number.isInteger(used) || used < 0) return undefined;
|
|
875
|
+
const window = value.window;
|
|
876
|
+
const known = typeof window === "number" && Number.isInteger(window) && window > 0 ? window : undefined;
|
|
877
|
+
return { used, ...(known === undefined ? {} : { window: known }) };
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
/** The model, tokens, cost and quality a harness's `usage` reports; each only when it did. */
|
|
380
881
|
export function usageOf(value: unknown): {
|
|
381
882
|
readonly model?: string;
|
|
382
883
|
readonly costMicros?: number;
|
|
383
884
|
readonly costQuality?: CostQuality;
|
|
885
|
+
readonly tokens?: UsageTokens;
|
|
384
886
|
} {
|
|
385
887
|
if (!isRecord(value)) return {};
|
|
386
888
|
const micros = value.costMicros;
|
|
387
889
|
const known = typeof micros === "number" && Number.isFinite(micros);
|
|
890
|
+
const tokens = usageTokensOf(value.tokens);
|
|
388
891
|
return {
|
|
389
892
|
...(typeof value.model === "string" && value.model.length > 0 ? { model: value.model } : {}),
|
|
390
893
|
...(known ? { costMicros: micros } : {}),
|
|
391
894
|
...(known ? { costQuality: isCostQuality(value.costQuality) ? value.costQuality : "estimated" } : {}),
|
|
895
|
+
...(tokens === undefined ? {} : { tokens }),
|
|
896
|
+
};
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
/** The timings a harness's step data reports; undefined when it has none or not a whole one. */
|
|
900
|
+
export function timingsOf(value: unknown): AgentTimings | undefined {
|
|
901
|
+
if (!isRecord(value)) return undefined;
|
|
902
|
+
const total = value.totalMs;
|
|
903
|
+
if (typeof total !== "number" || !Number.isFinite(total)) return undefined;
|
|
904
|
+
const duration = (key: string): number | null => {
|
|
905
|
+
const at = value[key];
|
|
906
|
+
return typeof at === "number" && Number.isFinite(at) ? at : null;
|
|
907
|
+
};
|
|
908
|
+
return {
|
|
909
|
+
startToReadyMs: duration("startToReadyMs"),
|
|
910
|
+
readyToFirstMs: duration("readyToFirstMs"),
|
|
911
|
+
totalMs: total,
|
|
392
912
|
};
|
|
393
913
|
}
|
|
394
914
|
|
|
@@ -454,11 +974,18 @@ export async function createChat(
|
|
|
454
974
|
if (input.harness.trim().length === 0) throw new Error("a chat needs an agent");
|
|
455
975
|
if (input.cwd.trim().length === 0) throw new Error("a chat needs a working directory");
|
|
456
976
|
if (input.title.trim().length === 0) throw new Error("a chat needs a title");
|
|
977
|
+
const accessLevel =
|
|
978
|
+
input.accessLevel ??
|
|
979
|
+
input.accessDefault ??
|
|
980
|
+
(input.access?.readOnly === true ? "plan" : "ask");
|
|
981
|
+
const accessDefault = input.accessDefault ?? accessLevel;
|
|
457
982
|
const data: ChatData = {
|
|
458
983
|
...(input.parent === undefined ? {} : { parent: input.parent }),
|
|
459
984
|
harness: input.harness,
|
|
460
985
|
cwd: input.cwd,
|
|
461
986
|
access: input.access ?? {},
|
|
987
|
+
accessLevel,
|
|
988
|
+
accessDefault,
|
|
462
989
|
skills: input.skills ?? [],
|
|
463
990
|
title: input.title.trim(),
|
|
464
991
|
closed: false,
|
|
@@ -466,8 +993,10 @@ export async function createChat(
|
|
|
466
993
|
channels: input.channels ?? [],
|
|
467
994
|
...(input.model === undefined ? {} : { model: input.model }),
|
|
468
995
|
...(input.effort === undefined ? {} : { effort: input.effort }),
|
|
469
|
-
...(input.
|
|
996
|
+
...(input.effortDefault === undefined ? {} : { effortDefault: input.effortDefault }),
|
|
470
997
|
...(input.refresh === undefined ? {} : { refresh: input.refresh }),
|
|
998
|
+
...(input.accessAction === undefined ? {} : { accessAction: input.accessAction }),
|
|
999
|
+
...(input.scheduled === undefined ? {} : { scheduled: input.scheduled }),
|
|
471
1000
|
};
|
|
472
1001
|
// The id counts up; a taken one (two chats made at once) moves on to the next.
|
|
473
1002
|
for (let attempt = 0; attempt < 20; attempt += 1) {
|
|
@@ -487,6 +1016,9 @@ function messageOfFact(fact: PluginFact): Message | undefined {
|
|
|
487
1016
|
if (data.role !== "user" && data.role !== "assistant") return undefined;
|
|
488
1017
|
const from = isRecord(data.from) ? data.from : {};
|
|
489
1018
|
const source = isRecord(data.source) ? data.source : {};
|
|
1019
|
+
const timings = timingsOf(data.timings);
|
|
1020
|
+
const tokens = usageTokensOf(data.tokens);
|
|
1021
|
+
const context = replyContextOf(data.context);
|
|
490
1022
|
return {
|
|
491
1023
|
id: data.id,
|
|
492
1024
|
role: data.role,
|
|
@@ -506,6 +1038,9 @@ function messageOfFact(fact: PluginFact): Message | undefined {
|
|
|
506
1038
|
...(typeof data.model === "string" && data.model.length > 0 ? { model: data.model } : {}),
|
|
507
1039
|
...(typeof data.costMicros === "number" && Number.isFinite(data.costMicros) ? { costMicros: data.costMicros } : {}),
|
|
508
1040
|
...(isCostQuality(data.costQuality) ? { costQuality: data.costQuality } : {}),
|
|
1041
|
+
...(tokens === undefined ? {} : { tokens }),
|
|
1042
|
+
...(context === undefined ? {} : { context }),
|
|
1043
|
+
...(timings === undefined ? {} : { timings }),
|
|
509
1044
|
at: fact.at,
|
|
510
1045
|
sequence: fact.sequence,
|
|
511
1046
|
};
|
|
@@ -520,20 +1055,28 @@ export function entryOfFact(fact: PluginFact): Entry | undefined {
|
|
|
520
1055
|
const data = fact.data;
|
|
521
1056
|
if (typeof data.runId !== "string" || data.runId.length === 0) return undefined;
|
|
522
1057
|
const kind = data.kind;
|
|
523
|
-
if (kind !== "text" && kind !== "thinking" && kind !== "tool" && kind !== "stopped") return undefined;
|
|
1058
|
+
if (kind !== "text" && kind !== "thinking" && kind !== "tool" && kind !== "stopped" && kind !== "failure" && kind !== "worktree") return undefined;
|
|
524
1059
|
const entryKind: EntryKind = kind;
|
|
525
|
-
const base = {
|
|
1060
|
+
const base = {
|
|
1061
|
+
runId: data.runId,
|
|
1062
|
+
kind: entryKind,
|
|
1063
|
+
at: fact.at,
|
|
1064
|
+
sequence: fact.sequence,
|
|
1065
|
+
...(typeof data.startedAt === "number" || data.startedAt === null ? { startedAt: data.startedAt } : {}),
|
|
1066
|
+
...(typeof data.reason === "string" ? { reason: data.reason } : {}),
|
|
1067
|
+
...(typeof data.messageId === "string" ? { messageId: data.messageId } : {}),
|
|
1068
|
+
...(data.interrupted === true ? { interrupted: true } : {}),
|
|
1069
|
+
};
|
|
526
1070
|
if (entryKind === "tool") {
|
|
527
|
-
if (
|
|
528
|
-
return undefined;
|
|
529
|
-
}
|
|
1071
|
+
if (!isToolResult(data.result)) return undefined;
|
|
530
1072
|
return {
|
|
531
1073
|
...base,
|
|
532
|
-
|
|
533
|
-
|
|
1074
|
+
// An older or partly written entry may have no id or name; it still ran,
|
|
1075
|
+
// so it is shown as a tool rather than dropped from the transcript.
|
|
1076
|
+
callId: typeof data.callId === "string" ? data.callId : "",
|
|
1077
|
+
toolName: typeof data.toolName === "string" && data.toolName.length > 0 ? data.toolName : "tool",
|
|
534
1078
|
...(typeof data.input === "string" || data.input === null ? { input: data.input } : {}),
|
|
535
1079
|
result: data.result,
|
|
536
|
-
...(typeof data.startedAt === "number" || data.startedAt === null ? { startedAt: data.startedAt } : {}),
|
|
537
1080
|
...(typeof data.durationMs === "number" && Number.isFinite(data.durationMs) ? { durationMs: data.durationMs } : {}),
|
|
538
1081
|
...(typeof data.output === "string" || data.output === null ? { output: data.output } : {}),
|
|
539
1082
|
...(typeof data.outputPath === "string" ? { outputPath: data.outputPath } : {}),
|
|
@@ -544,73 +1087,78 @@ export function entryOfFact(fact: PluginFact): Entry | undefined {
|
|
|
544
1087
|
return typeof data.text === "string" ? { ...base, text: data.text } : undefined;
|
|
545
1088
|
}
|
|
546
1089
|
|
|
547
|
-
/**
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
chat: string,
|
|
551
|
-
cursor: string | undefined,
|
|
552
|
-
limit: number,
|
|
553
|
-
): { readonly messages: readonly Message[]; readonly next: string | undefined } {
|
|
1090
|
+
/** The messages among a chat's facts, with a person's changed text and withdrawal. */
|
|
1091
|
+
function messagesOfFacts(facts: readonly PluginFact[]): readonly Message[] {
|
|
1092
|
+
const changes = messageChangesOf(facts);
|
|
554
1093
|
const messages: Message[] = [];
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
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 };
|
|
1094
|
+
for (const fact of facts) {
|
|
1095
|
+
const message = messageOfFact(fact);
|
|
1096
|
+
if (message === undefined) continue;
|
|
1097
|
+
if (message.role !== "user") {
|
|
1098
|
+
messages.push(message);
|
|
1099
|
+
continue;
|
|
567
1100
|
}
|
|
568
|
-
|
|
1101
|
+
const change = changes.get(message.id);
|
|
1102
|
+
if (change?.withdrawn !== undefined) continue;
|
|
1103
|
+
messages.push(change?.text === undefined ? message : { ...message, text: change.text });
|
|
569
1104
|
}
|
|
1105
|
+
return messages;
|
|
570
1106
|
}
|
|
571
1107
|
|
|
572
|
-
/**
|
|
573
|
-
|
|
574
|
-
const found:
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
cursor = page.next;
|
|
580
|
-
} while (cursor !== undefined);
|
|
1108
|
+
/** The entries among a chat's facts. */
|
|
1109
|
+
function entriesOfFacts(facts: readonly PluginFact[]): readonly Entry[] {
|
|
1110
|
+
const found: Entry[] = [];
|
|
1111
|
+
for (const fact of facts) {
|
|
1112
|
+
const entry = entryOfFact(fact);
|
|
1113
|
+
if (entry !== undefined) found.push(entry);
|
|
1114
|
+
}
|
|
581
1115
|
return found;
|
|
582
1116
|
}
|
|
583
1117
|
|
|
1118
|
+
/** Every message of a chat in force, oldest first: changed text, and no withdrawn message. */
|
|
1119
|
+
export function allMessages(store: ObjectStore, chat: string): readonly Message[] {
|
|
1120
|
+
return messagesOfFacts(chatFacts(store, chat));
|
|
1121
|
+
}
|
|
1122
|
+
|
|
584
1123
|
/** Every entry of a chat, oldest first. */
|
|
585
1124
|
export function allEntries(store: ObjectStore, chat: string): readonly Entry[] {
|
|
586
|
-
|
|
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;
|
|
1125
|
+
return entriesOfFacts(chatFacts(store, chat));
|
|
600
1126
|
}
|
|
601
1127
|
|
|
602
|
-
/** Every fact of
|
|
603
|
-
export function
|
|
1128
|
+
/** Every fact of one object, oldest first. */
|
|
1129
|
+
export function factsOf(store: ObjectStore, ref: ObjectRef): readonly PluginFact[] {
|
|
604
1130
|
const facts: PluginFact[] = [];
|
|
605
1131
|
let cursor: string | undefined;
|
|
606
1132
|
do {
|
|
607
|
-
const page = store.facts(
|
|
1133
|
+
const page = store.facts(ref, { ...(cursor === undefined ? {} : { cursor }), limit: 500 });
|
|
608
1134
|
facts.push(...page.facts);
|
|
609
1135
|
cursor = page.next;
|
|
610
1136
|
} while (cursor !== undefined);
|
|
611
1137
|
return facts;
|
|
612
1138
|
}
|
|
613
1139
|
|
|
1140
|
+
/** Every fact of a chat, oldest first. */
|
|
1141
|
+
export function chatFacts(store: ObjectStore, chat: string): readonly PluginFact[] {
|
|
1142
|
+
return factsOf(store, chatRef(chat));
|
|
1143
|
+
}
|
|
1144
|
+
|
|
1145
|
+
/** Everything a reader needs from a chat's facts, from one scan. */
|
|
1146
|
+
export interface ChatRead {
|
|
1147
|
+
readonly facts: readonly PluginFact[];
|
|
1148
|
+
readonly messages: readonly Message[];
|
|
1149
|
+
readonly entries: readonly Entry[];
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1152
|
+
/** Reads a chat's facts once and derives its messages and entries from them. */
|
|
1153
|
+
export function readChat(store: ObjectStore, chat: string): ChatRead {
|
|
1154
|
+
const facts = chatFacts(store, chat);
|
|
1155
|
+
return {
|
|
1156
|
+
facts,
|
|
1157
|
+
messages: messagesOfFacts(facts),
|
|
1158
|
+
entries: entriesOfFacts(facts),
|
|
1159
|
+
};
|
|
1160
|
+
}
|
|
1161
|
+
|
|
614
1162
|
/** The run id of the latest reply run recorded on a chat, if any. */
|
|
615
1163
|
export function latestRunOf(facts: readonly PluginFact[]): string | undefined {
|
|
616
1164
|
let found: string | undefined;
|
|
@@ -622,15 +1170,135 @@ export function latestRunOf(facts: readonly PluginFact[]): string | undefined {
|
|
|
622
1170
|
return found;
|
|
623
1171
|
}
|
|
624
1172
|
|
|
625
|
-
/**
|
|
626
|
-
export
|
|
1173
|
+
/** A reply run that is being written: its run id and when it began. */
|
|
1174
|
+
export interface WritingReply {
|
|
1175
|
+
readonly runId: string;
|
|
1176
|
+
readonly since: number;
|
|
1177
|
+
}
|
|
1178
|
+
|
|
1179
|
+
/**
|
|
1180
|
+
* The reply being written, if one is. The latest `chat.run` fact starts an
|
|
1181
|
+
* attempt; a failure entry, a stopped half reply or a successful `/stop` for
|
|
1182
|
+
* that run ends it. A reply for that run with no messages still unanswered also
|
|
1183
|
+
* ends it; with messages unanswered the flow is going round again. The answer
|
|
1184
|
+
* reads the chat's facts, so it works while the reply runs and costs no tokens.
|
|
1185
|
+
*/
|
|
1186
|
+
export function writingReply(
|
|
1187
|
+
facts: readonly PluginFact[],
|
|
1188
|
+
messages: readonly Message[],
|
|
1189
|
+
entries: readonly Entry[],
|
|
1190
|
+
): WritingReply | undefined {
|
|
1191
|
+
let runId: string | undefined;
|
|
1192
|
+
let since: number | undefined;
|
|
1193
|
+
let started = -1;
|
|
1194
|
+
for (const fact of facts) {
|
|
1195
|
+
if (fact.type === RUN_FACT && typeof fact.data.runId === "string" && fact.data.runId.length > 0) {
|
|
1196
|
+
runId = fact.data.runId;
|
|
1197
|
+
since = fact.at;
|
|
1198
|
+
started = fact.sequence;
|
|
1199
|
+
}
|
|
1200
|
+
}
|
|
1201
|
+
if (runId === undefined || since === undefined) return undefined;
|
|
1202
|
+
const ended = entries.some(
|
|
1203
|
+
(entry) => (entry.kind === "failure" || entry.kind === "stopped") && entry.runId === runId,
|
|
1204
|
+
);
|
|
1205
|
+
const stopped = facts.some((fact) => {
|
|
1206
|
+
if (fact.sequence <= started) return false;
|
|
1207
|
+
return stopOfFact(fact)?.runId === runId;
|
|
1208
|
+
});
|
|
1209
|
+
if (ended || stopped) return undefined;
|
|
1210
|
+
const replied = messages.some((message) => message.role === "assistant" && message.runId === runId);
|
|
1211
|
+
// The flow goes round again while messages arrived during the reply: a reply
|
|
1212
|
+
// for this run with messages still unanswered is the next round, not an end.
|
|
1213
|
+
if (!replied || unanswered(messages, facts).length > 0) return { runId, since };
|
|
1214
|
+
return undefined;
|
|
1215
|
+
}
|
|
1216
|
+
|
|
1217
|
+
/**
|
|
1218
|
+
* The reply being written now: as {@link writingReply}, unless the host says the
|
|
1219
|
+
* latest run has ended. A host that cannot tell leaves the fact-only answer as
|
|
1220
|
+
* it was.
|
|
1221
|
+
*/
|
|
1222
|
+
export async function writingReplyNow(
|
|
1223
|
+
facts: readonly PluginFact[],
|
|
1224
|
+
messages: readonly Message[],
|
|
1225
|
+
entries: readonly Entry[],
|
|
1226
|
+
runs?: Pick<RunControl, "active"> | undefined,
|
|
1227
|
+
): Promise<WritingReply | undefined> {
|
|
1228
|
+
const writing = writingReply(facts, messages, entries);
|
|
1229
|
+
if (writing === undefined || runs === undefined) return writing;
|
|
1230
|
+
const active = await runs.active(writing.runId);
|
|
1231
|
+
return active === false ? undefined : writing;
|
|
1232
|
+
}
|
|
1233
|
+
|
|
1234
|
+
/** The time from a reply's start to its first output, when its timings hold both parts. */
|
|
1235
|
+
export function firstOutputMs(timings: AgentTimings | undefined): number | undefined {
|
|
1236
|
+
if (timings === undefined || timings.startToReadyMs === null || timings.readyToFirstMs === null) {
|
|
1237
|
+
return undefined;
|
|
1238
|
+
}
|
|
1239
|
+
return timings.startToReadyMs + timings.readyToFirstMs;
|
|
1240
|
+
}
|
|
1241
|
+
|
|
1242
|
+
/** How the last attempt at a reply ended: a normal reply, a failure, a stopped half reply, or none yet. */
|
|
1243
|
+
export interface ReplyOutcome {
|
|
1244
|
+
readonly kind: "normal" | "failed" | "stopped" | "none";
|
|
1245
|
+
/** The reply run whose reply, failure or stopped half reply it was. */
|
|
1246
|
+
readonly runId?: string | undefined;
|
|
1247
|
+
}
|
|
1248
|
+
|
|
1249
|
+
/**
|
|
1250
|
+
* The outcome of the last reply attempt. A normal reply, a failure entry and a
|
|
1251
|
+
* stopped half reply are the ways an attempt can end; the newest of them wins,
|
|
1252
|
+
* so a message that arrived after a stopped reply does not hide the stop.
|
|
1253
|
+
*/
|
|
1254
|
+
export function lastReplyOutcome(
|
|
1255
|
+
messages: readonly Message[],
|
|
1256
|
+
entries: readonly Entry[],
|
|
1257
|
+
): ReplyOutcome {
|
|
1258
|
+
let kind: ReplyOutcome["kind"] = "none";
|
|
1259
|
+
let runId: string | undefined;
|
|
1260
|
+
let sequence = -1;
|
|
1261
|
+
for (const message of messages) {
|
|
1262
|
+
if (message.role !== "assistant" || message.sequence <= sequence) continue;
|
|
1263
|
+
kind = "normal";
|
|
1264
|
+
sequence = message.sequence;
|
|
1265
|
+
runId = message.runId;
|
|
1266
|
+
}
|
|
1267
|
+
for (const entry of entries) {
|
|
1268
|
+
if ((entry.kind !== "failure" && entry.kind !== "stopped") || entry.sequence <= sequence) continue;
|
|
1269
|
+
kind = entry.kind === "failure" ? "failed" : "stopped";
|
|
1270
|
+
sequence = entry.sequence;
|
|
1271
|
+
runId = entry.runId;
|
|
1272
|
+
}
|
|
1273
|
+
return { kind, ...(runId === undefined ? {} : { runId }) };
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1276
|
+
/**
|
|
1277
|
+
* The person's messages no assistant message answers yet, oldest first. A
|
|
1278
|
+
* `chat.answered` fact also answers messages an attempt took before it ended
|
|
1279
|
+
* without a reply message.
|
|
1280
|
+
*/
|
|
1281
|
+
export function unanswered(
|
|
1282
|
+
messages: readonly Message[],
|
|
1283
|
+
facts: readonly PluginFact[] = [],
|
|
1284
|
+
): readonly Message[] {
|
|
627
1285
|
const answered = new Set<string>();
|
|
628
1286
|
for (const message of messages) {
|
|
629
1287
|
if (message.role === "assistant") {
|
|
630
1288
|
for (const id of message.replyTo ?? []) answered.add(id);
|
|
631
1289
|
}
|
|
632
1290
|
}
|
|
633
|
-
|
|
1291
|
+
const withdrawn = new Set<string>();
|
|
1292
|
+
for (const fact of facts) {
|
|
1293
|
+
for (const id of takenOfFact(fact)) {
|
|
1294
|
+
if (fact.type === ANSWER_FACT) answered.add(id);
|
|
1295
|
+
}
|
|
1296
|
+
const change = messageChangeOfFact(fact);
|
|
1297
|
+
if (change?.kind === "withdraw") withdrawn.add(change.id);
|
|
1298
|
+
}
|
|
1299
|
+
return messages.filter(
|
|
1300
|
+
(message) => message.role === "user" && !answered.has(message.id) && !withdrawn.has(message.id),
|
|
1301
|
+
);
|
|
634
1302
|
}
|
|
635
1303
|
|
|
636
1304
|
/** The harness session after the last reply, else the chat's own reference. */
|
|
@@ -645,6 +1313,33 @@ export function currentSession(
|
|
|
645
1313
|
return typeof chat.session === "string" && chat.session.length > 0 ? chat.session : undefined;
|
|
646
1314
|
}
|
|
647
1315
|
|
|
1316
|
+
/**
|
|
1317
|
+
* The context a chat's view shows: the last finished reply's numbers, and the
|
|
1318
|
+
* model that gave it. A reply from before the chat's current session is left
|
|
1319
|
+
* out, so `/new` or a model change that starts a session clears the view until
|
|
1320
|
+
* the next reply.
|
|
1321
|
+
*/
|
|
1322
|
+
export function lastReplyContext(
|
|
1323
|
+
chat: ChatData,
|
|
1324
|
+
messages: readonly Message[],
|
|
1325
|
+
): ChatContext | undefined {
|
|
1326
|
+
let last: Message | undefined;
|
|
1327
|
+
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
1328
|
+
const message = messages[index];
|
|
1329
|
+
if (message?.role !== "assistant") continue;
|
|
1330
|
+
last = message;
|
|
1331
|
+
break;
|
|
1332
|
+
}
|
|
1333
|
+
if (last?.context === undefined) return undefined;
|
|
1334
|
+
if ((chat.session ?? undefined) !== (last.session ?? undefined)) return undefined;
|
|
1335
|
+
const model = last.model ?? chat.model ?? chat.lastModel;
|
|
1336
|
+
return {
|
|
1337
|
+
used: last.context.used,
|
|
1338
|
+
...(last.context.window === undefined ? {} : { window: last.context.window }),
|
|
1339
|
+
...(model === undefined || model.length === 0 ? {} : { model }),
|
|
1340
|
+
};
|
|
1341
|
+
}
|
|
1342
|
+
|
|
648
1343
|
function sizeText(size: number): string {
|
|
649
1344
|
if (size < 1024) return `${size} B`;
|
|
650
1345
|
if (size < 1024 * 1024) return `${Math.round(size / 1024)} KB`;
|
|
@@ -661,21 +1356,25 @@ function attachmentLines(message: Message, shown: ReadonlySet<string>): string {
|
|
|
661
1356
|
return `Attached files:\n${lines.join("\n")}`;
|
|
662
1357
|
}
|
|
663
1358
|
|
|
1359
|
+
/** How {@link promptFor} separates one unanswered message from the next. */
|
|
1360
|
+
export const PROMPT_MESSAGE_SEPARATOR = "\n\n---\n\n";
|
|
1361
|
+
|
|
664
1362
|
/**
|
|
665
|
-
* The prompt for the messages to answer, built from facts alone.
|
|
666
|
-
*
|
|
1363
|
+
* The prompt for the messages to answer, built from facts alone. Each message
|
|
1364
|
+
* is its own block, so two messages never read as one; a message's files
|
|
1365
|
+
* follow its text as paths, and `images` are the paths also given as image input.
|
|
667
1366
|
*/
|
|
668
1367
|
export function promptFor(pending: readonly Message[], images: ReadonlySet<string> = new Set()): string {
|
|
669
1368
|
const parts = pending.map((message) =>
|
|
670
1369
|
[message.text, attachmentLines(message, images)].filter((part) => part.length > 0).join("\n\n"),
|
|
671
1370
|
);
|
|
672
|
-
return parts.join(
|
|
1371
|
+
return parts.join(PROMPT_MESSAGE_SEPARATOR);
|
|
673
1372
|
}
|
|
674
1373
|
|
|
675
1374
|
/** One agent's choices for a new chat: what it lists, and what a chat starts with when none is asked for. */
|
|
676
1375
|
export interface AgentChoices {
|
|
677
1376
|
readonly name: string;
|
|
678
|
-
readonly models:
|
|
1377
|
+
readonly models: HarnessModels | undefined;
|
|
679
1378
|
readonly efforts: { readonly list: readonly string[]; readonly default: string | null } | undefined;
|
|
680
1379
|
/** A configured model (a bot's); it is the default only for the agent that lists it. */
|
|
681
1380
|
readonly preferredModel?: string | null | undefined;
|
|
@@ -702,13 +1401,22 @@ export function agentConditionals(agents: readonly AgentChoices[]): ActionArgSch
|
|
|
702
1401
|
return { enum: [...list], ...(chosen === null || chosen === undefined ? {} : { default: chosen }) };
|
|
703
1402
|
};
|
|
704
1403
|
return agents.map((agent) => {
|
|
705
|
-
const
|
|
1404
|
+
const list = modelIds(agent.models);
|
|
1405
|
+
const model = pick(list, agent.preferredModel, agent.models?.default);
|
|
1406
|
+
const info =
|
|
1407
|
+
agent.models?.info === undefined
|
|
1408
|
+
? undefined
|
|
1409
|
+
: Object.fromEntries(
|
|
1410
|
+
Object.entries(agent.models.info).filter(([id]) => list.includes(id)),
|
|
1411
|
+
);
|
|
706
1412
|
const effort = pick(agent.efforts?.list ?? [], agent.preferredEffort, agent.efforts?.default);
|
|
707
1413
|
return {
|
|
708
1414
|
if: { properties: { agent: { const: agent.name } }, required: ["agent"] },
|
|
709
1415
|
then: {
|
|
710
1416
|
properties: {
|
|
711
|
-
...(Object.keys(model).length === 0
|
|
1417
|
+
...(Object.keys(model).length === 0
|
|
1418
|
+
? {}
|
|
1419
|
+
: { model: { type: "string", ...model, ...(info === undefined ? {} : { info }) } }),
|
|
712
1420
|
...(Object.keys(effort).length === 0 ? {} : { effort: { type: "string", ...effort } }),
|
|
713
1421
|
},
|
|
714
1422
|
},
|