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