@catamorphic/ai-sdk 0.0.0-stage → 0.1.0-alpha.31

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/thread.ts ADDED
@@ -0,0 +1,209 @@
1
+ import type { JsonValue } from "@catamorphic/agent-protocol";
2
+ import { type ModelMessage, modelMessageSchema } from "ai";
3
+ import { z } from "zod";
4
+
5
+ /**
6
+ * The built-in agent's native thread (ADR 0198) is its AI SDK message
7
+ * history, stored with Work as append-only entries: one `turn` entry with
8
+ * the turn's input, one `step` entry per finished model step, and a
9
+ * `turn_end` boundary a fork or a retry cuts at. Any replica, or a new
10
+ * process, folds the entries back into the same history.
11
+ */
12
+ export type ThreadEntry =
13
+ | {
14
+ v: 1;
15
+ kind: "turn";
16
+ /** The turn's native ref (its attempt id), named again by `turn_end`. */
17
+ ref: string;
18
+ input: ModelMessage[];
19
+ /** Trailing messages a retry replaced: dropped before `input`. */
20
+ drop?: number;
21
+ }
22
+ | {
23
+ v: 1;
24
+ kind: "step";
25
+ /** The model that wrote the step; another model gets it without reasoning. */
26
+ model?: string;
27
+ messages: ModelMessage[];
28
+ }
29
+ | {
30
+ v: 1;
31
+ kind: "turn_end";
32
+ ref: string;
33
+ status: "completed" | "failed" | "interrupted";
34
+ };
35
+
36
+ const entrySchema = z.discriminatedUnion("kind", [
37
+ z.object({
38
+ v: z.literal(1),
39
+ kind: z.literal("turn"),
40
+ ref: z.string(),
41
+ input: z.array(modelMessageSchema),
42
+ drop: z.number().int().min(0).optional(),
43
+ }),
44
+ z.object({
45
+ v: z.literal(1),
46
+ kind: z.literal("step"),
47
+ model: z.string().optional(),
48
+ messages: z.array(modelMessageSchema),
49
+ }),
50
+ z.object({
51
+ v: z.literal(1),
52
+ kind: z.literal("turn_end"),
53
+ ref: z.string(),
54
+ status: z.enum(["completed", "failed", "interrupted"]),
55
+ }),
56
+ ]);
57
+
58
+ /** Stored entries back into typed ones; a malformed entry fails loudly. */
59
+ export function parseThreadEntries(
60
+ entries: readonly JsonValue[],
61
+ ): ThreadEntry[] {
62
+ return entries.map((entry, index) => {
63
+ const parsed = entrySchema.safeParse(entry);
64
+ if (!parsed.success)
65
+ throw new Error(
66
+ `The stored conversation has an entry this agent cannot read (entry ${index + 1}): ${parsed.error.message}`,
67
+ );
68
+ return parsed.data;
69
+ });
70
+ }
71
+
72
+ /**
73
+ * Entries as stored, each small enough for one runner frame: a long step
74
+ * is stored message by message, and media too large for a frame (a
75
+ * screenshot a tool returned) is kept out of the stored history, said so
76
+ * in its place. The live turn still saw it.
77
+ */
78
+ export function storedEntries(entry: ThreadEntry): JsonValue[] {
79
+ const encoded = toJsonValue(entry);
80
+ if (JSON.stringify(encoded).length <= STORED_ENTRY_CHARS) return [encoded];
81
+ if (entry.kind === "step" && entry.messages.length > 1)
82
+ return entry.messages.flatMap((message) =>
83
+ storedEntries({ ...entry, messages: [message] }),
84
+ );
85
+ return [withoutLargeMedia(encoded)];
86
+ }
87
+
88
+ /** An entry's limit, which keeps the stored conversation small to reload. */
89
+ const STORED_ENTRY_CHARS = 256 * 1024;
90
+ const STORED_MEDIA_CHARS = 64 * 1024;
91
+ const MEDIA_PART_TYPES = new Set(["image", "file", "image-data", "file-data"]);
92
+
93
+ function withoutLargeMedia(value: JsonValue): JsonValue {
94
+ if (Array.isArray(value)) return value.map(withoutLargeMedia);
95
+ if (value === null || typeof value !== "object") return value;
96
+ if (
97
+ typeof value.type === "string" &&
98
+ MEDIA_PART_TYPES.has(value.type) &&
99
+ JSON.stringify(value).length > STORED_MEDIA_CHARS
100
+ )
101
+ return {
102
+ type: "text",
103
+ text: "[Media omitted from the stored conversation: it was too large to keep.]",
104
+ };
105
+ const object: { [key: string]: JsonValue } = {};
106
+ for (const [key, field] of Object.entries(value))
107
+ object[key] = withoutLargeMedia(field);
108
+ return object;
109
+ }
110
+
111
+ export interface FoldedThread {
112
+ messages: ModelMessage[];
113
+ /** Where the last turn's input ended in `messages`, when there was a turn. */
114
+ lastTurnInputEnd?: number;
115
+ }
116
+
117
+ /**
118
+ * Fold entries into the model history. Steps written by another model than
119
+ * `model` lose their reasoning parts (signed by the model that produced
120
+ * them, rejected by another); `sanitize` strips reasoning everywhere.
121
+ */
122
+ export function foldThread(input: {
123
+ entries: readonly ThreadEntry[];
124
+ model?: string;
125
+ sanitize?: boolean;
126
+ }): FoldedThread {
127
+ const messages: ModelMessage[] = [];
128
+ let lastTurnInputEnd: number | undefined;
129
+ for (const entry of input.entries) {
130
+ if (entry.kind === "turn") {
131
+ if (entry.drop) messages.splice(messages.length - entry.drop);
132
+ messages.push(...entry.input);
133
+ lastTurnInputEnd = messages.length;
134
+ } else if (entry.kind === "step") {
135
+ const foreign =
136
+ input.sanitize === true ||
137
+ (input.model !== undefined &&
138
+ entry.model !== undefined &&
139
+ entry.model !== input.model);
140
+ messages.push(
141
+ ...(foreign ? stripReasoning(entry.messages) : entry.messages),
142
+ );
143
+ }
144
+ }
145
+ return {
146
+ messages,
147
+ ...(lastTurnInputEnd === undefined ? {} : { lastTurnInputEnd }),
148
+ };
149
+ }
150
+
151
+ /**
152
+ * The entries through the end of the turn `ref` names, for a fork; undefined
153
+ * when that turn never ended in this thread.
154
+ */
155
+ export function entriesThroughTurn(
156
+ entries: readonly ThreadEntry[],
157
+ ref: string,
158
+ ): ThreadEntry[] | undefined {
159
+ for (let end = entries.length - 1; end >= 0; end -= 1) {
160
+ const entry = entries[end];
161
+ if (entry?.kind === "turn_end" && entry.ref === ref)
162
+ return entries.slice(0, end + 1);
163
+ }
164
+ return undefined;
165
+ }
166
+
167
+ /**
168
+ * Drop reasoning parts from assistant history. Reasoning output is signed
169
+ * by the model that produced it; after a mid-conversation model switch the
170
+ * new model rejects those signatures ("encrypted reasoning" errors).
171
+ */
172
+ export function stripReasoning(messages: ModelMessage[]): ModelMessage[] {
173
+ return messages.map((message) => {
174
+ if (message.role !== "assistant" || !Array.isArray(message.content))
175
+ return message;
176
+ return {
177
+ ...message,
178
+ content: message.content.filter(
179
+ (part) => part.type !== "reasoning" && part.type !== "reasoning-file",
180
+ ),
181
+ };
182
+ });
183
+ }
184
+
185
+ /**
186
+ * Any value as JSON: binary data becomes base64, URLs and dates strings,
187
+ * functions and undefined fields disappear. Model messages and tool values
188
+ * cross the runner protocol this way.
189
+ */
190
+ export function toJsonValue(value: unknown): JsonValue {
191
+ if (value === null || typeof value === "string" || typeof value === "boolean")
192
+ return value;
193
+ if (typeof value === "number") return Number.isFinite(value) ? value : null;
194
+ if (value instanceof Uint8Array) return Buffer.from(value).toString("base64");
195
+ if (value instanceof ArrayBuffer)
196
+ return Buffer.from(new Uint8Array(value)).toString("base64");
197
+ if (value instanceof URL) return value.href;
198
+ if (value instanceof Date) return value.toISOString();
199
+ if (Array.isArray(value)) return value.map(toJsonValue);
200
+ if (typeof value === "object") {
201
+ const object: { [key: string]: JsonValue } = {};
202
+ for (const [key, field] of Object.entries(value)) {
203
+ if (field === undefined || typeof field === "function") continue;
204
+ object[key] = toJsonValue(field);
205
+ }
206
+ return object;
207
+ }
208
+ return null;
209
+ }