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