@restatedev/agents 0.3.0 → 0.5.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.
Files changed (136) hide show
  1. package/README.md +107 -53
  2. package/dist/calls.d.ts +29 -5
  3. package/dist/calls.d.ts.map +1 -1
  4. package/dist/calls.js +77 -10
  5. package/dist/calls.js.map +1 -1
  6. package/dist/claude/index.d.ts +36 -7
  7. package/dist/claude/index.d.ts.map +1 -1
  8. package/dist/claude/index.js +232 -151
  9. package/dist/claude/index.js.map +1 -1
  10. package/dist/client.d.ts +12 -3
  11. package/dist/client.d.ts.map +1 -1
  12. package/dist/client.js.map +1 -1
  13. package/dist/common.d.ts +151 -70
  14. package/dist/common.d.ts.map +1 -1
  15. package/dist/common.js +246 -204
  16. package/dist/common.js.map +1 -1
  17. package/dist/conversation.d.ts +478 -0
  18. package/dist/conversation.d.ts.map +1 -0
  19. package/dist/conversation.js +1256 -0
  20. package/dist/conversation.js.map +1 -0
  21. package/dist/deepseek/index.d.ts +38 -5
  22. package/dist/deepseek/index.d.ts.map +1 -1
  23. package/dist/deepseek/index.js +322 -106
  24. package/dist/deepseek/index.js.map +1 -1
  25. package/dist/deepseek/persistence.d.ts +9 -3
  26. package/dist/deepseek/persistence.d.ts.map +1 -1
  27. package/dist/deepseek/persistence.js +12 -6
  28. package/dist/deepseek/persistence.js.map +1 -1
  29. package/dist/index.d.ts +2 -2
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +2 -3
  32. package/dist/index.js.map +1 -1
  33. package/dist/langgraph/checkpointer.d.ts +16 -2
  34. package/dist/langgraph/checkpointer.d.ts.map +1 -1
  35. package/dist/langgraph/checkpointer.js +133 -26
  36. package/dist/langgraph/checkpointer.js.map +1 -1
  37. package/dist/langgraph/context.d.ts +10 -0
  38. package/dist/langgraph/context.d.ts.map +1 -0
  39. package/dist/langgraph/context.js +21 -0
  40. package/dist/langgraph/context.js.map +1 -0
  41. package/dist/langgraph/errors.d.ts +16 -0
  42. package/dist/langgraph/errors.d.ts.map +1 -0
  43. package/dist/langgraph/errors.js +30 -0
  44. package/dist/langgraph/errors.js.map +1 -0
  45. package/dist/langgraph/graph.d.ts +25 -0
  46. package/dist/langgraph/graph.d.ts.map +1 -0
  47. package/dist/langgraph/graph.js +346 -0
  48. package/dist/langgraph/graph.js.map +1 -0
  49. package/dist/langgraph/index.d.ts +65 -12
  50. package/dist/langgraph/index.d.ts.map +1 -1
  51. package/dist/langgraph/index.js +227 -171
  52. package/dist/langgraph/index.js.map +1 -1
  53. package/dist/langgraph/nodes.d.ts +70 -0
  54. package/dist/langgraph/nodes.d.ts.map +1 -0
  55. package/dist/langgraph/nodes.js +145 -0
  56. package/dist/langgraph/nodes.js.map +1 -0
  57. package/dist/messages.d.ts +18 -0
  58. package/dist/messages.d.ts.map +1 -0
  59. package/dist/messages.js +182 -0
  60. package/dist/messages.js.map +1 -0
  61. package/dist/object.d.ts +65 -23
  62. package/dist/object.d.ts.map +1 -1
  63. package/dist/object.js +123 -35
  64. package/dist/object.js.map +1 -1
  65. package/dist/opencode/db.d.ts +51 -10
  66. package/dist/opencode/db.d.ts.map +1 -1
  67. package/dist/opencode/db.js +122 -34
  68. package/dist/opencode/db.js.map +1 -1
  69. package/dist/opencode/index.d.ts +105 -21
  70. package/dist/opencode/index.d.ts.map +1 -1
  71. package/dist/opencode/index.js +827 -279
  72. package/dist/opencode/index.js.map +1 -1
  73. package/dist/output.d.ts +15 -7
  74. package/dist/output.d.ts.map +1 -1
  75. package/dist/output.js +44 -26
  76. package/dist/output.js.map +1 -1
  77. package/dist/pi/index.d.ts +39 -11
  78. package/dist/pi/index.d.ts.map +1 -1
  79. package/dist/pi/index.js +281 -77
  80. package/dist/pi/index.js.map +1 -1
  81. package/dist/pi/storage.d.ts +29 -4
  82. package/dist/pi/storage.d.ts.map +1 -1
  83. package/dist/pi/storage.js +18 -6
  84. package/dist/pi/storage.js.map +1 -1
  85. package/dist/signals.d.ts +74 -4
  86. package/dist/signals.d.ts.map +1 -1
  87. package/dist/signals.js +144 -15
  88. package/dist/signals.js.map +1 -1
  89. package/dist/steering.d.ts +31 -0
  90. package/dist/steering.d.ts.map +1 -0
  91. package/dist/steering.js +45 -0
  92. package/dist/steering.js.map +1 -0
  93. package/dist/tools.d.ts +28 -0
  94. package/dist/tools.d.ts.map +1 -1
  95. package/dist/tools.js +34 -5
  96. package/dist/tools.js.map +1 -1
  97. package/package.json +42 -13
  98. package/src/calls.ts +107 -15
  99. package/src/claude/README.md +41 -20
  100. package/src/claude/index.ts +266 -178
  101. package/src/client.ts +14 -3
  102. package/src/common.ts +317 -232
  103. package/src/conversation.ts +1547 -0
  104. package/src/deepseek/README.md +78 -11
  105. package/src/deepseek/index.ts +384 -137
  106. package/src/deepseek/persistence.ts +11 -8
  107. package/src/index.ts +13 -4
  108. package/src/langgraph/README.md +115 -25
  109. package/src/langgraph/checkpointer.ts +168 -28
  110. package/src/langgraph/context.ts +27 -0
  111. package/src/langgraph/errors.ts +26 -0
  112. package/src/langgraph/graph.ts +396 -0
  113. package/src/langgraph/index.ts +326 -181
  114. package/src/langgraph/nodes.ts +243 -0
  115. package/src/messages.ts +244 -0
  116. package/src/object.ts +169 -38
  117. package/src/opencode/README.md +172 -66
  118. package/src/opencode/db.ts +204 -40
  119. package/src/opencode/index.ts +1010 -325
  120. package/src/output.ts +52 -31
  121. package/src/pi/README.md +18 -3
  122. package/src/pi/index.ts +346 -78
  123. package/src/pi/storage.ts +20 -7
  124. package/src/signals.ts +225 -19
  125. package/src/steering.ts +67 -0
  126. package/src/tools.ts +61 -8
  127. package/dist/claude/conversation.d.ts +0 -33
  128. package/dist/claude/conversation.d.ts.map +0 -1
  129. package/dist/claude/conversation.js +0 -95
  130. package/dist/claude/conversation.js.map +0 -1
  131. package/dist/log.d.ts +0 -29
  132. package/dist/log.d.ts.map +0 -1
  133. package/dist/log.js +0 -146
  134. package/dist/log.js.map +0 -1
  135. package/src/claude/conversation.ts +0 -114
  136. package/src/log.ts +0 -194
@@ -0,0 +1,1547 @@
1
+ // The conversation of an agent's key, which every framework stores the same
2
+ // way: one endless sequence of turns. A turn is one prompt (the user's
3
+ // message) and what answers it. Its id is the prompt's (`nextPromptId`: the
4
+ // invocation's, then `<id>:2`... for a handler that prompts more than once),
5
+ // so each attempt of the invocation goes on with the same turn, and a retried
6
+ // attempt finds its answer. As the Python SDK's `_conversation.py`: the same
7
+ // tables, the same rules (see docs/turns.md and docs/conversation.md).
8
+ //
9
+ // The agent's `chat` handler is exclusive on the key, and keeps the key while
10
+ // it waits, so turns never overlap: at most one turn has no answer, the
11
+ // latest, and if a newer turn finds one, the invocation that ran it is gone
12
+ // (killed, say). The newer turn closes it (`ENDED`), as does the companion if
13
+ // it notices first (`settle`), rather than finishing it.
14
+ //
15
+ // A turn is stored in two parts, in the key's database:
16
+ //
17
+ // - The transcript, `restate_agent_turns`: one row per turn, with the
18
+ // prompt (the framework's item for it), the turn's answer once it has one,
19
+ // and what a framework carries from turn to turn that is no message (the
20
+ // agent the conversation is with, its own state: `Turn.carry`).
21
+ // - The trajectories, `restate_agent_items`: every other item (the model's
22
+ // replies, tool calls and their results), each with its turn.
23
+ //
24
+ // Both share one sequence of positions, which are the ids of the messages
25
+ // the `messages` view renders (messages.ts); and each row has a `seq`, which
26
+ // grows with every row written, for a client that reads from a cursor. Rows
27
+ // are only appended, in one transaction per step, but for a reply at the end
28
+ // that is dropped (to ask the model again), one range delete; and a turn's
29
+ // answer is one update of its row.
30
+ //
31
+ // The model gets the transcript, and the whole trajectories of the latest
32
+ // `window` turns and of any turn after them that another invocation ended
33
+ // (`Walk`), in `Conversation.history`. Earlier turns are the user's message
34
+ // and the answer, as many as a budget of tokens holds; those summarized are
35
+ // one summary (`compact`). A turn loads only what it needs: the transcript
36
+ // the budget holds, and the window; a retried attempt of an answered turn
37
+ // reads only its answer.
38
+ //
39
+ // On top of it, `answerOnce` runs a prompt the same way for every framework:
40
+ // each prompt is answered once per invocation, and a stopped, refused or
41
+ // failed run is closed so that the next prompt starts afresh. A framework
42
+ // gives its `Items` (how its items say what they are) and a `Run` (its own
43
+ // loop, from the conversation to the answer, storing each step as it goes).
44
+ import * as restate from '@restatedev/sessions';
45
+ import type { Database, DatabaseReader, DatabaseWriter, Transaction } from '@restatedev/sessions';
46
+ import { definitionOf, Schema } from '@restatedev/sessions/internal';
47
+ import { forPrompt, outcomes } from './calls.ts';
48
+ import {
49
+ answering,
50
+ AttemptEnded,
51
+ aborted,
52
+ BUDGET,
53
+ CANCELLED,
54
+ type Check,
55
+ checkWindow,
56
+ cutOffResult,
57
+ ENDED,
58
+ nextPromptId,
59
+ refusalOf,
60
+ REFUSED,
61
+ settingsOf,
62
+ stopSignalOf,
63
+ storedAnswer,
64
+ SUMMARIZE,
65
+ UNANSWERED,
66
+ type Window,
67
+ } from './common.ts';
68
+
69
+ /** The transcript: one row per turn. */
70
+ export const TURNS = 'restate_agent_turns';
71
+ /** The trajectories: the items of each turn but its prompt. */
72
+ export const STEPS = 'restate_agent_items';
73
+ /** Where the conversation starts: its first position, the last `seq` given, and the summary of the earliest turns. */
74
+ export const START = 'restate_agent_conversation_start';
75
+ /** The Python SDK's snapshots, which this package does not take (docs/plan.md, D3): created, never written. */
76
+ export const SNAPSHOTS = 'restate_agent_snapshots';
77
+ /**
78
+ * The messages steered to a turn that it took ({@link Turn.steer}): which
79
+ * items of the trajectories they are, by position, and their ids, each
80
+ * stored once.
81
+ */
82
+ export const STEERED = 'restate_agent_steers';
83
+
84
+ /** The conversation's tables: the Python SDK's, step for step, so that both SDKs read each other's. */
85
+ export const SCHEMA = new Schema('restate_agents.turns', [
86
+ `CREATE TABLE ${TURNS} (
87
+ n INTEGER PRIMARY KEY,
88
+ seq INTEGER NOT NULL,
89
+ prompt TEXT NOT NULL UNIQUE,
90
+ item TEXT NOT NULL,
91
+ status TEXT,
92
+ answer TEXT,
93
+ agent TEXT,
94
+ carried TEXT,
95
+ answered_at INTEGER,
96
+ answered_seq INTEGER,
97
+ asked_at INTEGER
98
+ )`,
99
+ `CREATE INDEX ${TURNS}_seq ON ${TURNS} (seq)`,
100
+ `CREATE INDEX ${TURNS}_answered_seq ON ${TURNS} (answered_seq)`,
101
+ `CREATE TABLE ${STEPS} (
102
+ n INTEGER PRIMARY KEY,
103
+ turn INTEGER NOT NULL,
104
+ seq INTEGER NOT NULL,
105
+ item TEXT NOT NULL,
106
+ reply INTEGER,
107
+ agent TEXT
108
+ )`,
109
+ `CREATE INDEX ${STEPS}_seq ON ${STEPS} (seq)`,
110
+ `CREATE TABLE ${START} (
111
+ row INTEGER PRIMARY KEY CHECK (row = 0),
112
+ n INTEGER NOT NULL,
113
+ seq INTEGER NOT NULL,
114
+ summary TEXT,
115
+ summarized INTEGER
116
+ )`,
117
+ `CREATE TABLE ${SNAPSHOTS} (
118
+ id INTEGER PRIMARY KEY,
119
+ covers INTEGER NOT NULL,
120
+ turn INTEGER,
121
+ items TEXT NOT NULL
122
+ )`,
123
+ // Appended: a new table, which costs a view that applies it to its own session nothing.
124
+ `CREATE TABLE ${STEERED} (
125
+ n INTEGER PRIMARY KEY,
126
+ turn INTEGER NOT NULL,
127
+ id TEXT NOT NULL UNIQUE
128
+ )`,
129
+ ]);
130
+
131
+ /**
132
+ * How a turn ended: answered by its run, or closed: stopped, failed for
133
+ * good, refused by the model's provider, or ended by another invocation once
134
+ * its own was gone ({@link ENDED}).
135
+ */
136
+ export type Status = 'answered' | 'cancelled' | 'failed' | 'refused' | 'ended';
137
+
138
+ /** A tool call an item makes. */
139
+ export interface Call {
140
+ id: string;
141
+ name: string;
142
+ input: unknown;
143
+ }
144
+
145
+ /** A tool call's result an item holds: an error if `error`, or if its output starts with `Error: `. */
146
+ export interface Result {
147
+ id: string;
148
+ output: string;
149
+ error?: boolean;
150
+ }
151
+
152
+ /** Whether `result` is an error: marked as one, or `Error: <message>`. */
153
+ export const failed = (result: Result) => result.error === true || result.output.startsWith('Error: ');
154
+
155
+ /** What an item is, as {@link Items.read} reads it. */
156
+ export interface Parsed {
157
+ /** The role and text of a message; none for any other item. */
158
+ said?: ['user' | 'assistant', string];
159
+ calls?: Call[];
160
+ results?: Result[];
161
+ }
162
+
163
+ /** A framework's items: how the core stores, reads and makes them. */
164
+ export interface Items<I> {
165
+ /** `item` as it is stored: its JSON, most often. */
166
+ dump(item: I): string;
167
+ /**
168
+ * The item `dump` stored as `stored`. It throws for a row it cannot read
169
+ * (another framework's), which {@link loadItem} makes a terminal error.
170
+ */
171
+ load(stored: string): I;
172
+ /** The item of a prompt (the user's message). */
173
+ prompt(text: string): I;
174
+ /** The item of an assistant's message of `text`, from `agent` if known: it closes a run, and is an earlier turn's answer as the model sees it. */
175
+ reply(text: string, agent?: string): I;
176
+ /** The items that give each call its result, as text: they close a run's cut-off calls. */
177
+ results(results: [Call, string][]): I[];
178
+ /** What `item` says, and the tool calls and results it holds. */
179
+ read(item: I): Parsed;
180
+ /** The summary of the earliest turns in the framework's own form; by default a user's message and "Understood." */
181
+ summary?(text: string): I[];
182
+ /**
183
+ * The item of the message `steerId` steered to a turn, with `text`, to
184
+ * tell it apart from a prompt in the framework's runs (LangGraph's has
185
+ * the id `steer:<steerId>`); by default, a prompt's item.
186
+ */
187
+ steered?(text: string, steerId: string): I;
188
+ /**
189
+ * For a framework whose history is in a store of its own that the turn is
190
+ * copied from after the fact (OpenCode's): bring that store to the turn's
191
+ * end, and copy what it has of the turn into it, before the turn is
192
+ * closed with `status`. `answerOnce` and `settle` call it before each
193
+ * close, so that the framework's store is closed first, then the copy,
194
+ * then the turn. A framework whose copy is in its own transaction (pi,
195
+ * DeepSeek) has none.
196
+ */
197
+ settleOwn?(ctx: restate.SessionContext, turn: Turn<I>, status: Status): Promise<void>;
198
+ /** For a framework with a database of its own beside `ctx.db`: forget it, as `clear` empties the key's. */
199
+ erase?(ctx: restate.SessionContext): Promise<void>;
200
+ }
201
+
202
+ /** What the user's message with the summary of the earliest turns starts with. */
203
+ export const SUMMARY = 'A summary of our conversation so far:\n\n';
204
+
205
+ /** The items that give the model `summary`, of the earliest turns: `items.summary`'s, if it has one. */
206
+ export const summaryItems = <I>(items: Items<I>, summary: string): I[] =>
207
+ items.summary ? items.summary(summary) : [items.prompt(SUMMARY + summary), items.reply('Understood.')];
208
+
209
+ /** The item of the message `steerId` steered to a turn, with `text`: `items.steered`'s, if it has one. */
210
+ export const steeredItem = <I>(items: Items<I>, text: string, steerId: string): I =>
211
+ items.steered ? items.steered(text, steerId) : items.prompt(text);
212
+
213
+ /** An item of the conversation, with what it is part of. */
214
+ export interface Entry<I> {
215
+ /** Its position: the conversation is ordered by it. */
216
+ n: number;
217
+ item: I;
218
+ /** The id of the prompt it is, if it is one: it starts a turn. */
219
+ prompt?: string;
220
+ /** On a prompt: its turn's answer, once it has one. */
221
+ answer?: string;
222
+ /** The id of the model's reply it is part of: the position of the reply's first item. */
223
+ reply?: number;
224
+ /** The agent that gave the reply; on a prompt, the agent the conversation is with after its turn. */
225
+ agent?: string;
226
+ /** What `item` is, read once (`Items.read`), as the conversation loads or appends it. */
227
+ parsed?: Parsed;
228
+ /** The position of its turn's prompt. */
229
+ turn?: number;
230
+ /** On a prompt: the framework's state as of its turn's end, if it carries one. */
231
+ carried?: string;
232
+ /** On a prompt: how its turn ended, once it did. */
233
+ status?: Status;
234
+ /** On a prompt: the position of its turn's answer, its last message of the assistant. */
235
+ answeredAt?: number;
236
+ /** On a prompt: the `seq` given as its turn was answered. */
237
+ answeredSeq?: number;
238
+ /** On a prompt: when its turn's row was stored, in Unix milliseconds. */
239
+ askedAt?: number;
240
+ /** The id of the steered message it is, if it is one: a message of the user that its turn took at a step. */
241
+ steer?: string;
242
+ /**
243
+ * On a prompt of the transcript: the messages steered to its turn that it
244
+ * took, in order, which the model sees between its message and its answer
245
+ * once the turn is before the window.
246
+ */
247
+ steers?: Entry<I>[];
248
+ }
249
+
250
+ /** What `entry` says, read once. */
251
+ const parsedOf = <I>(items: Items<I>, entry: Entry<I>) => (entry.parsed ??= items.read(entry.item));
252
+
253
+ /**
254
+ * The size of `turn` (a prompt of the transcript) as the model sees it before
255
+ * the window, in characters: its message, the messages steered to it, and
256
+ * its answer.
257
+ */
258
+ const turnSize = <I>(items: Items<I>, turn: Entry<I>) =>
259
+ [turn, ...(turn.steers ?? [])].reduce((sum, e) => sum + (parsedOf(items, e).said?.[1] ?? '').length, 0) +
260
+ (turn.answer ?? '').length;
261
+
262
+ /** Where a conversation starts: its first position, the last `seq` given, and the summary of the earliest turns. */
263
+ export interface Start {
264
+ n: number;
265
+ seq: number;
266
+ summary?: string;
267
+ /** The position of the first turn after the summary: those before it are the summary, as the model sees them. */
268
+ summarized?: number;
269
+ }
270
+
271
+ const int = (value: unknown) => (value === null || value === undefined ? undefined : Number(value));
272
+ const str = (value: unknown) =>
273
+ value === null || value === undefined ? undefined : typeof value === 'string' ? value : JSON.stringify(value);
274
+
275
+ /** Where the conversation in `db` starts, as `clear`, drops and summaries left it. */
276
+ export async function startOf(db: DatabaseReader): Promise<Start> {
277
+ const row = await db.get(`SELECT n, seq, summary, summarized FROM ${START}`);
278
+ if (!row) return { n: 0, seq: 0 };
279
+ return { n: int(row.n) ?? 0, seq: int(row.seq) ?? 0, summary: str(row.summary), summarized: int(row.summarized) };
280
+ }
281
+
282
+ /** The last position of `db`'s rows (none if it has none), and the last `seq` they have (or 0). */
283
+ export async function lastOf(db: DatabaseReader): Promise<[last: number | undefined, seq: number]> {
284
+ // One subquery per maximum: each reads the end of its b-tree, where one SELECT of several scans the table.
285
+ const [[turn, turnSeq, answeredSeq, step, stepSeq]] = (await db.values(
286
+ `SELECT (SELECT MAX(n) FROM ${TURNS}), (SELECT MAX(seq) FROM ${TURNS}), (SELECT MAX(answered_seq) FROM ${TURNS}), ` +
287
+ `(SELECT MAX(n) FROM ${STEPS}), (SELECT MAX(seq) FROM ${STEPS})`,
288
+ )) as unknown[][] as [[unknown, unknown, unknown, unknown, unknown]];
289
+ const positions = [turn, step].filter((n) => n !== null && n !== undefined).map(Number);
290
+ const seqs = [turnSeq, answeredSeq, stepSeq].filter((s) => s !== null && s !== undefined).map(Number);
291
+ return [positions.length > 0 ? Math.max(...positions) : undefined, seqs.length > 0 ? Math.max(...seqs) : 0];
292
+ }
293
+
294
+ /** Where the next conversation starts, past the positions and `seq` of the one in `db`. */
295
+ export async function nextStart(db: DatabaseReader): Promise<Start> {
296
+ const start = await startOf(db);
297
+ const [last, seq] = await lastOf(db);
298
+ return { n: last === undefined ? start.n : last + 1, seq: Math.max(start.seq, seq) };
299
+ }
300
+
301
+ /** Store `start` as where the conversation starts: in the transaction of `clear` that emptied it, say. */
302
+ export async function restart(tx: DatabaseWriter, start: Start) {
303
+ await tx.execute(`INSERT OR REPLACE INTO ${START} (row, n, seq, summary, summarized) VALUES (0, ?, ?, ?, ?)`, [
304
+ start.n,
305
+ start.seq,
306
+ start.summary ?? null,
307
+ start.summarized ?? null,
308
+ ]);
309
+ }
310
+
311
+ /** The stored answer of prompt `promptId`, and how its turn ended, if it has one: one read, of the turn's row. */
312
+ export async function answerIn(
313
+ db: DatabaseReader,
314
+ promptId: string,
315
+ ): Promise<{ answer: string; status: Status } | undefined> {
316
+ const row = await db.get(`SELECT answer, status FROM ${TURNS} WHERE prompt = ?`, [promptId]);
317
+ const answer = row ? str(row.answer) : undefined;
318
+ return answer === undefined ? undefined : { answer, status: (str(row!.status) ?? 'answered') as Status };
319
+ }
320
+
321
+ /**
322
+ * Of the turns from the latest back, which are in a window of `size` turns:
323
+ * the `size` latest turns their framework answered, and the turns after them
324
+ * it did not: the one being answered (only the latest can have no answer),
325
+ * and those another invocation ended (`ended`), whose framework never
326
+ * finished them, so that what they carried is a guess and their own rows say
327
+ * what happened.
328
+ */
329
+ class Walk {
330
+ #seen = 0;
331
+ #done = false;
332
+ readonly size: number;
333
+ constructor(size: number) {
334
+ this.size = size;
335
+ }
336
+
337
+ /** Whether the next turn back, which ended as `status` (or not yet), is in the window. */
338
+ holds(status: Status | undefined) {
339
+ if (this.#done) return false;
340
+ if (status === undefined || status === 'ended') return true;
341
+ if (this.#seen === this.size) {
342
+ this.#done = true;
343
+ return false;
344
+ }
345
+ this.#seen += 1;
346
+ this.#done = this.#seen === this.size;
347
+ return true;
348
+ }
349
+ }
350
+
351
+ /** The index in `turns` (prompts, in order) of the first turn in `window` (see {@link Walk}). */
352
+ export function windowStart<I>(turns: readonly Entry<I>[], window: Window) {
353
+ if (window === 'all') return 0;
354
+ const walk = new Walk(window);
355
+ let first = turns.length;
356
+ while (first > 0 && walk.holds(turns[first - 1]!.status)) first -= 1;
357
+ return first;
358
+ }
359
+
360
+ /** Runs its bodies one after another: writes that come at once (parallel tool calls') each get positions of their own. */
361
+ class Lock {
362
+ #tail: Promise<unknown> = Promise.resolve();
363
+ run<T>(body: () => Promise<T>): Promise<T> {
364
+ const done = this.#tail.then(body);
365
+ this.#tail = done.catch(() => {});
366
+ return done;
367
+ }
368
+ }
369
+
370
+ /** What a conversation and its turns share: the database, the next position and `seq`, and the writes' lock. */
371
+ class Ledger<I> {
372
+ /** The latest turn, if loaded whole: the only one that may be written. */
373
+ latest: Turn<I> | undefined;
374
+ /** Whether {@link Conversation.seal} closed the conversation to writes. */
375
+ closed = false;
376
+ readonly lock = new Lock();
377
+ /** The ids of the tool calls made in the loaded turns. */
378
+ readonly ids = new Set<string>();
379
+ /** Whether a call's id an earlier call has was logged: once is enough. */
380
+ warned = false;
381
+
382
+ readonly db: Database;
383
+ readonly items: Items<I>;
384
+ start: Start;
385
+ /** The turns' prompts, in order: the latest is the latest turn's. */
386
+ readonly transcript: Entry<I>[];
387
+ /** The next position to give. */
388
+ next: number;
389
+ /** The last `seq` given. */
390
+ seq: number;
391
+
392
+ constructor(db: Database, items: Items<I>, start: Start, transcript: Entry<I>[], next: number, seq: number) {
393
+ this.db = db;
394
+ this.items = items;
395
+ this.start = start;
396
+ this.transcript = transcript;
397
+ this.next = next;
398
+ this.seq = seq;
399
+ }
400
+
401
+ /** Note a tool call's id, and log one that an earlier call has (once). */
402
+ called(callId: string) {
403
+ if (this.ids.has(callId) && !this.warned) {
404
+ this.warned = true;
405
+ console.warn(
406
+ `Tool call id ${JSON.stringify(callId)} is used by more than one call: the conversation matches results to calls by id, so a call may be taken as answered by another's result`,
407
+ );
408
+ }
409
+ this.ids.add(callId);
410
+ }
411
+
412
+ checkOpen() {
413
+ if (this.closed) throw new Error('the run was stopped: it stores nothing more');
414
+ }
415
+
416
+ /** The agent and the framework's state that the latest answered turn left. */
417
+ carried(): [agent: string | undefined, carried: string | undefined] {
418
+ const latest = this.transcript.findLast((turn) => turn.answer !== undefined);
419
+ return latest ? [latest.agent, latest.carried] : [undefined, undefined];
420
+ }
421
+ }
422
+
423
+ /** The index of the first of `entries` (by position) at `n` or after. */
424
+ const bisect = <I>(entries: readonly Entry<I>[], n: number) => {
425
+ let low = 0;
426
+ let high = entries.length;
427
+ while (low < high) {
428
+ const mid = (low + high) >> 1;
429
+ if (entries[mid]!.n < n) low = mid + 1;
430
+ else high = mid;
431
+ }
432
+ return low;
433
+ };
434
+
435
+ /**
436
+ * One turn of the conversation: its prompt, and what its run stored to
437
+ * answer it. A turn's rows are read and written here, and only here: its
438
+ * open tool calls, its replies and its final reply are this turn's, never
439
+ * another's. Only the latest turn, while it has no answer, can be written:
440
+ * by its own run, or by whoever closes it ({@link Turn.close}), once its run
441
+ * is gone.
442
+ */
443
+ export class Turn<I> {
444
+ #ledger: Ledger<I>;
445
+ #entries: Entry<I>[] = [];
446
+ /** The tool calls' results, by their calls' ids. */
447
+ #results = new Map<string, Result>();
448
+ /** The tool calls without a result, in the order they were made: each, even if ids repeat. */
449
+ #open: Call[] = [];
450
+ /** What the turn carries to the turns after it, stored with its answer. */
451
+ #carried: { agent?: string; carried?: string } = {};
452
+ /**
453
+ * Whether the turn is being closed: its run (left running once stopped,
454
+ * as a promise cannot be cancelled) stores nothing more.
455
+ */
456
+ #fenced = false;
457
+
458
+ /** The turn's row: its prompt, and once it has them, its status, answer and what it carried. */
459
+ readonly prompt: Entry<I>;
460
+
461
+ /**
462
+ * What the model is told after the turn's prompt, where it reads it last
463
+ * (`output`'s ask for JSON), and never stored: the conversation keeps the
464
+ * prompt as it was asked. `history()` adds it to the prompt; a framework
465
+ * that keeps its own history adds it to the prompt it is given.
466
+ */
467
+ reminder: string | undefined;
468
+
469
+ constructor(ledger: Ledger<I>, prompt: Entry<I>, items: Entry<I>[] = []) {
470
+ this.#ledger = ledger;
471
+ this.prompt = prompt;
472
+ this.#add([prompt, ...items]);
473
+ }
474
+
475
+ /** The turn's id: its prompt's. */
476
+ get id() {
477
+ return this.prompt.prompt!;
478
+ }
479
+
480
+ /** The turn's position: its prompt's, the id of its user's message. */
481
+ get n() {
482
+ return this.prompt.n;
483
+ }
484
+
485
+ /** How the turn ended, or none while it is being answered. */
486
+ get status() {
487
+ return this.prompt.status;
488
+ }
489
+
490
+ /** The turn's answer, once it has one: the run's, or the note that closed it. */
491
+ get answer() {
492
+ return this.prompt.answer;
493
+ }
494
+
495
+ /** The turn's entries, in order: its prompt, then its items. */
496
+ get entries(): readonly Entry<I>[] {
497
+ return this.#entries;
498
+ }
499
+
500
+ /** The turn's items, in order: the model's replies, the tool calls' results... */
501
+ get items(): readonly Entry<I>[] {
502
+ return this.#entries.slice(1);
503
+ }
504
+
505
+ #add(entries: Entry<I>[]) {
506
+ for (const entry of entries) {
507
+ entry.parsed = this.#ledger.items.read(entry.item);
508
+ entry.turn = this.n;
509
+ this.#index(entry);
510
+ }
511
+ // In position order, also when a framework's copy into the turn committed between this write and its return.
512
+ this.#entries.splice(bisect(this.#entries, entries[0]?.n ?? Number.MAX_SAFE_INTEGER), 0, ...entries);
513
+ }
514
+
515
+ #index(entry: Entry<I>, note = true) {
516
+ for (const call of entry.parsed?.calls ?? []) {
517
+ if (note) this.#ledger.called(call.id);
518
+ if (!this.#results.has(call.id)) this.#open.push(call);
519
+ }
520
+ for (const result of entry.parsed?.results ?? []) {
521
+ this.#results.set(result.id, result);
522
+ if (this.#open.some((call) => call.id === result.id)) {
523
+ this.#open = this.#open.filter((call) => call.id !== result.id);
524
+ }
525
+ }
526
+ }
527
+
528
+ // Reading.
529
+
530
+ /** The ids of the model's replies in the turn, in order. */
531
+ replies(): number[] {
532
+ return [...new Set(this.#entries.flatMap((e) => (e.reply === undefined ? [] : [e.reply])))].toSorted(
533
+ (a, b) => a - b,
534
+ );
535
+ }
536
+
537
+ /** The id of the model's reply the turn ends with, if it ends with one. */
538
+ lastReply(): number | undefined {
539
+ return this.#entries.at(-1)!.reply;
540
+ }
541
+
542
+ /** The entries of the model's reply `reply`, in order: they follow one another, from position `reply`. */
543
+ replyEntries(reply: number): readonly Entry<I>[] {
544
+ const first = bisect(this.#entries, reply);
545
+ let end = first;
546
+ while (end < this.#entries.length && this.#entries[end]!.reply === reply) end += 1;
547
+ return this.#entries.slice(first, end);
548
+ }
549
+
550
+ /** The agent that gave the model's reply `reply`. */
551
+ agentOf(reply: number) {
552
+ return this.replyEntries(reply)[0]?.agent;
553
+ }
554
+
555
+ /** The text of the model's reply the turn ends with, if it ends the run: text, and no tool calls. */
556
+ finalReply(): string | undefined {
557
+ const reply = this.lastReply();
558
+ if (reply === undefined) return undefined;
559
+ const entries = this.replyEntries(reply);
560
+ if (entries.some((e) => (e.parsed?.calls ?? []).length > 0)) return undefined;
561
+ return entries.findLast((e) => e.parsed?.said !== undefined)?.parsed?.said?.[1];
562
+ }
563
+
564
+ /** The turn's tool calls without a result, in the order they were made. */
565
+ openCalls(): Call[] {
566
+ return [...this.#open];
567
+ }
568
+
569
+ /**
570
+ * The turn's latest message of the user that asks for its answer: its
571
+ * prompt, or the message that asked again ({@link askAgain}). A framework
572
+ * that runs from a message of its own runs from this one. A steered
573
+ * message ({@link steer}) is not one: the model reads it within the run,
574
+ * which goes on from the same ask.
575
+ */
576
+ latestAsk(): Entry<I> {
577
+ return this.items.findLast((e) => e.steer === undefined && e.parsed?.said?.[0] === 'user') ?? this.prompt;
578
+ }
579
+
580
+ /** The messages steered to the turn that it took, in order. */
581
+ steered(): Entry<I>[] {
582
+ return this.items.filter((e) => e.steer !== undefined);
583
+ }
584
+
585
+ /** Whether the turn's tool call `callId` has a result. */
586
+ hasResult(callId: string) {
587
+ return this.#results.has(callId);
588
+ }
589
+
590
+ /** Whether tool call `callId` has its result: not an error, unless it is `failed`, its own. */
591
+ stored(callId: string, failedWith?: string) {
592
+ const result = this.#results.get(callId);
593
+ return result !== undefined && (!failed(result) || result.output === failedWith);
594
+ }
595
+
596
+ // Writing: only the latest turn, while it has no answer.
597
+
598
+ /** Append `items` (a tool's results, say) to the turn, in one transaction; appends at once are each stored after the ones before. */
599
+ async append(...items: I[]): Promise<void> {
600
+ await this.#insert((n) => items.map((item, i) => ({ n: n + i, item })));
601
+ }
602
+
603
+ /** Append the model's reply, of `items` (given by `agent`), to the turn, and return its id. */
604
+ appendReply(items: I[], agent?: string): Promise<number> {
605
+ return this.#insert((n) => items.map((item, i) => ({ n: n + i, item, reply: n, agent })));
606
+ }
607
+
608
+ /**
609
+ * Ask the model again within the turn, with `text`: a message of the user
610
+ * that is a step of the turn, not a turn of its own (the transcript, and
611
+ * the summary view, have the turn's prompt and its answer).
612
+ */
613
+ async askAgain(text: string) {
614
+ await this.append(this.#ledger.items.prompt(text));
615
+ }
616
+
617
+ /**
618
+ * Store the steered `messages` that the turn has not taken yet as steps of
619
+ * the turn, and return their items. Each is stored once, by its id, as a
620
+ * message of the user (as `Items.steered` makes it) after the turn's steps
621
+ * before: the model reads it in its next request, and in every turn's
622
+ * history after, between the turn's message and its answer. `taken` adds
623
+ * what goes out with the transaction that stores them (the companion's
624
+ * `taken`), which commits once.
625
+ *
626
+ * `going` tells whether the turn still goes on: once it has the ledger, a
627
+ * turn that stopped meanwhile takes none, which are then answered as turns
628
+ * of their own. A store under way finishes even if the turn stops: the
629
+ * turn then closes after it, at the positions after its messages, and the
630
+ * messages are its own (stopped with it).
631
+ */
632
+ async steer(
633
+ messages: readonly { id: string; text: string }[],
634
+ taken: (tx: Transaction, ids: string[]) => void,
635
+ going: () => boolean,
636
+ ): Promise<I[]> {
637
+ const held = new Set(this.steered().map((e) => e.steer));
638
+ const wanted = [...new Map(messages.filter((m) => !held.has(m.id)).map((m) => [m.id, m])).values()];
639
+ if (wanted.length === 0) return [];
640
+ const ledger = this.#ledger;
641
+ return ledger.lock.run(async () => {
642
+ if (!going()) return [];
643
+ this.#checkWritable();
644
+ // The database, not the turn: an id is stored once in the conversation, by whichever turn took it.
645
+ const stored = await steersStored(
646
+ ledger.db,
647
+ wanted.map((m) => m.id),
648
+ );
649
+ const fresh = wanted.filter((m) => !stored.has(m.id));
650
+ if (fresh.length === 0) return [];
651
+ let added: Entry<I>[] = [];
652
+ // The positions and seqs taken as the write runs, as `#insert` takes them.
653
+ await ledger.db.transaction(async (tx) => {
654
+ const n = ledger.next;
655
+ added = fresh.map((m, i) => ({ n: n + i, item: steeredItem(ledger.items, m.text, m.id), steer: m.id }));
656
+ for (const [i, e] of added.entries()) {
657
+ await tx.execute(INSERT_STEP, [e.n, this.n, ledger.seq + i + 1, ledger.items.dump(e.item), null, null]);
658
+ await tx.execute(INSERT_STEERED, [e.n, this.n, e.steer!]);
659
+ }
660
+ taken(
661
+ tx,
662
+ fresh.map((m) => m.id),
663
+ );
664
+ ledger.seq += added.length;
665
+ ledger.next = n + added.length;
666
+ });
667
+ this.#add(added);
668
+ // The transcript's entry of the turn has them too, as the next turn loads it: for its size, say.
669
+ (this.prompt.steers ??= []).push(...added);
670
+ return added.map((e) => e.item);
671
+ });
672
+ }
673
+
674
+ /**
675
+ * Keep what the turn carries to the turns after it, stored with its
676
+ * answer: `agent`, the agent the conversation is with (by default, its
677
+ * latest reply's, else the previous turn's); `state`, the framework's own,
678
+ * as text (by default, the previous turn's).
679
+ */
680
+ carry({ agent, state }: { agent?: string; state?: string }) {
681
+ if (agent !== undefined) this.#carried.agent = agent;
682
+ if (state !== undefined) this.#carried.carried = state;
683
+ }
684
+
685
+ /**
686
+ * Drop the turn's reply `reply`, and what came after it, to ask the model
687
+ * again: one range delete. The positions are given again, so the new
688
+ * reply's messages take the dropped ones' ids; the `seq` is kept, so that
689
+ * a client's cursor still sees them. A steered message after the reply is
690
+ * dropped too: it is no longer the turn's, so the agent's `steered`
691
+ * answers it as a turn of its own.
692
+ */
693
+ async drop(reply: number) {
694
+ this.#checkWritable();
695
+ if (!this.replies().includes(reply)) throw new Error(`turn ${this.id} has no reply ${reply}`);
696
+ const ledger = this.#ledger;
697
+ await ledger.lock.run(async () => {
698
+ this.#checkWritable();
699
+ const start = { ...ledger.start, seq: ledger.seq };
700
+ await ledger.db.transaction(async (tx) => {
701
+ await tx.execute(`DELETE FROM ${STEPS} WHERE n >= ?`, [reply]);
702
+ await tx.execute(`DELETE FROM ${STEERED} WHERE n >= ?`, [reply]);
703
+ await restart(tx, start);
704
+ });
705
+ ledger.start = start;
706
+ ledger.next = Math.min(ledger.next, reply);
707
+ if (this.prompt.steers) this.prompt.steers = this.prompt.steers.filter((e) => e.n < reply);
708
+ const cut = bisect(this.#entries, reply);
709
+ const kept = this.#entries.slice(0, cut);
710
+ // The dropped calls are not made: their ids may be made again, by the reply that replaces them.
711
+ for (const entry of this.#entries.slice(cut))
712
+ for (const call of entry.parsed?.calls ?? []) ledger.ids.delete(call.id);
713
+ for (const entry of kept) for (const call of entry.parsed?.calls ?? []) ledger.ids.add(call.id);
714
+ this.#entries = kept;
715
+ this.#results = new Map();
716
+ this.#open = [];
717
+ for (const entry of kept) this.#index(entry, false);
718
+ });
719
+ }
720
+
721
+ /**
722
+ * Store the turn's `answer`, how it ended (`status`) and what it carries,
723
+ * in one update of its row. The answer's message is the assistant's
724
+ * message the turn ends with; a turn that ends otherwise gets `answer` as
725
+ * its reply first, and an empty answer gets none.
726
+ */
727
+ async answered(answer: string, status: Status = 'answered') {
728
+ let at = this.#answerMessage();
729
+ if (at === undefined && answer.trim()) {
730
+ const agent = this.#agent();
731
+ at = await this.appendReply([this.#ledger.items.reply(answer, agent)], agent);
732
+ }
733
+ const ledger = this.#ledger;
734
+ await ledger.lock.run(async () => {
735
+ this.#checkWritable();
736
+ const agent = this.#agent();
737
+ const carried = 'carried' in this.#carried ? this.#carried.carried : ledger.carried()[1];
738
+ let seq = ledger.seq + 1;
739
+ // Its seq taken as the write runs, as `#insert` takes its own.
740
+ await ledger.db.transaction(async (tx) => {
741
+ seq = ledger.seq + 1;
742
+ await tx.execute(ANSWER, [status, answer, agent ?? null, carried ?? null, at ?? null, seq, this.n]);
743
+ ledger.seq = seq;
744
+ });
745
+ Object.assign(this.prompt, { status, answer, agent, carried, answeredAt: at, answeredSeq: seq });
746
+ });
747
+ }
748
+
749
+ /**
750
+ * The position of the assistant's message the turn ends with, if it ends
751
+ * with one: a message without tool calls, with no call nor result after
752
+ * it (items that are neither, a reasoning item say, do not count).
753
+ */
754
+ #answerMessage(): number | undefined {
755
+ for (const entry of this.items.toReversed()) {
756
+ const { said, calls = [], results = [] } = entry.parsed ?? {};
757
+ if (said === undefined && calls.length === 0 && results.length === 0) continue;
758
+ if (said?.[0] === 'assistant' && calls.length === 0) return entry.n;
759
+ return undefined;
760
+ }
761
+ return undefined;
762
+ }
763
+
764
+ /** The agent the turn is with: the one it carries, else its latest reply's, else the previous turn's. */
765
+ #agent(): string | undefined {
766
+ const replied = this.#entries.findLast((e) => e.reply !== undefined)?.agent;
767
+ return this.#carried.agent || replied || this.#ledger.carried()[0];
768
+ }
769
+
770
+ /**
771
+ * Close the turn (stopped, refused, failed, or ended once its invocation is
772
+ * gone) with `note`. Each tool call without a result gets one: the error
773
+ * its Restate call answered with, a note that it did happen if it
774
+ * answered, or else `note` ({@link cutOffResult}). Then `note` is the
775
+ * turn's last message, and its answer. The calls' outcomes are those of the
776
+ * invocation that made the turn's prompt: this one, or an earlier one whose
777
+ * calls are still stored. A turn with its answer has nothing to close.
778
+ */
779
+ async close(ctx: restate.SessionContext, status: Status, note: string) {
780
+ if (this.status !== undefined) return;
781
+ // The run stores nothing more: a write it makes from here fails. Those
782
+ // under way are stored first, so that the calls they make are open here,
783
+ // and the results they hold are not.
784
+ this.#fenced = true;
785
+ const ledger = this.#ledger;
786
+ await ledger.lock.run(async () => {});
787
+ if (this.status !== undefined) return;
788
+ const { items } = ledger;
789
+ const calls = this.openCalls();
790
+ const returned = await outcomes(
791
+ ctx,
792
+ calls.map((call) => call.id),
793
+ invocationOf(this.id),
794
+ this.id,
795
+ );
796
+ const closing = [
797
+ ...items.results(calls.map((call) => [call, cutOffResult(returned, call.id, note)])),
798
+ items.reply(note),
799
+ ];
800
+ // The results, the note and the answer in one transaction: a crash
801
+ // between them would close the turn again, with a second note.
802
+ await ledger.lock.run(async () => {
803
+ this.#checkWritable(true);
804
+ const n = ledger.next;
805
+ const seq = ledger.seq;
806
+ const added: Entry<I>[] = closing.map((item, i) => ({ n: n + i, item }));
807
+ const at = n + added.length - 1; // the note: the turn's last message, and its answer
808
+ const answeredSeq = seq + added.length + 1;
809
+ const agent = this.#agent();
810
+ const carried = 'carried' in this.#carried ? this.#carried.carried : ledger.carried()[1];
811
+ await ledger.db.transaction(async (tx) => {
812
+ for (const [i, e] of added.entries()) {
813
+ await tx.execute(INSERT_STEP, [e.n, this.n, seq + i + 1, items.dump(e.item), null, null]);
814
+ }
815
+ await tx.execute(ANSWER, [status, note, agent ?? null, carried ?? null, at, answeredSeq, this.n]);
816
+ });
817
+ ledger.next = n + added.length;
818
+ ledger.seq = answeredSeq;
819
+ this.#add(added);
820
+ Object.assign(this.prompt, { status, answer: note, agent, carried, answeredAt: at, answeredSeq });
821
+ });
822
+ }
823
+
824
+ /** Whether the turn's run can write it: the latest, without an answer, not being closed, of a conversation not sealed. */
825
+ get writable() {
826
+ return !this.#ledger.closed && !this.#fenced && this.#ledger.latest === this && this.status === undefined;
827
+ }
828
+
829
+ /**
830
+ * Copy a framework's own messages into the turn, in `tx`, a transaction of
831
+ * the framework's own store (its write of these messages): the rows commit
832
+ * with it, so the copy is made once, however often the attempt crashes.
833
+ * Each of `items` is a reply of the model (`reply`, from `agent`), a
834
+ * message steered to the turn that its framework placed (`steer`, its id:
835
+ * stored once, in the steered messages' table too), or another item (a
836
+ * tool's result). For a framework that keeps its own history. It cannot wait for the turn's other writes inside `tx`, which
837
+ * holds the database: it takes its positions, and adds its entries, at
838
+ * once, so that a close after it sees them and writes after them. A turn
839
+ * being closed (or closed) takes no copy: its close says how it ended.
840
+ * Whether it copied.
841
+ */
842
+ async copyIn(
843
+ tx: DatabaseWriter,
844
+ items: { item: I; reply?: boolean; agent?: string; steer?: string }[],
845
+ ): Promise<boolean> {
846
+ if (!this.writable) return false;
847
+ const ledger = this.#ledger;
848
+ const n = ledger.next;
849
+ const seq = ledger.seq;
850
+ const added: Entry<I>[] = items.map(({ item, reply, agent, steer }, i) => ({
851
+ n: n + i,
852
+ item,
853
+ ...(reply ? { reply: n + i, agent } : {}),
854
+ ...(steer === undefined ? {} : { steer }),
855
+ }));
856
+ // A rolled back transaction fails its attempt, whose state goes with it.
857
+ ledger.next = n + added.length;
858
+ ledger.seq += added.length;
859
+ this.#add(added);
860
+ const steered = added.filter((e) => e.steer !== undefined);
861
+ if (steered.length > 0) (this.prompt.steers ??= []).push(...steered);
862
+ for (const [i, e] of added.entries()) {
863
+ await tx.execute(INSERT_STEP, [
864
+ e.n,
865
+ this.n,
866
+ seq + i + 1,
867
+ ledger.items.dump(e.item),
868
+ e.reply ?? null,
869
+ e.agent ?? null,
870
+ ]);
871
+ if (e.steer !== undefined) await tx.execute(INSERT_STEERED, [e.n, this.n, e.steer]);
872
+ }
873
+ return true;
874
+ }
875
+
876
+ /**
877
+ * Refuse a write unless this is the latest turn, without an answer: only
878
+ * its run (or its close, `byClose`) writes it, and its run not once the
879
+ * turn is being closed.
880
+ */
881
+ #checkWritable(byClose = false) {
882
+ this.#ledger.checkOpen();
883
+ if (!byClose && this.#fenced) throw new Error('the run was stopped: it stores nothing more');
884
+ if (this.#ledger.latest !== this || this.status !== undefined) {
885
+ throw new Error(`turn ${this.id} is not the turn being answered: only that turn is written`);
886
+ }
887
+ }
888
+
889
+ /** Store the entries `made` makes from the next position, and return that position. */
890
+ #insert(made: (n: number) => Entry<I>[]): Promise<number> {
891
+ const ledger = this.#ledger;
892
+ return ledger.lock.run(async () => {
893
+ this.#checkWritable();
894
+ let n = ledger.next;
895
+ let added: Entry<I>[] = [];
896
+ // The positions and seqs taken as the write runs: a framework's copy
897
+ // into the turn (`copyIn`, in a transaction of its own, which this one
898
+ // may wait for) takes those after them, so that they go in the order
899
+ // the rows commit in, as a follower's cursor needs.
900
+ await ledger.db.transaction(async (tx) => {
901
+ n = ledger.next;
902
+ added = made(n);
903
+ for (const [i, e] of added.entries()) {
904
+ await tx.execute(INSERT_STEP, [
905
+ e.n,
906
+ this.n,
907
+ ledger.seq + i + 1,
908
+ ledger.items.dump(e.item),
909
+ e.reply ?? null,
910
+ e.agent ?? null,
911
+ ]);
912
+ }
913
+ ledger.seq += added.length;
914
+ ledger.next = n + added.length;
915
+ });
916
+ this.#add(added);
917
+ return n;
918
+ });
919
+ }
920
+ }
921
+
922
+ /** How many turns of the transcript a load reads at a time, from the latest back. */
923
+ export const PAGE = 64;
924
+
925
+ /**
926
+ * The item stored as `stored`, or a terminal error: a retry would read the
927
+ * same row again. A row that `items` cannot read was stored by an agent of
928
+ * another framework under the same name, or by another version of this one.
929
+ */
930
+ export function loadItem<I>(items: Items<I>, stored: string): I {
931
+ try {
932
+ return items.load(stored);
933
+ } catch (error) {
934
+ const reason = error instanceof Error ? `${error.name}: ${error.message}` : JSON.stringify(error);
935
+ throw new restate.TerminalError(
936
+ 'This conversation holds a message that this agent cannot read (one stored by an agent of another ' +
937
+ `framework under the same name, or by another version of this one?): ${reason}`,
938
+ );
939
+ }
940
+ }
941
+
942
+ /** The columns of the transcript a load reads. */
943
+ const TRANSCRIPT = `SELECT n, prompt, item, status, answer, agent, carried, answered_at, answered_seq, asked_at FROM ${TURNS}`;
944
+
945
+ /** A row of {@link TRANSCRIPT} as a prompt's entry, with the messages steered to its turn (`steered`, by turn). */
946
+ function promptEntry<I>(items: Items<I>, row: unknown[], steered: ReadonlyMap<number, Entry<I>[]>): Entry<I> {
947
+ const [n, prompt, item, status, answer, agent, carried, answeredAt, answeredSeq, askedAt] = row;
948
+ const at = Number(n);
949
+ const steers = steered.get(at);
950
+ return {
951
+ n: at,
952
+ item: loadItem(items, String(item)),
953
+ prompt: String(prompt),
954
+ answer: str(answer),
955
+ agent: str(agent),
956
+ turn: at,
957
+ carried: str(carried),
958
+ status: str(status) as Status | undefined,
959
+ answeredAt: int(answeredAt),
960
+ answeredSeq: int(answeredSeq),
961
+ askedAt: int(askedAt),
962
+ ...(steers ? { steers } : {}),
963
+ };
964
+ }
965
+
966
+ /**
967
+ * The messages steered to the turns at positions `first` (included) to `end`,
968
+ * by their turn's position. It reads only the steered messages: one range of
969
+ * their table's primary key, joined to their items.
970
+ */
971
+ async function steeredIn<I>(
972
+ db: DatabaseReader,
973
+ items: Items<I>,
974
+ first: number,
975
+ end: number,
976
+ ): Promise<Map<number, Entry<I>[]>> {
977
+ const rows = await db.values(
978
+ `SELECT st.n, st.turn, st.id, s.item FROM ${STEERED} st JOIN ${STEPS} s ON s.n = st.n ` +
979
+ 'WHERE st.n >= ? AND st.n < ? ORDER BY st.n',
980
+ [first, end],
981
+ );
982
+ const steered = new Map<number, Entry<I>[]>();
983
+ for (const [n, turn, id, item] of rows) {
984
+ const entry: Entry<I> = {
985
+ n: Number(n),
986
+ item: loadItem(items, String(item)),
987
+ steer: String(id),
988
+ turn: Number(turn),
989
+ };
990
+ parsedOf(items, entry);
991
+ const of = steered.get(entry.turn!);
992
+ if (of) of.push(entry);
993
+ else steered.set(entry.turn!, [entry]);
994
+ }
995
+ return steered;
996
+ }
997
+
998
+ /**
999
+ * Whether a turn took the steered message `steerId`, in a database that may
1000
+ * not have the conversation yet (the agent's `steered` asks, which may be
1001
+ * the key's first handler).
1002
+ */
1003
+ export async function steerStored(db: DatabaseReader, steerId: string): Promise<boolean> {
1004
+ await SCHEMA.ensure(db);
1005
+ return (await steersStored(db, [steerId])).has(steerId);
1006
+ }
1007
+
1008
+ /** Which of the steered messages `steerIds` a turn took: one read, of their unique ids. */
1009
+ async function steersStored(db: DatabaseReader, steerIds: readonly string[]): Promise<Set<string>> {
1010
+ const marks = steerIds.map(() => '?').join(', ');
1011
+ const rows = await db.values(`SELECT id FROM ${STEERED} WHERE id IN (${marks})`, [...steerIds]);
1012
+ return new Set(rows.map(([id]) => String(id)));
1013
+ }
1014
+
1015
+ /**
1016
+ * The turns from position `first` on, in order: all of them, or as many as
1017
+ * `bounded` (the window and the budget) needs. Bounded, they are read from
1018
+ * the latest back, a page at a time, until they hold the window and more of
1019
+ * the turns before it than the budget holds.
1020
+ */
1021
+ async function transcriptOf<I>(
1022
+ db: DatabaseReader,
1023
+ items: Items<I>,
1024
+ first: number,
1025
+ bounded: [window: number, budget: number] | undefined,
1026
+ ): Promise<Entry<I>[]> {
1027
+ if (bounded === undefined) {
1028
+ const rows = await db.values(`${TRANSCRIPT} WHERE n >= ? ORDER BY n`, [first]);
1029
+ const steered = await steeredIn(db, items, first, Number.MAX_SAFE_INTEGER);
1030
+ return rows.map((row) => promptEntry(items, row, steered));
1031
+ }
1032
+ const read: Entry<I>[] = [];
1033
+ let before = Number.MAX_SAFE_INTEGER;
1034
+ const walk = new Walk(bounded[0]);
1035
+ let left = bounded[1] * 4;
1036
+ // Without a budget, the window and the turn before it are a few turns: a page of a few.
1037
+ const page = left > 0 ? PAGE : 4;
1038
+ for (;;) {
1039
+ const rows = await db.values(`${TRANSCRIPT} WHERE n >= ? AND n < ? ORDER BY n DESC LIMIT ?`, [first, before, page]);
1040
+ // The messages steered to the page's turns: positions from its earliest turn's to the turn after it.
1041
+ const steered = rows.length > 0 ? await steeredIn(db, items, Number(rows.at(-1)![0]), before) : new Map();
1042
+ for (const row of rows) {
1043
+ const entry = promptEntry(items, row, steered);
1044
+ read.push(entry);
1045
+ if (walk.holds(entry.status)) continue;
1046
+ if (entry.answer !== undefined) {
1047
+ // A turn before the window: the model sees its messages and answer, while the budget holds them.
1048
+ left -= turnSize(items, entry);
1049
+ // Without a budget, the first turn before the window is the last read (the model is told how it ended).
1050
+ if (left < 0 || bounded[1] === 0) return read.toReversed();
1051
+ }
1052
+ }
1053
+ if (rows.length < page) return read.toReversed();
1054
+ before = read.at(-1)!.n;
1055
+ }
1056
+ }
1057
+
1058
+ /** Store a step of a turn: its position, its turn's, its `seq`, its item, and the reply and agent it is of. */
1059
+ const INSERT_STEP = `INSERT INTO ${STEPS} (n, turn, seq, item, reply, agent) VALUES (?, ?, ?, ?, ?, ?)`;
1060
+
1061
+ /** Mark the step at a position a message steered to its turn: the position, its turn's, and the message's id. */
1062
+ const INSERT_STEERED = `INSERT INTO ${STEERED} (n, turn, id) VALUES (?, ?, ?)`;
1063
+
1064
+ /** Store a turn's answer on its row: how it ended, the answer, what it carries, its message's position, its `seq`. */
1065
+ const ANSWER = `UPDATE ${TURNS} SET status = ?, answer = ?, agent = ?, carried = ?, answered_at = ?, answered_seq = ? WHERE n = ?`;
1066
+
1067
+ /** The rows of the trajectories after position `after`, in order, as entries, each steered message marked as one. */
1068
+ async function stepsAfter<I>(db: DatabaseReader, items: Items<I>, after: number): Promise<Entry<I>[]> {
1069
+ const rows = await db.values(
1070
+ `SELECT s.n, s.item, s.reply, s.agent, st.id FROM ${STEPS} s LEFT JOIN ${STEERED} st ON st.n = s.n ` +
1071
+ 'WHERE s.n > ? ORDER BY s.n',
1072
+ [after],
1073
+ );
1074
+ return rows.map(([n, item, reply, agent, steer]) => {
1075
+ const entry: Entry<I> = { n: Number(n), item: loadItem(items, String(item)), reply: int(reply), agent: str(agent) };
1076
+ if (steer !== null && steer !== undefined) entry.steer = String(steer);
1077
+ return entry;
1078
+ });
1079
+ }
1080
+
1081
+ /**
1082
+ * The conversation in the key's database, loaded once and kept in step with
1083
+ * it: the transcript, every turn's prompt and answer, as far back as a turn
1084
+ * needs it; and the window, the latest turns whole ({@link Turn}). Only the
1085
+ * latest turn is written; the conversation composes the turns into what the
1086
+ * model gets ({@link history}), until {@link seal} closes it.
1087
+ *
1088
+ * Tool calls and their results are matched by the call's id, within a turn:
1089
+ * each call's id must be its own, as model providers make them. A call whose
1090
+ * id an earlier call has is logged, as its result may be taken for the
1091
+ * other's.
1092
+ */
1093
+ export class Conversation<I> {
1094
+ readonly #ledger: Ledger<I>;
1095
+ readonly #turns: Turn<I>[];
1096
+ readonly items: Items<I>;
1097
+ readonly budget: number;
1098
+ /** How many of the latest answered turns are loaded whole: the window's size. */
1099
+ readonly size: Window;
1100
+
1101
+ readonly db: Database;
1102
+
1103
+ constructor(
1104
+ db: Database,
1105
+ items: Items<I>,
1106
+ entries: Entry<I>[],
1107
+ {
1108
+ start = { n: 0, seq: 0 },
1109
+ transcript = entries.filter((e) => e.prompt !== undefined),
1110
+ last,
1111
+ seq = 0,
1112
+ budget = BUDGET,
1113
+ window = 'all',
1114
+ }: {
1115
+ start?: Start;
1116
+ transcript?: Entry<I>[];
1117
+ last?: number;
1118
+ seq?: number;
1119
+ budget?: number;
1120
+ window?: Window;
1121
+ } = {},
1122
+ ) {
1123
+ this.db = db;
1124
+ this.items = items;
1125
+ this.budget = budget;
1126
+ this.size = window;
1127
+ const positions = [last, entries.at(-1)?.n, transcript.at(-1)?.n].filter((n): n is number => n !== undefined);
1128
+ const following = Math.max(start.n, positions.length > 0 ? Math.max(...positions) + 1 : 0);
1129
+ this.#ledger = new Ledger(db, items, start, transcript, following, Math.max(start.seq, seq));
1130
+ const grouped: [Entry<I>, Entry<I>[]][] = [];
1131
+ for (const entry of entries) {
1132
+ if (entry.prompt !== undefined) grouped.push([entry, []]);
1133
+ else if (grouped.length > 0) grouped.at(-1)![1].push(entry);
1134
+ else throw new Error(`entry ${entry.n} comes before any turn's prompt`);
1135
+ }
1136
+ this.#turns = grouped.map(([prompt, rest]) => new Turn(this.#ledger, prompt, rest));
1137
+ if (this.#turns.length > 0 && transcript.length > 0 && this.#turns.at(-1)!.prompt === transcript.at(-1)) {
1138
+ this.#ledger.latest = this.#turns.at(-1);
1139
+ }
1140
+ }
1141
+
1142
+ /**
1143
+ * Load the conversation from `db`: the transcript, and the window's turns
1144
+ * whole (the latest also while it has no answer). The transcript is read
1145
+ * from the latest turn back, in pages, until it holds the window and the
1146
+ * turns before it that `budget` holds, or the summary's start; with
1147
+ * `complete`, from the summary's start whatever the budget (to summarize
1148
+ * it).
1149
+ */
1150
+ static async load<I>(
1151
+ db: Database,
1152
+ items: Items<I>,
1153
+ window: Window = 'all',
1154
+ budget: number = BUDGET,
1155
+ { complete = false }: { complete?: boolean } = {},
1156
+ ): Promise<Conversation<I>> {
1157
+ checkWindow(window);
1158
+ await SCHEMA.ensure(db);
1159
+ const start = await startOf(db);
1160
+ const [last, seq] = await lastOf(db);
1161
+ const first = window === 'all' || start.summarized === undefined ? start.n : start.summarized;
1162
+ const transcript = await transcriptOf(
1163
+ db,
1164
+ items,
1165
+ first,
1166
+ window === 'all' || complete ? undefined : [window, budget],
1167
+ );
1168
+ const whole = transcript.slice(windowStart(transcript, window));
1169
+ const steps = whole.length > 0 ? await stepsAfter(db, items, whole[0]!.n) : [];
1170
+ const entries = [...whole, ...steps].toSorted((a, b) => a.n - b.n);
1171
+ return new Conversation(db, items, entries, { start, transcript, last, seq, budget, window });
1172
+ }
1173
+
1174
+ // Reading: the conversation as a whole.
1175
+
1176
+ /** The turns' prompts, in order, from the first the load read. Each has its turn's status, answer and what it carried. */
1177
+ get transcript(): readonly Entry<I>[] {
1178
+ return this.#ledger.transcript;
1179
+ }
1180
+
1181
+ /** The window's turns, whole, in order: the last of them is the latest turn. */
1182
+ get turns(): readonly Turn<I>[] {
1183
+ return this.#turns;
1184
+ }
1185
+
1186
+ /** The latest turn: the one being answered, during a run. */
1187
+ get turn(): Turn<I> {
1188
+ if (!this.#ledger.latest) throw new Error('the conversation has no turn loaded whole yet: ask first');
1189
+ return this.#ledger.latest;
1190
+ }
1191
+
1192
+ /** The latest turn if it is being answered: it has no answer yet. */
1193
+ running(): Turn<I> | undefined {
1194
+ const latest = this.#ledger.latest;
1195
+ return latest && latest.status === undefined ? latest : undefined;
1196
+ }
1197
+
1198
+ /** The window's turns, flat, in order: each prompt, then its turn's items. */
1199
+ get entries(): Entry<I>[] {
1200
+ return this.#turns.flatMap((turn) => turn.entries);
1201
+ }
1202
+
1203
+ /** The summary of the turns before the transcript, if they have one (and the transcript is after them). */
1204
+ get summary(): string | undefined {
1205
+ const { transcript, start } = this.#ledger;
1206
+ const first = transcript[0]?.n ?? this.#ledger.next;
1207
+ return start.summarized !== undefined && first >= start.summarized ? start.summary : undefined;
1208
+ }
1209
+
1210
+ /** Whether {@link seal} closed the conversation to writes. */
1211
+ get closed() {
1212
+ return this.#ledger.closed;
1213
+ }
1214
+
1215
+ /** The answer of the turn of prompt `promptId`, if the transcript has it and it has one. */
1216
+ answerOf(promptId: string) {
1217
+ return this.#ledger.transcript.find((turn) => turn.prompt === promptId)?.answer;
1218
+ }
1219
+
1220
+ /** The agent the conversation is with, and the framework's state, as the latest answered turn left them. */
1221
+ carried() {
1222
+ return this.#ledger.carried();
1223
+ }
1224
+
1225
+ /** Whether a turn of the window holds the result of tool call `callId`: the model was given it. */
1226
+ knowsResult(callId: string) {
1227
+ return this.#turns.some((turn) => turn.hasResult(callId));
1228
+ }
1229
+
1230
+ /** The position of the window's first turn: the turns before it are in the transcript only. */
1231
+ window() {
1232
+ return this.#turns[0]?.n ?? this.#ledger.next;
1233
+ }
1234
+
1235
+ /** The size of `turn` as the transcript has it, in characters: its messages and its answer. */
1236
+ #size(turn: Entry<I>) {
1237
+ return turnSize(this.items, turn);
1238
+ }
1239
+
1240
+ /** The latest of `turns` that `characters` holds, in order. */
1241
+ #latest(turns: Entry<I>[], characters: number) {
1242
+ let kept = 0;
1243
+ for (const turn of turns.toReversed()) {
1244
+ characters -= this.#size(turn);
1245
+ if (characters < 0) break;
1246
+ kept += 1;
1247
+ }
1248
+ return turns.slice(turns.length - kept);
1249
+ }
1250
+
1251
+ /** The turns before the window that {@link history} gives the model: the latest that `budget` holds. */
1252
+ earlier(): Entry<I>[] {
1253
+ const start = this.window();
1254
+ const before = this.#ledger.transcript.filter((turn) => turn.n < start && turn.answer !== undefined);
1255
+ return this.#latest(before, this.budget * 4);
1256
+ }
1257
+
1258
+ /** The turns before the next turn's window (once the latest is answered), and the position the window starts at. */
1259
+ #upcoming(): [Entry<I>[], number] {
1260
+ const { transcript } = this.#ledger;
1261
+ if (this.size === 'all') return [[], transcript[0]?.n ?? this.#ledger.next];
1262
+ const first = windowStart(transcript, this.size);
1263
+ const start = first < transcript.length ? transcript[first]!.n : this.#ledger.next;
1264
+ return [transcript.slice(0, first).filter((turn) => turn.answer !== undefined), start];
1265
+ }
1266
+
1267
+ /** Whether the turns before the next turn's window outgrow `budget`: then they are summarized. */
1268
+ overflowing() {
1269
+ const [before] = this.#upcoming();
1270
+ return before.reduce((sum, turn) => sum + this.#size(turn), 0) > this.budget * 4;
1271
+ }
1272
+
1273
+ /**
1274
+ * The turns to summarize, and the position of the first turn after them,
1275
+ * if any are to be: the turns before the next turn's window but the latest
1276
+ * that half the `budget` holds, which stay as they are.
1277
+ */
1278
+ toSummarize(): [Entry<I>[], number] | undefined {
1279
+ const [before, start] = this.#upcoming();
1280
+ const kept = this.#latest(before, this.budget * 2);
1281
+ const summarized = before.slice(0, before.length - kept.length);
1282
+ if (summarized.length === 0) return undefined;
1283
+ return [summarized, kept[0]?.n ?? start];
1284
+ }
1285
+
1286
+ /**
1287
+ * The items the model gets, in order, the one place where turns are made
1288
+ * one flat list: the summary of the earliest turns, if they have one; the
1289
+ * turns before the window, as their prompts, the messages steered to them
1290
+ * and their answers, as many of the latest as `budget` holds; then the
1291
+ * window's turns, whole.
1292
+ */
1293
+ history(): I[] {
1294
+ const out: I[] = [];
1295
+ const summary = this.summary;
1296
+ if (summary !== undefined) out.push(...summaryItems(this.items, summary));
1297
+ for (const turn of this.earlier()) {
1298
+ out.push(turn.item, ...(turn.steers ?? []).map((e) => e.item), this.items.reply(turn.answer ?? '', turn.agent));
1299
+ }
1300
+ for (const turn of this.#turns) {
1301
+ for (const entry of turn.entries) {
1302
+ // The prompt as the model gets it: with the turn's reminder, which is not stored.
1303
+ const reminded = entry === turn.prompt && turn.reminder !== undefined;
1304
+ const said = reminded ? parsedOf(this.items, entry).said?.[1] : undefined;
1305
+ out.push(said === undefined ? entry.item : this.items.prompt(said + turn.reminder));
1306
+ }
1307
+ }
1308
+ return out;
1309
+ }
1310
+
1311
+ // Writing.
1312
+
1313
+ /** Start the turn of prompt `promptId`, with `text`, and return it: the latest turn now. */
1314
+ ask(promptId: string, text: string): Promise<Turn<I>> {
1315
+ const ledger = this.#ledger;
1316
+ return ledger.lock.run(async () => {
1317
+ ledger.checkOpen();
1318
+ const running = this.running();
1319
+ if (running) throw new Error(`turn ${running.id} has no answer yet: turns never overlap`);
1320
+ const n = ledger.next;
1321
+ const entry: Entry<I> = { n, item: this.items.prompt(text), prompt: promptId, askedAt: Date.now() };
1322
+ await this.db.execute(`INSERT INTO ${TURNS} (n, seq, prompt, item, asked_at) VALUES (?, ?, ?, ?, ?)`, [
1323
+ n,
1324
+ ledger.seq + 1,
1325
+ promptId,
1326
+ this.items.dump(entry.item),
1327
+ entry.askedAt!,
1328
+ ]);
1329
+ ledger.seq += 1;
1330
+ ledger.next = n + 1;
1331
+ ledger.transcript.push(entry);
1332
+ const turn = new Turn(ledger, entry);
1333
+ this.#turns.push(turn);
1334
+ ledger.latest = turn;
1335
+ return turn;
1336
+ });
1337
+ }
1338
+
1339
+ /**
1340
+ * Close the conversation to writes, once those under way are stored: for
1341
+ * a stopped run, which (unwinding, or a promise of it left behind) stores
1342
+ * nothing more once its turn is closed.
1343
+ */
1344
+ async seal() {
1345
+ await this.#ledger.lock.run(async () => {
1346
+ this.#ledger.closed = true;
1347
+ });
1348
+ }
1349
+ }
1350
+
1351
+ /**
1352
+ * A framework's run: from the conversation, whose latest turn
1353
+ * (`conversation.turn`) is the one to answer (just asked, or left unfinished
1354
+ * by an earlier attempt), to its answer. It reads what the model gets from
1355
+ * the conversation (`history()`), and stores each step in the turn as it
1356
+ * goes. A tool's error fails the attempt.
1357
+ */
1358
+ export type Run<I> = (conversation: Conversation<I>) => Promise<string>;
1359
+
1360
+ /** The id of the invocation that made prompt `promptId` (see `nextPromptId`). */
1361
+ export const invocationOf = (promptId: string) => promptId.split(':', 1)[0]!;
1362
+
1363
+ /**
1364
+ * Answer the prompt `text` with a framework's `run`, once. The prompt's id is
1365
+ * the invocation's (`nextPromptId`), so a retried attempt returns the stored
1366
+ * answer (reading only it), or goes on with the turn. A turn an earlier
1367
+ * invocation left without an answer is closed first ({@link ENDED}): that
1368
+ * invocation is gone. `items` must be the agent's `messages` view's, if it
1369
+ * has one: one framework per agent.
1370
+ *
1371
+ * `window` and `budget` are the agent's unless given; with `ownHistory`
1372
+ * (the framework keeps the model's history itself), none: only the latest
1373
+ * turns are read, and the agent's `summarize` is not for it. With `check`, the
1374
+ * answer is checked: a message it returns asks the model again with it,
1375
+ * once, as a step of the turn ({@link Turn.askAgain}), and the turn's answer
1376
+ * is the reply to that. With `reminder`, the model is told it after the
1377
+ * prompt ({@link Turn.reminder}), which is stored as it was asked.
1378
+ */
1379
+ export async function answerOnce<I>(
1380
+ ctx: restate.SessionContext,
1381
+ text: string,
1382
+ items: Items<I>,
1383
+ run: Run<I>,
1384
+ options: { window?: Window; budget?: number; check?: Check; reminder?: string; ownHistory?: boolean } = {},
1385
+ ): Promise<string> {
1386
+ const settings = settingsOf(ctx);
1387
+ // One framework per agent (D7): its conversation holds its `messages` view's items, which another can't read.
1388
+ if (settings.items !== undefined && settings.items !== items) {
1389
+ throw new restate.TerminalError(
1390
+ "this agent's `messages` view is another framework's: an agent's conversation holds one framework's items",
1391
+ );
1392
+ }
1393
+ // A framework that keeps the model's history itself (pi, DeepSeek) reads
1394
+ // only the latest turns: the one it answers, and the one before, to tell
1395
+ // the model how that ended. Summaries are of `history()`, which it never reads.
1396
+ const own = options.ownHistory === true;
1397
+ const window = own ? 0 : checkWindow(options.window ?? settings.window);
1398
+ const budget = own ? 0 : (options.budget ?? settings.budget);
1399
+ const promptId = nextPromptId(ctx);
1400
+ await SCHEMA.ensure(ctx.db);
1401
+ const stored = await answerIn(ctx.db, promptId);
1402
+ // Answered (or closed) already: a retry answers, or fails, as the turn ended.
1403
+ if (stored !== undefined) return storedAnswer(stored.answer, stored.status);
1404
+ const conversation = await Conversation.load(ctx.db, items, window, budget);
1405
+ const answered = await forPrompt(ctx, promptId, () =>
1406
+ answering(
1407
+ ctx,
1408
+ // The Restate calls of this invocation are its turn's: the latest, answered
1409
+ // or not (its end forgets the calls whose results it stored).
1410
+ (callId, failedWith) => {
1411
+ const turn = conversation.turns.at(-1);
1412
+ return turn !== undefined && turn.id === promptId && turn.stored(callId, failedWith);
1413
+ },
1414
+ () => answerTurn(ctx, conversation, promptId, text, run, options.check, options.reminder),
1415
+ ),
1416
+ );
1417
+ const definition = definitionOf(ctx) as { name: string } | undefined;
1418
+ if (!own && settings.summarize && conversation.overflowing() && definition) {
1419
+ // Compacted in an invocation of its own, which the key runs before its next message.
1420
+ ctx.send({ service: definition.name, handler: 'compact', key: ctx.key, idempotencyKey: `${promptId}:compact` });
1421
+ }
1422
+ return answered;
1423
+ }
1424
+
1425
+ /** Answer the turn of `promptId` (ending one another invocation left first), as `answerOnce` says. */
1426
+ async function answerTurn<I>(
1427
+ ctx: restate.SessionContext,
1428
+ conversation: Conversation<I>,
1429
+ promptId: string,
1430
+ text: string,
1431
+ run: Run<I>,
1432
+ check: Check | undefined,
1433
+ reminder: string | undefined,
1434
+ ): Promise<string> {
1435
+ const { items } = conversation;
1436
+ /** Close `closed` with `status` and `note`: the framework's own store first, if it has one. */
1437
+ const close = async (closed: Turn<I>, status: Status, note: string) => {
1438
+ if (closed.status !== undefined) return;
1439
+ await items.settleOwn?.(ctx, closed, status);
1440
+ await closed.close(ctx, status, note);
1441
+ };
1442
+ let running = conversation.running();
1443
+ if (running && running.id !== promptId) {
1444
+ // Turns never overlap, so the invocation of this one is gone: it ends unanswered.
1445
+ await close(running, 'ended', ENDED);
1446
+ running = undefined;
1447
+ }
1448
+ const turn = running ?? (await conversation.ask(promptId, text));
1449
+ turn.reminder = reminder;
1450
+ const going = (async () => {
1451
+ let answered = await run(conversation);
1452
+ // Once at most: a turn that asked again (in an earlier attempt, say) answers with the reply to that,
1453
+ // or its check fails it (a terminal error, which closes it failed, below).
1454
+ const again = check?.(answered, turn.latestAsk() !== turn.prompt);
1455
+ if (again !== undefined && turn.latestAsk() === turn.prompt) {
1456
+ await turn.askAgain(again);
1457
+ answered = await run(conversation);
1458
+ check?.(answered, true);
1459
+ }
1460
+ return answered;
1461
+ })();
1462
+ const stop = stopSignalOf(ctx);
1463
+ let answered: string;
1464
+ try {
1465
+ answered = await (stop ? Promise.race([going, aborted(stop)]) : going);
1466
+ } catch (error) {
1467
+ if (stop) going.catch(() => {}); // a run left behind: it stores nothing more once its turn is closed
1468
+ if (error instanceof AttemptEnded) throw error; // the next attempt goes on with the run
1469
+ if (error instanceof restate.CancelledError) {
1470
+ // Cancelled: close the turn, so that the next prompt starts afresh.
1471
+ await close(turn, 'cancelled', CANCELLED);
1472
+ await conversation.seal();
1473
+ throw error;
1474
+ }
1475
+ // Refused for good (a wrong API key, say): closed unanswered, and a
1476
+ // terminal error. A framework's own 424 is one (a model it cannot take,
1477
+ // its provider's refusal), as is an error a retry would meet again.
1478
+ const refused =
1479
+ error instanceof restate.TerminalError ? (error.code === REFUSED ? error : undefined) : refusalOf(ctx, error);
1480
+ if (refused) {
1481
+ await close(turn, 'refused', UNANSWERED);
1482
+ throw refused;
1483
+ }
1484
+ if (error instanceof restate.TerminalError) {
1485
+ // Failed for good: closed with the error, so that the next prompt does not run into it again.
1486
+ await close(turn, 'failed', `Error: ${error.message}`);
1487
+ throw error;
1488
+ }
1489
+ throw error;
1490
+ }
1491
+ await turn.answered(answered);
1492
+ return storedAnswer(answered);
1493
+ }
1494
+
1495
+ /**
1496
+ * Close the latest turn (`ended`) if invocation `invocationId` made it and
1497
+ * left it without an answer: the companion has this done when it finds the
1498
+ * turn's invocation gone. A turn with its answer (closed by a newer turn
1499
+ * first, say) is left as it is. Whether it closed the turn.
1500
+ */
1501
+ export async function settle<I>(ctx: restate.SessionContext, items: Items<I>, invocationId: string): Promise<boolean> {
1502
+ await SCHEMA.ensure(ctx.db);
1503
+ const row = await ctx.db.get(`SELECT prompt, status FROM ${TURNS} ORDER BY n DESC LIMIT 1`);
1504
+ if (!row || row.status !== null || invocationOf(String(row.prompt)) !== invocationId) return false;
1505
+ const running = (await Conversation.load(ctx.db, items, 0)).running();
1506
+ if (!running) return false;
1507
+ await items.settleOwn?.(ctx, running, 'ended');
1508
+ await running.close(ctx, 'ended', ENDED);
1509
+ return true;
1510
+ }
1511
+
1512
+ /** `turns` as text, after the summary of the turns before them, if any: what is summarized. */
1513
+ function transcribed<I>(conversation: Conversation<I>, turns: Entry<I>[]) {
1514
+ const lines = conversation.summary ? [`Summary of the conversation before:\n${conversation.summary}\n`] : [];
1515
+ for (const turn of turns) {
1516
+ const said = parsedOf(conversation.items, turn).said?.[1] ?? '';
1517
+ const steered = (turn.steers ?? []).map((e) => `User: ${parsedOf(conversation.items, e).said?.[1] ?? ''}\n`);
1518
+ lines.push(`User: ${said}\n${steered.join('')}Assistant: ${turn.answer ?? ''}\n`);
1519
+ }
1520
+ return lines.join('\n');
1521
+ }
1522
+
1523
+ /**
1524
+ * Summarize the turns before the window that outgrow the agent's budget,
1525
+ * with the agent's `summarize`. The summary, of the earlier summary and those
1526
+ * turns, takes their place in what the model sees; the turns stay stored,
1527
+ * and `messages` shows them as before. A summary that fails is logged, and
1528
+ * tried again after the next turn. Whether it summarized.
1529
+ */
1530
+ export async function compact<I>(ctx: restate.SessionContext, items: Items<I>): Promise<boolean> {
1531
+ const settings = settingsOf(ctx);
1532
+ if (!settings.summarize) return false;
1533
+ const conversation = await Conversation.load(ctx.db, items, settings.window, settings.budget, { complete: true });
1534
+ const found = conversation.overflowing() ? conversation.toSummarize() : undefined;
1535
+ if (!found) return false;
1536
+ const [turns, after] = found;
1537
+ let summary: string;
1538
+ try {
1539
+ summary = await settings.summarize(ctx, SUMMARIZE + transcribed(conversation, turns));
1540
+ } catch (error) {
1541
+ if (error instanceof restate.CancelledError) throw error;
1542
+ console.warn(`Summarizing the earlier turns failed, and is tried again after the next turn: ${String(error)}`);
1543
+ return false;
1544
+ }
1545
+ await restart(ctx.db, { ...(await startOf(ctx.db)), summary, summarized: after });
1546
+ return true;
1547
+ }