@operad-io/chat 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/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 { ActionArgSchema, JsonValue, ObjectRef, ObjectStore, PluginFact } from "@operad-io/engine";
7
- import { isRecord, storedType, stringList } from "@operad-io/engine";
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, so the row can tell a choice from the default. */
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: { readonly list: readonly string[]; readonly default: string | null } | undefined,
395
+ models: HarnessModels | undefined,
235
396
  asked: string | undefined,
236
397
  preferred?: string | undefined,
237
398
  ): string | undefined {
238
- const list = models?.list ?? [];
399
+ const list = modelIds(models);
239
400
  const wanted = asked ?? preferred;
240
401
  if (wanted !== undefined) {
241
402
  if (!list.includes(wanted)) {
@@ -261,6 +422,8 @@ export interface MessageData {
261
422
  readonly source: { readonly kind: string; readonly ref: string | null };
262
423
  /** An assistant message: the ids of the messages it answers. */
263
424
  readonly replyTo?: readonly string[] | undefined;
425
+ /** A user message: text only the agent is given after the text; no view shows it. */
426
+ readonly instruction?: string | undefined;
264
427
  /** The run whose answer this message or entry belongs to. */
265
428
  readonly runId?: string | undefined;
266
429
  /** An assistant message: the harness session after it. */
@@ -270,6 +433,12 @@ export interface MessageData {
270
433
  /** An assistant message: what it cost in millionths of a dollar, when reported. */
271
434
  readonly costMicros?: number | undefined;
272
435
  readonly costQuality?: CostQuality | undefined;
436
+ /** An assistant message: the tokens it used, when the harness reported them. */
437
+ readonly tokens?: UsageTokens | undefined;
438
+ /** An assistant message: the context it ended with, when the harness could tell. */
439
+ readonly context?: ReplyContext | undefined;
440
+ /** An assistant message: how long the step took to start, to its first line, and in all. */
441
+ readonly timings?: AgentTimings | undefined;
273
442
  }
274
443
 
275
444
  /** One message with when it was recorded. */
@@ -294,7 +463,11 @@ export interface EntryData {
294
463
  /** What ran: the command, path or main argument, as the harness summarized it. */
295
464
  readonly input?: string | null | undefined;
296
465
  readonly result?: ToolResult | undefined;
297
- /** Epoch milliseconds; null when the harness gave no start time. */
466
+ /**
467
+ * Epoch milliseconds: a tool call's start, or when the log received the line
468
+ * that finished a text or thinking part. Null for a tool call whose log had
469
+ * no start line; absent when the item carries no time, such as an old fact.
470
+ */
298
471
  readonly startedAt?: number | null | undefined;
299
472
  readonly durationMs?: number | undefined;
300
473
  /** The first 4 KB of what the call printed; null when it printed nothing. */
@@ -304,6 +477,12 @@ export interface EntryData {
304
477
  readonly outputTruncated?: boolean | undefined;
305
478
  /** The first line of the error, when the call failed. */
306
479
  readonly error?: string | null | undefined;
480
+ /** On `failure`: why the reply failed (`empty`, `model_error`, ...). */
481
+ readonly reason?: string | undefined;
482
+ /** On `failure`: the oldest message the failed reply was for. */
483
+ readonly messageId?: string | undefined;
484
+ /** On `stopped`: the one line that says a crash or restart interrupted the reply. */
485
+ readonly interrupted?: boolean | undefined;
307
486
  }
308
487
 
309
488
  /** One entry with when its fact was recorded. */
@@ -312,30 +491,313 @@ export interface Entry extends EntryData {
312
491
  readonly sequence: number;
313
492
  }
314
493
 
494
+ /** What a stop fact holds: the reply run the command cancelled, and who stopped it. */
495
+ export interface StopData {
496
+ readonly [key: string]: unknown;
497
+ readonly runId: string;
498
+ readonly by: { readonly via: string; readonly id: string };
499
+ }
500
+
501
+ /** The stop a fact records, or undefined for another fact. */
502
+ export function stopOfFact(fact: PluginFact): StopData | undefined {
503
+ if (fact.type !== STOP_FACT) return undefined;
504
+ const data = fact.data;
505
+ if (typeof data.runId !== "string" || data.runId.length === 0) return undefined;
506
+ const from = isRecord(data.by) ? data.by : {};
507
+ return {
508
+ runId: data.runId,
509
+ by: {
510
+ via: typeof from.via === "string" ? from.via : "",
511
+ id: typeof from.id === "string" ? from.id : "",
512
+ },
513
+ };
514
+ }
515
+
516
+ /** The run a stop fact cancelled after a sequence, newest first, or undefined. */
517
+ export function stoppedRunAfter(
518
+ facts: readonly PluginFact[],
519
+ after: number,
520
+ ): string | undefined {
521
+ let found: string | undefined;
522
+ for (const fact of facts) {
523
+ if (fact.sequence <= after) continue;
524
+ const stop = stopOfFact(fact);
525
+ if (stop !== undefined) found = stop.runId;
526
+ }
527
+ return found;
528
+ }
529
+
530
+ /** The ids a `chat.answered` fact records as taken by one run. */
531
+ export function answeredOfFact(fact: PluginFact): readonly string[] {
532
+ if (fact.type !== ANSWER_FACT || !Array.isArray(fact.data.ids)) return [];
533
+ return fact.data.ids.filter((id): id is string => typeof id === "string" && id.length > 0);
534
+ }
535
+
536
+ /** The ids a `chat.answered` or `chat.taken` fact records as taken by one run. */
537
+ export function takenOfFact(fact: PluginFact): readonly string[] {
538
+ if ((fact.type !== ANSWER_FACT && fact.type !== TAKEN_FACT) || !Array.isArray(fact.data.ids)) return [];
539
+ return fact.data.ids.filter((id): id is string => typeof id === "string" && id.length > 0);
540
+ }
541
+
542
+ /** Every message a run has taken: in its first prompt, handed over mid-run, or answered. */
543
+ export function takenIds(facts: readonly PluginFact[]): ReadonlySet<string> {
544
+ const taken = new Set<string>();
545
+ for (const fact of facts) {
546
+ for (const id of takenOfFact(fact)) taken.add(id);
547
+ if (fact.type === MESSAGE_FACT && fact.data.role === "assistant" && Array.isArray(fact.data.replyTo)) {
548
+ for (const id of fact.data.replyTo) {
549
+ if (typeof id === "string" && id.length > 0) taken.add(id);
550
+ }
551
+ }
552
+ }
553
+ return taken;
554
+ }
555
+
556
+ /** What a message change fact holds: who changed which message, and how. */
557
+ export interface MessageChangeData {
558
+ readonly [key: string]: unknown;
559
+ readonly id: string;
560
+ readonly kind: "text" | "withdraw";
561
+ readonly by: { readonly via: string; readonly id: string };
562
+ /** The new text, on a `text` change. */
563
+ readonly text?: string | undefined;
564
+ }
565
+
566
+ /** One message change with when its fact was recorded. */
567
+ export interface MessageChange extends MessageChangeData {
568
+ readonly at: number;
569
+ readonly sequence: number;
570
+ }
571
+
572
+ /** The change a fact records, or undefined for another fact. */
573
+ export function messageChangeOfFact(fact: PluginFact): MessageChange | undefined {
574
+ if (fact.type !== MESSAGE_CHANGE_FACT) return undefined;
575
+ const data = fact.data;
576
+ if (typeof data.id !== "string" || data.id.length === 0) return undefined;
577
+ if (data.kind !== "text" && data.kind !== "withdraw") return undefined;
578
+ if (data.kind === "text" && typeof data.text !== "string") return undefined;
579
+ const from = isRecord(data.by) ? data.by : {};
580
+ return {
581
+ id: data.id,
582
+ kind: data.kind,
583
+ by: {
584
+ via: typeof from.via === "string" ? from.via : "",
585
+ id: typeof from.id === "string" ? from.id : "",
586
+ },
587
+ ...(typeof data.text === "string" ? { text: data.text } : {}),
588
+ at: fact.at,
589
+ sequence: fact.sequence,
590
+ };
591
+ }
592
+
593
+ /** The changes to each message, oldest first: its latest text and its withdrawal. */
594
+ export interface MessageChangeState {
595
+ readonly withdrawn?: MessageChange | undefined;
596
+ readonly text?: string | undefined;
597
+ }
598
+
599
+ export function messageChangesOf(facts: readonly PluginFact[]): ReadonlyMap<string, MessageChangeState> {
600
+ const changes = new Map<string, MessageChangeState>();
601
+ for (const fact of facts) {
602
+ const change = messageChangeOfFact(fact);
603
+ if (change === undefined) continue;
604
+ const before = changes.get(change.id) ?? {};
605
+ changes.set(
606
+ change.id,
607
+ change.kind === "withdraw"
608
+ ? { ...before, withdrawn: change }
609
+ : { ...before, text: change.text },
610
+ );
611
+ }
612
+ return changes;
613
+ }
614
+
615
+ /** The messages with their latest text, without the ones a person withdrew. */
616
+ export function applyMessageChanges(
617
+ messages: readonly Message[],
618
+ changes: ReadonlyMap<string, MessageChangeState>,
619
+ ): readonly Message[] {
620
+ const found: Message[] = [];
621
+ for (const message of messages) {
622
+ const change = changes.get(message.id);
623
+ if (change?.withdrawn !== undefined) continue;
624
+ found.push(change?.text === undefined ? message : { ...message, text: change.text });
625
+ }
626
+ return found;
627
+ }
628
+
629
+ /** The message facts with their latest text, without the messages a person withdrew. */
630
+ export function messageFactsInForce(
631
+ facts: readonly PluginFact[],
632
+ changes: ReadonlyMap<string, MessageChangeState> = messageChangesOf(facts),
633
+ ): readonly PluginFact[] {
634
+ const found: PluginFact[] = [];
635
+ for (const fact of facts) {
636
+ if (fact.type !== MESSAGE_FACT || fact.data.role !== "user") {
637
+ found.push(fact);
638
+ continue;
639
+ }
640
+ const id = typeof fact.data.id === "string" ? fact.data.id : undefined;
641
+ const change = id === undefined ? undefined : changes.get(id);
642
+ if (change?.withdrawn !== undefined) continue;
643
+ found.push(
644
+ change?.text === undefined ? fact : { ...fact, data: { ...fact.data, text: change.text } },
645
+ );
646
+ }
647
+ return found;
648
+ }
649
+
650
+ /** A queued message, in the shape a chat's row and section carry. */
651
+ export interface QueuedMessage {
652
+ readonly id: string;
653
+ readonly text: string;
654
+ readonly at: number;
655
+ readonly attachments: readonly Attachment[];
656
+ }
657
+
658
+ /** The queued messages a chat shows a client, oldest first. */
659
+ export function queuedMessages(
660
+ messages: readonly Message[],
661
+ facts: readonly PluginFact[],
662
+ ): readonly Message[] {
663
+ const taken = takenIds(facts);
664
+ return unanswered(messages, facts).filter((message) => !taken.has(message.id));
665
+ }
666
+
667
+ /** The queued messages as a client reads them. */
668
+ export function queuedData(messages: readonly Message[]): readonly QueuedMessage[] {
669
+ return messages.map((message) => ({
670
+ id: message.id,
671
+ text: message.text,
672
+ at: message.at,
673
+ attachments: message.attachments,
674
+ }));
675
+ }
676
+
677
+ /** The queued messages a stored chat object carries, when it has them. */
678
+ export function queuedOf(value: unknown): readonly QueuedMessage[] {
679
+ if (!Array.isArray(value)) return [];
680
+ const found: QueuedMessage[] = [];
681
+ for (const item of value) {
682
+ if (!isRecord(item)) continue;
683
+ if (typeof item.id !== "string" || item.id.length === 0) continue;
684
+ if (typeof item.text !== "string") continue;
685
+ const at = item.at;
686
+ if (typeof at !== "number" || !Number.isFinite(at)) continue;
687
+ found.push({ id: item.id, text: item.text, at, attachments: attachmentsOf(item.attachments) });
688
+ }
689
+ return found;
690
+ }
691
+
692
+ /** The run an attempt fact says ended on its own, or undefined for another fact. */
693
+ export function attemptEndedOfFact(fact: PluginFact): string | undefined {
694
+ if (fact.type !== ATTEMPT_END_FACT) return undefined;
695
+ return typeof fact.data.runId === "string" && fact.data.runId.length > 0
696
+ ? fact.data.runId
697
+ : undefined;
698
+ }
699
+
315
700
  /** What a close fact holds: who closed the chat. */
316
701
  export interface ClosedData {
317
702
  readonly [key: string]: unknown;
318
703
  readonly by: { readonly via: string; readonly id: string };
319
704
  }
320
705
 
321
- /** The chat fields of a stored object, with the lists defaulted. */
706
+ /** What a command fact holds: who typed it, the command and how it went. */
707
+ export interface CommandData {
708
+ readonly [key: string]: unknown;
709
+ readonly from: { readonly via: string; readonly id: string };
710
+ /** The command as typed, starting with `/`. */
711
+ readonly command: string;
712
+ /** What happened, or why it was refused. */
713
+ readonly outcome: string;
714
+ readonly ok: boolean;
715
+ }
716
+
717
+ /** One command with when its fact was recorded. */
718
+ export interface Command extends CommandData {
719
+ readonly at: number;
720
+ readonly sequence: number;
721
+ }
722
+
723
+ /** The command a fact records, or undefined for another fact. */
724
+ export function commandOfFact(fact: PluginFact): Command | undefined {
725
+ if (fact.type !== COMMAND_FACT) return undefined;
726
+ const data = fact.data;
727
+ if (
728
+ typeof data.command !== "string" ||
729
+ typeof data.outcome !== "string" ||
730
+ typeof data.ok !== "boolean"
731
+ ) {
732
+ return undefined;
733
+ }
734
+ const from = isRecord(data.from) ? data.from : {};
735
+ return {
736
+ from: {
737
+ via: typeof from.via === "string" ? from.via : "",
738
+ id: typeof from.id === "string" ? from.id : "",
739
+ },
740
+ command: data.command,
741
+ outcome: data.outcome,
742
+ ok: data.ok,
743
+ at: fact.at,
744
+ sequence: fact.sequence,
745
+ };
746
+ }
747
+
748
+ /** The level a chat falls back to when it has none: a read-only profile starts at plan, any other at ask. */
749
+ function fallbackAccessLevel(data: Readonly<Record<string, unknown>>): AccessLevel {
750
+ return isRecord(data.access) && data.access.readOnly === true ? "plan" : "ask";
751
+ }
752
+
753
+ function noteHashesOf(value: unknown): ChatNoteHashes | undefined {
754
+ if (!isRecord(value) || !isRecord(value.files)) return undefined;
755
+ const files: Record<string, string> = {};
756
+ for (const [name, hash] of Object.entries(value.files)) {
757
+ if (name.length > 0 && typeof hash === "string" && hash.length > 0) files[name] = hash;
758
+ }
759
+ return {
760
+ ...(typeof value.session === "string" && value.session.length > 0 ? { session: value.session } : {}),
761
+ files,
762
+ };
763
+ }
764
+
765
+ /** The chat fields of a stored object, with the lists and the access level defaulted. */
322
766
  export function chatData(data: Readonly<Record<string, unknown>>): ChatData {
767
+ const tokens = usageTokensOf(data.tokens);
768
+ const scheduled = scheduledChatOf(data.scheduled);
769
+ const noteHashes = noteHashesOf(data.noteHashes);
770
+ const accessDefault = isAccessLevel(data.accessDefault)
771
+ ? data.accessDefault
772
+ : fallbackAccessLevel(data);
773
+ const accessLevel = isAccessLevel(data.accessLevel) ? data.accessLevel : accessDefault;
774
+ // A chat stored before the flag existed chose a level when it differs from its starting one.
775
+ const accessChosen = data.accessChosen === true || accessLevel !== accessDefault;
323
776
  return {
324
777
  ...data,
325
778
  harness: typeof data.harness === "string" ? data.harness : "",
326
779
  cwd: typeof data.cwd === "string" ? data.cwd : "",
327
780
  access: isRecord(data.access) ? (data.access as Record<string, JsonValue>) : {},
781
+ accessLevel,
782
+ accessDefault,
783
+ accessChosen,
328
784
  skills: stringList(data.skills),
329
785
  title: typeof data.title === "string" ? data.title : "",
330
786
  closed: data.closed === true,
331
787
  channels: stringList(data.channels),
332
788
  ...(typeof data.refresh === "string" && data.refresh.length > 0 ? { refresh: data.refresh } : {}),
789
+ ...(typeof data.accessAction === "string" && data.accessAction.length > 0 ? { accessAction: data.accessAction } : {}),
790
+ ...(typeof data.contextCwd === "string" && data.contextCwd.length > 0 ? { contextCwd: data.contextCwd } : {}),
791
+ ...(noteHashes === undefined ? {} : { noteHashes }),
333
792
  ...(typeof data.model === "string" && data.model.length > 0 ? { model: data.model } : {}),
334
793
  ...(typeof data.effort === "string" && data.effort.length > 0 ? { effort: data.effort } : {}),
335
794
  ...(typeof data.effortDefault === "string" && data.effortDefault.length > 0 ? { effortDefault: data.effortDefault } : {}),
336
795
  ...(typeof data.lastModel === "string" && data.lastModel.length > 0 ? { lastModel: data.lastModel } : {}),
337
796
  ...(typeof data.costMicros === "number" && Number.isFinite(data.costMicros) ? { costMicros: data.costMicros } : {}),
338
797
  ...(isCostQuality(data.costQuality) ? { costQuality: data.costQuality } : {}),
798
+ ...(tokens === undefined ? {} : { tokens }),
799
+ ...(data.tokensIncomplete === true ? { tokensIncomplete: true as const } : {}),
800
+ ...(scheduled === undefined ? {} : { scheduled }),
339
801
  };
340
802
  }
341
803
 
@@ -364,31 +826,91 @@ export function modelAndCost(
364
826
  /** What a chat uses, for its row and its page: `claude · sonnet · high · $0.12`. */
365
827
  export function agentLine(chat: ChatData): string {
366
828
  const model = chat.model ?? chat.lastModel;
367
- const effort =
368
- chat.effort !== undefined && chat.effort !== chat.effortDefault ? [chat.effort] : [];
829
+ // A row reads only the stored chat, so it shows the effort the chat itself
830
+ // chose; the agent's live default is not a choice and may have changed since.
831
+ const effort = chosenEffort(chat);
369
832
  return [
370
833
  chat.harness,
371
834
  ...(model === undefined || model.length === 0 ? [] : [model]),
372
- ...effort,
835
+ ...(effort === undefined ? [] : [effort]),
373
836
  ...(chat.costMicros === undefined ? [] : [costText(chat.costMicros, chat.costQuality)]),
374
837
  ]
375
838
  .filter((part) => part.length > 0)
376
839
  .join(" · ");
377
840
  }
378
841
 
379
- /** The model, cost and quality a harness's `usage` reports; each only when it did. */
842
+ /** The four token counts of a usage, when all are known and at least one is not zero. */
843
+ function usageTokensOf(value: unknown): UsageTokens | undefined {
844
+ if (!isRecord(value)) return undefined;
845
+ const count = (key: string): number | undefined => {
846
+ const found = value[key];
847
+ return typeof found === "number" && Number.isInteger(found) && found >= 0 ? found : undefined;
848
+ };
849
+ const input = count("input");
850
+ const output = count("output");
851
+ const cacheread = count("cacheread");
852
+ const cachewrite = count("cachewrite");
853
+ if (input === undefined || output === undefined || cacheread === undefined || cachewrite === undefined) {
854
+ return undefined;
855
+ }
856
+ // A harness that reports no token counts gives all four as zero.
857
+ if (input === 0 && output === 0 && cacheread === 0 && cachewrite === 0) return undefined;
858
+ return { input, output, cacheread, cachewrite };
859
+ }
860
+
861
+ /** What a reply records about the context it ended with. */
862
+ export interface ReplyContext {
863
+ readonly used: number;
864
+ readonly window?: number | undefined;
865
+ }
866
+
867
+ /** What a chat's view says about its context: the last reply's numbers and model. */
868
+ export interface ChatContext extends ReplyContext {
869
+ readonly model?: string | undefined;
870
+ }
871
+
872
+ /** The context numbers a harness or a stored reply reports, when they are whole. */
873
+ export function replyContextOf(value: unknown): ReplyContext | undefined {
874
+ if (!isRecord(value)) return undefined;
875
+ const used = value.used;
876
+ if (typeof used !== "number" || !Number.isInteger(used) || used < 0) return undefined;
877
+ const window = value.window;
878
+ const known = typeof window === "number" && Number.isInteger(window) && window > 0 ? window : undefined;
879
+ return { used, ...(known === undefined ? {} : { window: known }) };
880
+ }
881
+
882
+ /** The model, tokens, cost and quality a harness's `usage` reports; each only when it did. */
380
883
  export function usageOf(value: unknown): {
381
884
  readonly model?: string;
382
885
  readonly costMicros?: number;
383
886
  readonly costQuality?: CostQuality;
887
+ readonly tokens?: UsageTokens;
384
888
  } {
385
889
  if (!isRecord(value)) return {};
386
890
  const micros = value.costMicros;
387
891
  const known = typeof micros === "number" && Number.isFinite(micros);
892
+ const tokens = usageTokensOf(value.tokens);
388
893
  return {
389
894
  ...(typeof value.model === "string" && value.model.length > 0 ? { model: value.model } : {}),
390
895
  ...(known ? { costMicros: micros } : {}),
391
896
  ...(known ? { costQuality: isCostQuality(value.costQuality) ? value.costQuality : "estimated" } : {}),
897
+ ...(tokens === undefined ? {} : { tokens }),
898
+ };
899
+ }
900
+
901
+ /** The timings a harness's step data reports; undefined when it has none or not a whole one. */
902
+ export function timingsOf(value: unknown): AgentTimings | undefined {
903
+ if (!isRecord(value)) return undefined;
904
+ const total = value.totalMs;
905
+ if (typeof total !== "number" || !Number.isFinite(total)) return undefined;
906
+ const duration = (key: string): number | null => {
907
+ const at = value[key];
908
+ return typeof at === "number" && Number.isFinite(at) ? at : null;
909
+ };
910
+ return {
911
+ startToReadyMs: duration("startToReadyMs"),
912
+ readyToFirstMs: duration("readyToFirstMs"),
913
+ totalMs: total,
392
914
  };
393
915
  }
394
916
 
@@ -454,11 +976,18 @@ export async function createChat(
454
976
  if (input.harness.trim().length === 0) throw new Error("a chat needs an agent");
455
977
  if (input.cwd.trim().length === 0) throw new Error("a chat needs a working directory");
456
978
  if (input.title.trim().length === 0) throw new Error("a chat needs a title");
979
+ const accessLevel =
980
+ input.accessLevel ??
981
+ input.accessDefault ??
982
+ (input.access?.readOnly === true ? "plan" : "ask");
983
+ const accessDefault = input.accessDefault ?? accessLevel;
457
984
  const data: ChatData = {
458
985
  ...(input.parent === undefined ? {} : { parent: input.parent }),
459
986
  harness: input.harness,
460
987
  cwd: input.cwd,
461
988
  access: input.access ?? {},
989
+ accessLevel,
990
+ accessDefault,
462
991
  skills: input.skills ?? [],
463
992
  title: input.title.trim(),
464
993
  closed: false,
@@ -466,8 +995,10 @@ export async function createChat(
466
995
  channels: input.channels ?? [],
467
996
  ...(input.model === undefined ? {} : { model: input.model }),
468
997
  ...(input.effort === undefined ? {} : { effort: input.effort }),
469
- ...(input.effort === undefined || input.effortDefault === undefined ? {} : { effortDefault: input.effortDefault }),
998
+ ...(input.effortDefault === undefined ? {} : { effortDefault: input.effortDefault }),
470
999
  ...(input.refresh === undefined ? {} : { refresh: input.refresh }),
1000
+ ...(input.accessAction === undefined ? {} : { accessAction: input.accessAction }),
1001
+ ...(input.scheduled === undefined ? {} : { scheduled: input.scheduled }),
471
1002
  };
472
1003
  // The id counts up; a taken one (two chats made at once) moves on to the next.
473
1004
  for (let attempt = 0; attempt < 20; attempt += 1) {
@@ -487,6 +1018,9 @@ function messageOfFact(fact: PluginFact): Message | undefined {
487
1018
  if (data.role !== "user" && data.role !== "assistant") return undefined;
488
1019
  const from = isRecord(data.from) ? data.from : {};
489
1020
  const source = isRecord(data.source) ? data.source : {};
1021
+ const timings = timingsOf(data.timings);
1022
+ const tokens = usageTokensOf(data.tokens);
1023
+ const context = replyContextOf(data.context);
490
1024
  return {
491
1025
  id: data.id,
492
1026
  role: data.role,
@@ -501,11 +1035,17 @@ function messageOfFact(fact: PluginFact): Message | undefined {
501
1035
  ref: typeof source.ref === "string" ? source.ref : null,
502
1036
  },
503
1037
  ...(Array.isArray(data.replyTo) ? { replyTo: stringList(data.replyTo) } : {}),
1038
+ ...(data.role === "user" && typeof data.instruction === "string" && data.instruction.length > 0
1039
+ ? { instruction: data.instruction }
1040
+ : {}),
504
1041
  ...(typeof data.runId === "string" && data.runId.length > 0 ? { runId: data.runId } : {}),
505
1042
  ...(typeof data.session === "string" ? { session: data.session } : {}),
506
1043
  ...(typeof data.model === "string" && data.model.length > 0 ? { model: data.model } : {}),
507
1044
  ...(typeof data.costMicros === "number" && Number.isFinite(data.costMicros) ? { costMicros: data.costMicros } : {}),
508
1045
  ...(isCostQuality(data.costQuality) ? { costQuality: data.costQuality } : {}),
1046
+ ...(tokens === undefined ? {} : { tokens }),
1047
+ ...(context === undefined ? {} : { context }),
1048
+ ...(timings === undefined ? {} : { timings }),
509
1049
  at: fact.at,
510
1050
  sequence: fact.sequence,
511
1051
  };
@@ -520,20 +1060,28 @@ export function entryOfFact(fact: PluginFact): Entry | undefined {
520
1060
  const data = fact.data;
521
1061
  if (typeof data.runId !== "string" || data.runId.length === 0) return undefined;
522
1062
  const kind = data.kind;
523
- if (kind !== "text" && kind !== "thinking" && kind !== "tool" && kind !== "stopped") return undefined;
1063
+ if (kind !== "text" && kind !== "thinking" && kind !== "tool" && kind !== "stopped" && kind !== "failure" && kind !== "worktree") return undefined;
524
1064
  const entryKind: EntryKind = kind;
525
- const base = { runId: data.runId, kind: entryKind, at: fact.at, sequence: fact.sequence };
1065
+ const base = {
1066
+ runId: data.runId,
1067
+ kind: entryKind,
1068
+ at: fact.at,
1069
+ sequence: fact.sequence,
1070
+ ...(typeof data.startedAt === "number" || data.startedAt === null ? { startedAt: data.startedAt } : {}),
1071
+ ...(typeof data.reason === "string" ? { reason: data.reason } : {}),
1072
+ ...(typeof data.messageId === "string" ? { messageId: data.messageId } : {}),
1073
+ ...(data.interrupted === true ? { interrupted: true } : {}),
1074
+ };
526
1075
  if (entryKind === "tool") {
527
- if (typeof data.callId !== "string" || typeof data.toolName !== "string" || !isToolResult(data.result)) {
528
- return undefined;
529
- }
1076
+ if (!isToolResult(data.result)) return undefined;
530
1077
  return {
531
1078
  ...base,
532
- callId: data.callId,
533
- toolName: data.toolName,
1079
+ // An older or partly written entry may have no id or name; it still ran,
1080
+ // so it is shown as a tool rather than dropped from the transcript.
1081
+ callId: typeof data.callId === "string" ? data.callId : "",
1082
+ toolName: typeof data.toolName === "string" && data.toolName.length > 0 ? data.toolName : "tool",
534
1083
  ...(typeof data.input === "string" || data.input === null ? { input: data.input } : {}),
535
1084
  result: data.result,
536
- ...(typeof data.startedAt === "number" || data.startedAt === null ? { startedAt: data.startedAt } : {}),
537
1085
  ...(typeof data.durationMs === "number" && Number.isFinite(data.durationMs) ? { durationMs: data.durationMs } : {}),
538
1086
  ...(typeof data.output === "string" || data.output === null ? { output: data.output } : {}),
539
1087
  ...(typeof data.outputPath === "string" ? { outputPath: data.outputPath } : {}),
@@ -544,73 +1092,78 @@ export function entryOfFact(fact: PluginFact): Entry | undefined {
544
1092
  return typeof data.text === "string" ? { ...base, text: data.text } : undefined;
545
1093
  }
546
1094
 
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 } {
1095
+ /** The messages among a chat's facts, with a person's changed text and withdrawal. */
1096
+ function messagesOfFacts(facts: readonly PluginFact[]): readonly Message[] {
1097
+ const changes = messageChangesOf(facts);
554
1098
  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 };
1099
+ for (const fact of facts) {
1100
+ const message = messageOfFact(fact);
1101
+ if (message === undefined) continue;
1102
+ if (message.role !== "user") {
1103
+ messages.push(message);
1104
+ continue;
567
1105
  }
568
- at = page.next;
1106
+ const change = changes.get(message.id);
1107
+ if (change?.withdrawn !== undefined) continue;
1108
+ messages.push(change?.text === undefined ? message : { ...message, text: change.text });
569
1109
  }
1110
+ return messages;
570
1111
  }
571
1112
 
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);
1113
+ /** The entries among a chat's facts. */
1114
+ function entriesOfFacts(facts: readonly PluginFact[]): readonly Entry[] {
1115
+ const found: Entry[] = [];
1116
+ for (const fact of facts) {
1117
+ const entry = entryOfFact(fact);
1118
+ if (entry !== undefined) found.push(entry);
1119
+ }
581
1120
  return found;
582
1121
  }
583
1122
 
1123
+ /** Every message of a chat in force, oldest first: changed text, and no withdrawn message. */
1124
+ export function allMessages(store: ObjectStore, chat: string): readonly Message[] {
1125
+ return messagesOfFacts(chatFacts(store, chat));
1126
+ }
1127
+
584
1128
  /** Every entry of a chat, oldest first. */
585
1129
  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;
1130
+ return entriesOfFacts(chatFacts(store, chat));
600
1131
  }
601
1132
 
602
- /** Every fact of a chat, oldest first. */
603
- export function chatFacts(store: ObjectStore, chat: string): readonly PluginFact[] {
1133
+ /** Every fact of one object, oldest first. */
1134
+ export function factsOf(store: ObjectStore, ref: ObjectRef): readonly PluginFact[] {
604
1135
  const facts: PluginFact[] = [];
605
1136
  let cursor: string | undefined;
606
1137
  do {
607
- const page = store.facts(chatRef(chat), { ...(cursor === undefined ? {} : { cursor }), limit: 500 });
1138
+ const page = store.facts(ref, { ...(cursor === undefined ? {} : { cursor }), limit: 500 });
608
1139
  facts.push(...page.facts);
609
1140
  cursor = page.next;
610
1141
  } while (cursor !== undefined);
611
1142
  return facts;
612
1143
  }
613
1144
 
1145
+ /** Every fact of a chat, oldest first. */
1146
+ export function chatFacts(store: ObjectStore, chat: string): readonly PluginFact[] {
1147
+ return factsOf(store, chatRef(chat));
1148
+ }
1149
+
1150
+ /** Everything a reader needs from a chat's facts, from one scan. */
1151
+ export interface ChatRead {
1152
+ readonly facts: readonly PluginFact[];
1153
+ readonly messages: readonly Message[];
1154
+ readonly entries: readonly Entry[];
1155
+ }
1156
+
1157
+ /** Reads a chat's facts once and derives its messages and entries from them. */
1158
+ export function readChat(store: ObjectStore, chat: string): ChatRead {
1159
+ const facts = chatFacts(store, chat);
1160
+ return {
1161
+ facts,
1162
+ messages: messagesOfFacts(facts),
1163
+ entries: entriesOfFacts(facts),
1164
+ };
1165
+ }
1166
+
614
1167
  /** The run id of the latest reply run recorded on a chat, if any. */
615
1168
  export function latestRunOf(facts: readonly PluginFact[]): string | undefined {
616
1169
  let found: string | undefined;
@@ -622,15 +1175,135 @@ export function latestRunOf(facts: readonly PluginFact[]): string | undefined {
622
1175
  return found;
623
1176
  }
624
1177
 
625
- /** The person's messages no assistant message answers yet, oldest first. */
626
- export function unanswered(messages: readonly Message[]): readonly Message[] {
1178
+ /** A reply run that is being written: its run id and when it began. */
1179
+ export interface WritingReply {
1180
+ readonly runId: string;
1181
+ readonly since: number;
1182
+ }
1183
+
1184
+ /**
1185
+ * The reply being written, if one is. The latest `chat.run` fact starts an
1186
+ * attempt; a failure entry, a stopped half reply or a successful `/stop` for
1187
+ * that run ends it. A reply for that run with no messages still unanswered also
1188
+ * ends it; with messages unanswered the flow is going round again. The answer
1189
+ * reads the chat's facts, so it works while the reply runs and costs no tokens.
1190
+ */
1191
+ export function writingReply(
1192
+ facts: readonly PluginFact[],
1193
+ messages: readonly Message[],
1194
+ entries: readonly Entry[],
1195
+ ): WritingReply | undefined {
1196
+ let runId: string | undefined;
1197
+ let since: number | undefined;
1198
+ let started = -1;
1199
+ for (const fact of facts) {
1200
+ if (fact.type === RUN_FACT && typeof fact.data.runId === "string" && fact.data.runId.length > 0) {
1201
+ runId = fact.data.runId;
1202
+ since = fact.at;
1203
+ started = fact.sequence;
1204
+ }
1205
+ }
1206
+ if (runId === undefined || since === undefined) return undefined;
1207
+ const ended = entries.some(
1208
+ (entry) => (entry.kind === "failure" || entry.kind === "stopped") && entry.runId === runId,
1209
+ );
1210
+ const stopped = facts.some((fact) => {
1211
+ if (fact.sequence <= started) return false;
1212
+ return stopOfFact(fact)?.runId === runId;
1213
+ });
1214
+ if (ended || stopped) return undefined;
1215
+ const replied = messages.some((message) => message.role === "assistant" && message.runId === runId);
1216
+ // The flow goes round again while messages arrived during the reply: a reply
1217
+ // for this run with messages still unanswered is the next round, not an end.
1218
+ if (!replied || unanswered(messages, facts).length > 0) return { runId, since };
1219
+ return undefined;
1220
+ }
1221
+
1222
+ /**
1223
+ * The reply being written now: as {@link writingReply}, unless the host says the
1224
+ * latest run has ended. A host that cannot tell leaves the fact-only answer as
1225
+ * it was.
1226
+ */
1227
+ export async function writingReplyNow(
1228
+ facts: readonly PluginFact[],
1229
+ messages: readonly Message[],
1230
+ entries: readonly Entry[],
1231
+ runs?: Pick<RunControl, "active"> | undefined,
1232
+ ): Promise<WritingReply | undefined> {
1233
+ const writing = writingReply(facts, messages, entries);
1234
+ if (writing === undefined || runs === undefined) return writing;
1235
+ const active = await runs.active(writing.runId);
1236
+ return active === false ? undefined : writing;
1237
+ }
1238
+
1239
+ /** The time from a reply's start to its first output, when its timings hold both parts. */
1240
+ export function firstOutputMs(timings: AgentTimings | undefined): number | undefined {
1241
+ if (timings === undefined || timings.startToReadyMs === null || timings.readyToFirstMs === null) {
1242
+ return undefined;
1243
+ }
1244
+ return timings.startToReadyMs + timings.readyToFirstMs;
1245
+ }
1246
+
1247
+ /** How the last attempt at a reply ended: a normal reply, a failure, a stopped half reply, or none yet. */
1248
+ export interface ReplyOutcome {
1249
+ readonly kind: "normal" | "failed" | "stopped" | "none";
1250
+ /** The reply run whose reply, failure or stopped half reply it was. */
1251
+ readonly runId?: string | undefined;
1252
+ }
1253
+
1254
+ /**
1255
+ * The outcome of the last reply attempt. A normal reply, a failure entry and a
1256
+ * stopped half reply are the ways an attempt can end; the newest of them wins,
1257
+ * so a message that arrived after a stopped reply does not hide the stop.
1258
+ */
1259
+ export function lastReplyOutcome(
1260
+ messages: readonly Message[],
1261
+ entries: readonly Entry[],
1262
+ ): ReplyOutcome {
1263
+ let kind: ReplyOutcome["kind"] = "none";
1264
+ let runId: string | undefined;
1265
+ let sequence = -1;
1266
+ for (const message of messages) {
1267
+ if (message.role !== "assistant" || message.sequence <= sequence) continue;
1268
+ kind = "normal";
1269
+ sequence = message.sequence;
1270
+ runId = message.runId;
1271
+ }
1272
+ for (const entry of entries) {
1273
+ if ((entry.kind !== "failure" && entry.kind !== "stopped") || entry.sequence <= sequence) continue;
1274
+ kind = entry.kind === "failure" ? "failed" : "stopped";
1275
+ sequence = entry.sequence;
1276
+ runId = entry.runId;
1277
+ }
1278
+ return { kind, ...(runId === undefined ? {} : { runId }) };
1279
+ }
1280
+
1281
+ /**
1282
+ * The person's messages no assistant message answers yet, oldest first. A
1283
+ * `chat.answered` fact also answers messages an attempt took before it ended
1284
+ * without a reply message.
1285
+ */
1286
+ export function unanswered(
1287
+ messages: readonly Message[],
1288
+ facts: readonly PluginFact[] = [],
1289
+ ): readonly Message[] {
627
1290
  const answered = new Set<string>();
628
1291
  for (const message of messages) {
629
1292
  if (message.role === "assistant") {
630
1293
  for (const id of message.replyTo ?? []) answered.add(id);
631
1294
  }
632
1295
  }
633
- return messages.filter((message) => message.role === "user" && !answered.has(message.id));
1296
+ const withdrawn = new Set<string>();
1297
+ for (const fact of facts) {
1298
+ for (const id of takenOfFact(fact)) {
1299
+ if (fact.type === ANSWER_FACT) answered.add(id);
1300
+ }
1301
+ const change = messageChangeOfFact(fact);
1302
+ if (change?.kind === "withdraw") withdrawn.add(change.id);
1303
+ }
1304
+ return messages.filter(
1305
+ (message) => message.role === "user" && !answered.has(message.id) && !withdrawn.has(message.id),
1306
+ );
634
1307
  }
635
1308
 
636
1309
  /** The harness session after the last reply, else the chat's own reference. */
@@ -645,6 +1318,33 @@ export function currentSession(
645
1318
  return typeof chat.session === "string" && chat.session.length > 0 ? chat.session : undefined;
646
1319
  }
647
1320
 
1321
+ /**
1322
+ * The context a chat's view shows: the last finished reply's numbers, and the
1323
+ * model that gave it. A reply from before the chat's current session is left
1324
+ * out, so `/new` or a model change that starts a session clears the view until
1325
+ * the next reply.
1326
+ */
1327
+ export function lastReplyContext(
1328
+ chat: ChatData,
1329
+ messages: readonly Message[],
1330
+ ): ChatContext | undefined {
1331
+ let last: Message | undefined;
1332
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
1333
+ const message = messages[index];
1334
+ if (message?.role !== "assistant") continue;
1335
+ last = message;
1336
+ break;
1337
+ }
1338
+ if (last?.context === undefined) return undefined;
1339
+ if ((chat.session ?? undefined) !== (last.session ?? undefined)) return undefined;
1340
+ const model = last.model ?? chat.model ?? chat.lastModel;
1341
+ return {
1342
+ used: last.context.used,
1343
+ ...(last.context.window === undefined ? {} : { window: last.context.window }),
1344
+ ...(model === undefined || model.length === 0 ? {} : { model }),
1345
+ };
1346
+ }
1347
+
648
1348
  function sizeText(size: number): string {
649
1349
  if (size < 1024) return `${size} B`;
650
1350
  if (size < 1024 * 1024) return `${Math.round(size / 1024)} KB`;
@@ -661,21 +1361,25 @@ function attachmentLines(message: Message, shown: ReadonlySet<string>): string {
661
1361
  return `Attached files:\n${lines.join("\n")}`;
662
1362
  }
663
1363
 
1364
+ /** How {@link promptFor} separates one unanswered message from the next. */
1365
+ export const PROMPT_MESSAGE_SEPARATOR = "\n\n---\n\n";
1366
+
664
1367
  /**
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.
1368
+ * The prompt for the messages to answer, built from facts alone. Each message
1369
+ * is its own block, so two messages never read as one; a message's files
1370
+ * follow its text as paths, and `images` are the paths also given as image input.
667
1371
  */
668
1372
  export function promptFor(pending: readonly Message[], images: ReadonlySet<string> = new Set()): string {
669
1373
  const parts = pending.map((message) =>
670
- [message.text, attachmentLines(message, images)].filter((part) => part.length > 0).join("\n\n"),
1374
+ [message.text, attachmentLines(message, images), typeof message.instruction === "string" ? message.instruction : ""].filter((part) => part.length > 0).join("\n\n"),
671
1375
  );
672
- return parts.join("\n\n");
1376
+ return parts.join(PROMPT_MESSAGE_SEPARATOR);
673
1377
  }
674
1378
 
675
1379
  /** One agent's choices for a new chat: what it lists, and what a chat starts with when none is asked for. */
676
1380
  export interface AgentChoices {
677
1381
  readonly name: string;
678
- readonly models: { readonly list: readonly string[]; readonly default: string | null } | undefined;
1382
+ readonly models: HarnessModels | undefined;
679
1383
  readonly efforts: { readonly list: readonly string[]; readonly default: string | null } | undefined;
680
1384
  /** A configured model (a bot's); it is the default only for the agent that lists it. */
681
1385
  readonly preferredModel?: string | null | undefined;
@@ -702,13 +1406,22 @@ export function agentConditionals(agents: readonly AgentChoices[]): ActionArgSch
702
1406
  return { enum: [...list], ...(chosen === null || chosen === undefined ? {} : { default: chosen }) };
703
1407
  };
704
1408
  return agents.map((agent) => {
705
- const model = pick(agent.models?.list ?? [], agent.preferredModel, agent.models?.default);
1409
+ const list = modelIds(agent.models);
1410
+ const model = pick(list, agent.preferredModel, agent.models?.default);
1411
+ const info =
1412
+ agent.models?.info === undefined
1413
+ ? undefined
1414
+ : Object.fromEntries(
1415
+ Object.entries(agent.models.info).filter(([id]) => list.includes(id)),
1416
+ );
706
1417
  const effort = pick(agent.efforts?.list ?? [], agent.preferredEffort, agent.efforts?.default);
707
1418
  return {
708
1419
  if: { properties: { agent: { const: agent.name } }, required: ["agent"] },
709
1420
  then: {
710
1421
  properties: {
711
- ...(Object.keys(model).length === 0 ? {} : { model: { type: "string", ...model } }),
1422
+ ...(Object.keys(model).length === 0
1423
+ ? {}
1424
+ : { model: { type: "string", ...model, ...(info === undefined ? {} : { info }) } }),
712
1425
  ...(Object.keys(effort).length === 0 ? {} : { effort: { type: "string", ...effort } }),
713
1426
  },
714
1427
  },