@restatedev/agents 0.2.0 → 0.4.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 +89 -49
- package/dist/calls.d.ts +29 -8
- package/dist/calls.d.ts.map +1 -1
- package/dist/calls.js +79 -18
- 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 +238 -156
- 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 +161 -71
- package/dist/common.d.ts.map +1 -1
- package/dist/common.js +277 -226
- package/dist/common.js.map +1 -1
- package/dist/conversation.d.ts +466 -0
- package/dist/conversation.d.ts.map +1 -0
- package/dist/conversation.js +1247 -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 +323 -107
- 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 +234 -180
- 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 -40
- package/dist/object.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 +75 -7
- package/dist/signals.d.ts.map +1 -1
- package/dist/signals.js +154 -27
- 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 +33 -37
- package/src/calls.ts +110 -24
- package/src/claude/README.md +41 -20
- package/src/claude/index.ts +271 -183
- package/src/client.ts +14 -3
- package/src/common.ts +354 -247
- package/src/conversation.ts +1527 -0
- package/src/deepseek/README.md +78 -11
- package/src/deepseek/index.ts +385 -138
- 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 +337 -193
- package/src/langgraph/nodes.ts +243 -0
- package/src/messages.ts +244 -0
- package/src/object.ts +178 -48
- package/src/output.ts +52 -31
- package/src/pi/README.md +18 -3
- package/src/pi/index.ts +346 -79
- package/src/pi/storage.ts +20 -7
- package/src/signals.ts +235 -31
- 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 -145
- package/dist/log.js.map +0 -1
- package/dist/opencode/db.d.ts +0 -40
- package/dist/opencode/db.d.ts.map +0 -1
- package/dist/opencode/db.js +0 -161
- package/dist/opencode/db.js.map +0 -1
- package/dist/opencode/index.d.ts +0 -100
- package/dist/opencode/index.d.ts.map +0 -1
- package/dist/opencode/index.js +0 -436
- package/dist/opencode/index.js.map +0 -1
- package/src/claude/conversation.ts +0 -114
- package/src/log.ts +0 -193
- package/src/opencode/README.md +0 -125
- package/src/opencode/db.ts +0 -223
- package/src/opencode/index.ts +0 -559
package/src/pi/index.ts
CHANGED
|
@@ -16,7 +16,13 @@
|
|
|
16
16
|
//
|
|
17
17
|
// It runs `work` over `ctx.db`: pi-durable's storage is the object's
|
|
18
18
|
// database (storage.ts), and each pi-durable commit is an SQL transaction
|
|
19
|
-
// in it, stored in order with everything else the handler does.
|
|
19
|
+
// in it, stored in order with everything else the handler does. pi keeps its
|
|
20
|
+
// own history (and compacts it); each commit of a prompt's run copies its
|
|
21
|
+
// new entries (the model's replies, the tools' results) into the
|
|
22
|
+
// conversation of turns (../conversation.ts) in the same transaction: what
|
|
23
|
+
// clients read, and how turns end. A run another invocation left (killed)
|
|
24
|
+
// is aborted, never finished, and the next prompt tells the model how the
|
|
25
|
+
// turn before it ended. The Harness
|
|
20
26
|
// is opened with `tools` (made with pi-durable's `defineTool`) and closed at
|
|
21
27
|
// the end. A retried attempt (a crash, a lost connection) opens it again and
|
|
22
28
|
// carries on: a prompt is submitted once, by its id (pi-durable's requestId),
|
|
@@ -32,7 +38,6 @@
|
|
|
32
38
|
// and a coding tool cut off by a crash is not run again (the model is told
|
|
33
39
|
// it was interrupted).
|
|
34
40
|
import * as restate from '@restatedev/sessions';
|
|
35
|
-
import type { Database } from '@restatedev/sessions';
|
|
36
41
|
import type { Context } from '@earendil-works/chord';
|
|
37
42
|
import { awaitWithContext, BACKGROUND_CONTEXT, withCancel, withoutAbortSignal } from '@earendil-works/chord/context';
|
|
38
43
|
import { mkdir } from 'node:fs/promises';
|
|
@@ -44,47 +49,60 @@ import {
|
|
|
44
49
|
createRegistry,
|
|
45
50
|
defineExtension,
|
|
46
51
|
defineTool,
|
|
52
|
+
GenerationTask,
|
|
47
53
|
Harness,
|
|
54
|
+
hook,
|
|
48
55
|
section,
|
|
49
56
|
type Conversation,
|
|
57
|
+
type ConversationId,
|
|
58
|
+
type ConversationRetryPolicy,
|
|
50
59
|
type ConversationStreamOptions,
|
|
51
|
-
type EntryId,
|
|
52
60
|
type ToolRegistration,
|
|
53
61
|
} from '@earendil-works/pi-durable';
|
|
54
62
|
import { NodeExecutionEnv } from '@earendil-works/pi-durable/env/node';
|
|
55
63
|
import { CodingTools } from '@earendil-works/pi-durable/tools';
|
|
64
|
+
import type { Transaction } from '@restatedev/sessions';
|
|
56
65
|
import {
|
|
57
66
|
AttemptEnded,
|
|
58
67
|
chatHandler,
|
|
59
68
|
CHECK_MODEL,
|
|
69
|
+
type Check,
|
|
60
70
|
checkModelName,
|
|
61
71
|
type Configure,
|
|
62
72
|
configured,
|
|
63
|
-
|
|
73
|
+
fromTool,
|
|
74
|
+
inboxOf,
|
|
64
75
|
ModelError,
|
|
65
76
|
modelOf,
|
|
66
|
-
nextPromptId,
|
|
67
77
|
providerOf,
|
|
68
78
|
refusal,
|
|
69
79
|
REFUSED,
|
|
80
|
+
RETURNED_UNRECORDED,
|
|
70
81
|
stopSignalOf,
|
|
71
82
|
toolCallEnded,
|
|
72
83
|
toolCallStarted,
|
|
73
|
-
transcribing,
|
|
74
|
-
Transcript,
|
|
75
84
|
} from '../common.ts';
|
|
76
|
-
import { type
|
|
85
|
+
import { answerOnce, invocationOf, type Items, type Parsed, type Turn } from '../conversation.ts';
|
|
86
|
+
import { tookSteers } from '../steering.ts';
|
|
87
|
+
import { conversationView } from '../messages.ts';
|
|
88
|
+
import { type Answer, withChecked } from '../output.ts';
|
|
77
89
|
import { type Definition, sessionObject } from '../object.ts';
|
|
78
90
|
import { isTool, jsonSchemaOf, type Tool as AnyTool } from '../tools.ts';
|
|
79
91
|
import type { z } from 'zod';
|
|
80
|
-
import { openSqlKvStorage } from './storage.ts';
|
|
92
|
+
import { openSqlKvStorage, SqlKvDatabase } from './storage.ts';
|
|
81
93
|
|
|
82
94
|
/** What `work` gets: `prompt(text)`, the `conversation()`, and the `harness` and chord `context` for anything else. */
|
|
83
95
|
export interface Pi {
|
|
84
96
|
harness: Harness;
|
|
85
97
|
context: Context;
|
|
86
|
-
/**
|
|
87
|
-
|
|
98
|
+
/**
|
|
99
|
+
* Answer `text`, once, with the answer's text: a turn of the object's
|
|
100
|
+
* conversation (each prompt of an invocation has an id of its own, the
|
|
101
|
+
* same on every attempt). With `check`, a reply it returns a message for
|
|
102
|
+
* is asked again within the turn, once. With `reminder`, the model is told
|
|
103
|
+
* it after the prompt, which the conversation keeps as it was asked.
|
|
104
|
+
*/
|
|
105
|
+
prompt: (text: string, check?: Check, reminder?: string) => Promise<string>;
|
|
88
106
|
/** The object's conversation, on the model: for `reset`, `compact`, `entries` and the like. */
|
|
89
107
|
conversation: () => Promise<Conversation>;
|
|
90
108
|
}
|
|
@@ -93,6 +111,144 @@ export interface Pi {
|
|
|
93
111
|
const textOf = (content: Message['content']): string =>
|
|
94
112
|
typeof content === 'string' ? content : content.flatMap((c) => (c.type === 'text' ? [c.text] : [])).join('');
|
|
95
113
|
|
|
114
|
+
/** A pi message as the conversation of turns keeps it: with the id of the pi entry it was copied from. */
|
|
115
|
+
export interface Item {
|
|
116
|
+
entry?: number;
|
|
117
|
+
message: Message;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** No usage: a message the conversation makes, which no model gave. */
|
|
121
|
+
const NO_USAGE = {
|
|
122
|
+
input: 0,
|
|
123
|
+
output: 0,
|
|
124
|
+
cacheRead: 0,
|
|
125
|
+
cacheWrite: 0,
|
|
126
|
+
totalTokens: 0,
|
|
127
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* pi's items: pi-ai's messages. A user's message is said by the user; an
|
|
132
|
+
* assistant's (but one aborted, failed or deferred) says its text, with its
|
|
133
|
+
* tool calls; a tool's result is a result; a system message says nothing.
|
|
134
|
+
*/
|
|
135
|
+
export const items: Items<Item> = {
|
|
136
|
+
dump: (item) => JSON.stringify(item),
|
|
137
|
+
load: (stored) => {
|
|
138
|
+
// Only a pi message, with the entry it was copied from: another framework's row is not one.
|
|
139
|
+
const item = JSON.parse(stored) as Item;
|
|
140
|
+
const { message, entry, ...rest } = item;
|
|
141
|
+
if (typeof message !== 'object' || message === null || typeof message.role !== 'string')
|
|
142
|
+
throw new Error("not a pi item (a pi-ai message, with its entry's id)");
|
|
143
|
+
if (Object.keys(rest).length > 0 || (entry !== undefined && typeof entry !== 'number'))
|
|
144
|
+
throw new Error(`not a pi item: ${Object.keys(item).join(', ')}`);
|
|
145
|
+
return item;
|
|
146
|
+
},
|
|
147
|
+
prompt: (text) => ({ message: { role: 'user', content: text, timestamp: 0 } }),
|
|
148
|
+
reply: (text) => ({
|
|
149
|
+
message: {
|
|
150
|
+
role: 'assistant',
|
|
151
|
+
content: [{ type: 'text', text }],
|
|
152
|
+
api: 'restate',
|
|
153
|
+
provider: 'restate',
|
|
154
|
+
model: 'note',
|
|
155
|
+
usage: NO_USAGE,
|
|
156
|
+
stopReason: 'stop',
|
|
157
|
+
timestamp: 0,
|
|
158
|
+
},
|
|
159
|
+
}),
|
|
160
|
+
results: (results) =>
|
|
161
|
+
results.map(([call, output]) => ({
|
|
162
|
+
message: {
|
|
163
|
+
role: 'toolResult',
|
|
164
|
+
toolCallId: call.id,
|
|
165
|
+
toolName: call.name,
|
|
166
|
+
content: [{ type: 'text', text: output }],
|
|
167
|
+
isError: output !== RETURNED_UNRECORDED,
|
|
168
|
+
timestamp: 0,
|
|
169
|
+
},
|
|
170
|
+
})),
|
|
171
|
+
read: ({ message: m }): Parsed => {
|
|
172
|
+
if (m.role === 'user') return { said: ['user', textOf(m.content)] };
|
|
173
|
+
if (m.role === 'assistant') {
|
|
174
|
+
if (m.stopReason === 'aborted' || m.stopReason === 'error' || m.stopReason === 'deferred') return {};
|
|
175
|
+
const calls = m.content.flatMap((c) =>
|
|
176
|
+
c.type === 'toolCall' ? [{ id: c.id, name: c.name, input: c.arguments }] : [],
|
|
177
|
+
);
|
|
178
|
+
// Each reply is a message of its own, its tool calls' too.
|
|
179
|
+
return { said: ['assistant', textOf(m.content)], calls };
|
|
180
|
+
}
|
|
181
|
+
if (m.role === 'toolResult')
|
|
182
|
+
return { results: [{ id: m.toolCallId, output: textOf(m.content), error: m.isError }] };
|
|
183
|
+
return {};
|
|
184
|
+
},
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
/** The kind of the entry of a message steered to a turn, as pi places it: its data is the message's id. */
|
|
188
|
+
const STEER_ENTRY = 'restate.steer';
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* What each pi commit copies into `turn`, in its transaction: the entries of
|
|
192
|
+
* the run of the turn's request `requestId` after its user entry (pi's
|
|
193
|
+
* submission names it),
|
|
194
|
+
* its replies, its tools' results, and the messages steered to the turn that
|
|
195
|
+
* pi placed at a step (whose companion is told they are taken, in the
|
|
196
|
+
* commit); nothing once `stopped()`, or once the turn is closed. Each entry
|
|
197
|
+
* once: after the last one copied. `resulted` gets the calls whose results
|
|
198
|
+
* it copied.
|
|
199
|
+
*/
|
|
200
|
+
function copying(
|
|
201
|
+
ctx: restate.SessionContext,
|
|
202
|
+
turn: Turn<Item>,
|
|
203
|
+
requestId: string,
|
|
204
|
+
stopped: () => boolean,
|
|
205
|
+
resulted: (calls: string[]) => void,
|
|
206
|
+
) {
|
|
207
|
+
let from: { conversation: number; last: number } | undefined;
|
|
208
|
+
return async (tx: Transaction) => {
|
|
209
|
+
if (stopped() || !turn.writable) return;
|
|
210
|
+
if (!from) {
|
|
211
|
+
const submitted = await tx.get<{ entry: number | null; conversation: number }>(
|
|
212
|
+
"SELECT json_extract(record, '$.entry') AS entry, conversation_id AS conversation FROM restate_pi_submissions WHERE request_id = ?",
|
|
213
|
+
[JSON.stringify(requestId)],
|
|
214
|
+
);
|
|
215
|
+
if (submitted?.entry === null || submitted?.entry === undefined) return;
|
|
216
|
+
const copied = turn.items.flatMap((e) => (e.item.entry === undefined ? [] : [e.item.entry]));
|
|
217
|
+
from = { conversation: submitted.conversation, last: Math.max(submitted.entry, ...copied) };
|
|
218
|
+
}
|
|
219
|
+
const rows = await tx.values(
|
|
220
|
+
'SELECT id, record FROM restate_pi_entries WHERE conversation_id = ? AND id > ? ORDER BY id',
|
|
221
|
+
[from.conversation, from.last],
|
|
222
|
+
);
|
|
223
|
+
const copied: { item: Item; reply?: boolean; steer?: string }[] = [];
|
|
224
|
+
const held = new Set(turn.steered().map((e) => e.steer));
|
|
225
|
+
for (const [id, record] of rows) {
|
|
226
|
+
const entry = JSON.parse(String(record)) as { kind: string; model?: Message[]; data?: { id?: unknown } };
|
|
227
|
+
from.last = Number(id);
|
|
228
|
+
if (entry.kind === STEER_ENTRY) {
|
|
229
|
+
const steer = typeof entry.data?.id === 'string' ? entry.data.id : undefined;
|
|
230
|
+
const [message] = entry.model ?? [];
|
|
231
|
+
if (steer !== undefined && message && !held.has(steer)) {
|
|
232
|
+
copied.push({ item: { entry: Number(id), message }, steer });
|
|
233
|
+
}
|
|
234
|
+
continue;
|
|
235
|
+
}
|
|
236
|
+
if (entry.kind !== 'pi.assistant' && entry.kind !== 'pi.tool-result') continue;
|
|
237
|
+
for (const message of entry.model ?? []) {
|
|
238
|
+
copied.push({ item: { entry: Number(id), message }, reply: message.role === 'assistant' });
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
if (copied.length === 0) return;
|
|
242
|
+
await turn.copyIn(tx, copied);
|
|
243
|
+
tookSteers(
|
|
244
|
+
ctx,
|
|
245
|
+
tx,
|
|
246
|
+
copied.flatMap(({ steer }) => (steer === undefined ? [] : [steer])),
|
|
247
|
+
);
|
|
248
|
+
resulted(copied.flatMap(({ item: { message } }) => (message.role === 'toolResult' ? [message.toolCallId] : [])));
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
|
|
96
252
|
/** An agent's options: `chat`, `prompt` and `withPi` take them. */
|
|
97
253
|
export interface Options<O extends z.ZodObject | undefined = z.ZodObject | undefined> {
|
|
98
254
|
/** The model, as `provider/model-id`: MODEL, or else openai/gpt-6-sol. */
|
|
@@ -107,6 +263,15 @@ export interface Options<O extends z.ZodObject | undefined = z.ZodObject | undef
|
|
|
107
263
|
workspace?: string;
|
|
108
264
|
/** OpenAI's service tier for each request: `fast` for its fast mode (priced higher), `flex`, and so on. */
|
|
109
265
|
serviceTier?: ServiceTier;
|
|
266
|
+
/**
|
|
267
|
+
* How pi asks the model again after a request failed for a reason that
|
|
268
|
+
* passes (an overloaded or unreachable provider, a rate limit): by
|
|
269
|
+
* default without limit, 2 s after the first failure, then twice as long
|
|
270
|
+
* each time, a minute apart at most. With `maxRetries`, a failure after
|
|
271
|
+
* that many retries ends the turn. A request refused for good (a wrong API
|
|
272
|
+
* key, an unknown model) is never asked again.
|
|
273
|
+
*/
|
|
274
|
+
retry?: Partial<ConversationRetryPolicy>;
|
|
110
275
|
/**
|
|
111
276
|
* The answer as data: a zod object, whose JSON the agent replies with
|
|
112
277
|
* (checked), and `chat` and `prompt` answer with (see output.ts).
|
|
@@ -145,9 +310,21 @@ const native = (t: AnyTool, ctx: restate.SessionContext): ToolRegistration =>
|
|
|
145
310
|
* `workspace`, pi's coding tools working there, with the environment they
|
|
146
311
|
* run in.
|
|
147
312
|
*/
|
|
148
|
-
async function extensions(
|
|
313
|
+
async function extensions(
|
|
314
|
+
tools: ToolRegistration[],
|
|
315
|
+
system: string | undefined,
|
|
316
|
+
workspace: string | undefined,
|
|
317
|
+
afterTools: (conversation: ConversationId) => Promise<void>,
|
|
318
|
+
) {
|
|
149
319
|
const registry = createRegistry();
|
|
150
320
|
registry.install(defineExtension({ name: 'tools', tools }));
|
|
321
|
+
// Once a round's tools are done, before pi places what waits at its end: the messages steered to the turn.
|
|
322
|
+
registry.install(
|
|
323
|
+
defineExtension({
|
|
324
|
+
name: 'steering',
|
|
325
|
+
hooks: [hook(GenerationTask, { afterTools: (_assistant, _results, api) => afterTools(api.conversationId) })],
|
|
326
|
+
}),
|
|
327
|
+
);
|
|
151
328
|
if (system) registry.install(defineExtension({ name: 'system', sections: [section('system', () => system)] }));
|
|
152
329
|
if (!workspace) return { registry, env: undefined };
|
|
153
330
|
await mkdir(workspace, { recursive: true });
|
|
@@ -196,7 +373,7 @@ function unanswered(id: string, why: string | null | undefined, detail: unknown,
|
|
|
196
373
|
*/
|
|
197
374
|
export const withPi = async <T>(
|
|
198
375
|
ctx: restate.SessionContext,
|
|
199
|
-
{ model: named, models, system, tools = [], workspace, serviceTier }: Options,
|
|
376
|
+
{ model: named, models, system, tools = [], workspace, serviceTier, retry }: Options,
|
|
200
377
|
work: (pi: Pi) => Promise<T>,
|
|
201
378
|
): Promise<T> => {
|
|
202
379
|
const model = modelOf(named);
|
|
@@ -222,6 +399,19 @@ export const withPi = async <T>(
|
|
|
222
399
|
turn?.addEventListener('abort', onStop, { once: true });
|
|
223
400
|
// The root conversation, once the Harness is open (below).
|
|
224
401
|
const conversation = () => rootOn(harness, context, model);
|
|
402
|
+
/**
|
|
403
|
+
* Abort the run of a live input of the root conversation that `kept` does
|
|
404
|
+
* not keep: a run a prompt left, whose turn is closed (or the next prompt
|
|
405
|
+
* closes it), is aborted, never finished. pi's own writes (a compaction's)
|
|
406
|
+
* are not runs, and an input without a request id is not a prompt's.
|
|
407
|
+
*/
|
|
408
|
+
const abortLeft = async (kept: (requestId: string) => boolean) => {
|
|
409
|
+
const { submissions } = await harness.inspect(context);
|
|
410
|
+
const left = submissions.filter((s) => s.type === 'input' && s.requestId !== undefined && !kept(s.requestId));
|
|
411
|
+
if (left.length === 0) return;
|
|
412
|
+
const root = await conversation();
|
|
413
|
+
if (left.some((s) => s.conversationId === root.id)) await root.abort(context);
|
|
414
|
+
};
|
|
225
415
|
// A tool call's error: the attempt fails, and the call never returns.
|
|
226
416
|
const stopped = (error: unknown, task: Context): Promise<never> => {
|
|
227
417
|
// The turn was cancelled, and the abort ended the call: pi-durable records it.
|
|
@@ -234,15 +424,25 @@ export const withPi = async <T>(
|
|
|
234
424
|
cancel(error);
|
|
235
425
|
return awaitWithContext(new Promise<never>(() => {}), context);
|
|
236
426
|
};
|
|
427
|
+
// The tool calls that returned, whose ends are published once pi stored their results (`prompt`).
|
|
428
|
+
const returned = new Set<string>();
|
|
429
|
+
// The messages steered to the turn of a prompt's run, submitted to pi as a publish lists them (`prompt`).
|
|
430
|
+
let steering: ((of: ConversationId) => Promise<void>) | undefined;
|
|
431
|
+
// Whether a tool of the round asks to end the run (`terminate`, a handoff): pi then ends the round at its final
|
|
432
|
+
// boundary, which would start a run of its own for a message submitted there, outside the turn.
|
|
433
|
+
let ending = false;
|
|
237
434
|
const tracked = (t: ToolRegistration): ToolRegistration => ({
|
|
238
435
|
...t,
|
|
239
436
|
execute: async (args, api, task) => {
|
|
240
437
|
try {
|
|
241
438
|
await toolCallStarted(ctx);
|
|
242
439
|
const result = await t.execute(args, api, task);
|
|
243
|
-
|
|
440
|
+
if (result.control?.terminate === true || result.control?.handoff !== undefined) ending = true;
|
|
441
|
+
returned.add(api.callId);
|
|
244
442
|
return result;
|
|
245
443
|
} catch (error) {
|
|
444
|
+
// The tool's error: never taken for the model's provider refusing (a tool may call a model API).
|
|
445
|
+
fromTool(ctx, error);
|
|
246
446
|
return stopped(error, task);
|
|
247
447
|
}
|
|
248
448
|
},
|
|
@@ -251,55 +451,149 @@ export const withPi = async <T>(
|
|
|
251
451
|
tools.map((t) => tracked(isTool(t) ? native(t, ctx) : t)),
|
|
252
452
|
system,
|
|
253
453
|
workspace,
|
|
454
|
+
async (of) => {
|
|
455
|
+
// A round that may end the run takes no steered message: each waits for the turn's end, then is a turn of its own.
|
|
456
|
+
const ends = ending;
|
|
457
|
+
ending = false;
|
|
458
|
+
if (!ends) await steering?.(of);
|
|
459
|
+
},
|
|
254
460
|
);
|
|
255
461
|
const settings = {
|
|
256
462
|
// A task that crashes is run again however often Restate retries the attempt (its retry policy decides):
|
|
257
463
|
// pi-durable would park it after 5 crashes in a row, and the prompt would never be answered.
|
|
258
464
|
restartLimit: Infinity,
|
|
465
|
+
// A provider's outage never ends the turn: pi asks again until it answers (pi-durable would give up after 3
|
|
466
|
+
// retries, ending the turn unanswered for good). Each retry is committed: a retried attempt waits as it would.
|
|
467
|
+
retry: { maxRetries: Infinity, ...retry },
|
|
468
|
+
// Every message steered to a turn that waits at a step is placed there, not one a step.
|
|
469
|
+
steeringMode: 'all' as const,
|
|
259
470
|
// pi-durable hands its stream settings to pi-ai's requests as they are: serviceTier is pi-ai's.
|
|
260
471
|
...(serviceTier ? { stream: { serviceTier } as ConversationStreamOptions } : {}),
|
|
261
472
|
};
|
|
262
|
-
const
|
|
473
|
+
const database = new SqlKvDatabase(ctx.db);
|
|
474
|
+
const harness = await Harness.open(
|
|
475
|
+
await openSqlKvStorage(ctx.db, database),
|
|
476
|
+
{ models, registry, env, settings },
|
|
477
|
+
context,
|
|
478
|
+
);
|
|
263
479
|
|
|
264
|
-
const prompt =
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
480
|
+
const prompt = (text: string, check?: Check, reminder?: string) => {
|
|
481
|
+
// 0.3.0's `prompt(text, id)` took a prompt's id: from JavaScript, it would
|
|
482
|
+
// fail as the check is called, again at every retry.
|
|
483
|
+
if (check !== undefined && typeof check !== 'function') {
|
|
484
|
+
throw new restate.TerminalError(
|
|
485
|
+
`pi's prompt(text, check) takes a check of the answer, not ${JSON.stringify(check)}: a prompt has an id of its own`,
|
|
486
|
+
);
|
|
487
|
+
}
|
|
488
|
+
return answerOnce(
|
|
489
|
+
ctx,
|
|
490
|
+
text,
|
|
491
|
+
items,
|
|
492
|
+
async (store) => {
|
|
493
|
+
const current = store.turn;
|
|
494
|
+
const id = current.id;
|
|
495
|
+
const root = await conversation();
|
|
496
|
+
// The turn's own request: its prompt, or the message that asked again within it.
|
|
497
|
+
const again = current.latestAsk() !== current.prompt;
|
|
498
|
+
const requestId = again ? `${id}:again` : id;
|
|
499
|
+
// A run an earlier prompt of this invocation left (its turn failed, say). A steered message is its run's.
|
|
500
|
+
await abortLeft((r) => r === id || r === `${id}:again` || r.startsWith('steer:'));
|
|
501
|
+
// Once stopped, the turn's close says how it ended: not pi's abort of its tools.
|
|
502
|
+
// A tool call's end is published once its result is stored, for followers to read it there.
|
|
503
|
+
let ended = false;
|
|
504
|
+
database.onCommit = copying(
|
|
505
|
+
ctx,
|
|
506
|
+
current,
|
|
507
|
+
requestId,
|
|
508
|
+
() => cancelled !== undefined || stopSignalOf(ctx)?.aborted === true,
|
|
509
|
+
(calls) => {
|
|
510
|
+
for (const call of calls) if (returned.delete(call)) ended = true;
|
|
511
|
+
},
|
|
512
|
+
);
|
|
513
|
+
database.afterCommit = async () => {
|
|
514
|
+
if (!ended) return;
|
|
515
|
+
ended = false;
|
|
516
|
+
// Failing, it fails the attempt, as a tool's error does: never pi's commit, which is done.
|
|
517
|
+
await toolCallEnded(ctx).catch((error: unknown) => {
|
|
518
|
+
failed(error);
|
|
519
|
+
cancel(error);
|
|
520
|
+
});
|
|
521
|
+
};
|
|
522
|
+
// Each message steered to the turn, submitted to pi once (keyed by its id, also by a retried attempt)
|
|
523
|
+
// as a round of tool calls is done (`afterTools`): pi places it at the round's end, after its results,
|
|
524
|
+
// as an entry of its own kind, which `copying` stores.
|
|
525
|
+
const given = new Set<string>();
|
|
526
|
+
steering = async (of) => {
|
|
527
|
+
const inbox = inboxOf(ctx);
|
|
528
|
+
// The root conversation's rounds only: it is the turn's.
|
|
529
|
+
if (!inbox || of !== root.id || cancelled !== undefined) return;
|
|
530
|
+
if (stopSignalOf(ctx)?.aborted || !current.writable) return;
|
|
531
|
+
const held = new Set(current.steered().map((e) => e.steer));
|
|
532
|
+
for (const { id: steerId, text: said } of inbox.messages) {
|
|
533
|
+
if (given.has(steerId) || held.has(steerId)) continue;
|
|
534
|
+
given.add(steerId);
|
|
535
|
+
await root.submit(
|
|
536
|
+
{
|
|
537
|
+
type: 'input',
|
|
538
|
+
content: said,
|
|
539
|
+
whenBusy: 'steer',
|
|
540
|
+
requestId: `steer:${steerId}`,
|
|
541
|
+
entry: { kind: STEER_ENTRY, data: { id: steerId } },
|
|
542
|
+
},
|
|
543
|
+
context,
|
|
544
|
+
);
|
|
545
|
+
}
|
|
546
|
+
};
|
|
547
|
+
// The model is told how the turn before this one ended, if its run did not answer it.
|
|
548
|
+
const before = store.transcript.at(-2);
|
|
549
|
+
const note = !again && before && before.status !== 'answered' && before.answer ? `(${before.answer})\n\n` : '';
|
|
550
|
+
// pi keeps the prompt as it is given, the turn's reminder too; the conversation as it was asked.
|
|
551
|
+
const asked = textOf(current.latestAsk().item.message.content) + (again ? '' : (current.reminder ?? ''));
|
|
552
|
+
const submission = await root.submit({ type: 'input', content: note + asked, requestId }, context);
|
|
553
|
+
const settled = await submission.wait(context);
|
|
554
|
+
// A prompt the cancellation's abort ended fails with the cancellation.
|
|
555
|
+
if (settled.status !== 'done' || settled.answer === undefined)
|
|
556
|
+
throw cancelled ?? unanswered(id, settled.reason, settled.detail, model);
|
|
557
|
+
const { answer } = settled;
|
|
558
|
+
const entry = await root.commit((tx) => tx.entry(AssistantEntry, answer), context);
|
|
559
|
+
const reply = entry?.model?.at(-1);
|
|
560
|
+
if (!reply) throw new restate.TerminalError(`prompt ${id}: no answer entry`);
|
|
561
|
+
return textOf(reply.content);
|
|
562
|
+
},
|
|
563
|
+
// pi keeps the model's history: the conversation reads only its latest turns.
|
|
564
|
+
{ check, reminder, ownHistory: true },
|
|
565
|
+
);
|
|
276
566
|
};
|
|
277
|
-
// `failure`, once it comes
|
|
567
|
+
// `failure`, once it comes. A cancellation aborts the conversation's work
|
|
568
|
+
// instead: the work ends with it (a prompt closes its turn, cancelled).
|
|
278
569
|
const abortOn = async (): Promise<never> => {
|
|
279
570
|
try {
|
|
280
571
|
return await failure;
|
|
281
572
|
} catch (error) {
|
|
282
|
-
if (error instanceof restate.CancelledError)
|
|
283
|
-
|
|
573
|
+
if (!(error instanceof restate.CancelledError)) throw error;
|
|
574
|
+
await (await conversation()).abort(context);
|
|
575
|
+
return new Promise<never>(() => {});
|
|
284
576
|
}
|
|
285
577
|
};
|
|
286
578
|
|
|
579
|
+
// Whatever `work` does (a prompt, a compaction, a wait) has pi schedule
|
|
580
|
+
// what it has: a run another invocation left is aborted first. This
|
|
581
|
+
// invocation's own (a retried attempt's) goes on.
|
|
582
|
+
const working = async () => {
|
|
583
|
+
await abortLeft((r) => invocationOf(r) === ctx.request.id || r.startsWith('steer:'));
|
|
584
|
+
return work({ harness, context, conversation, prompt });
|
|
585
|
+
};
|
|
287
586
|
try {
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
);
|
|
587
|
+
const done = await Promise.race([abortOn(), working()]);
|
|
588
|
+
// Work the cancellation's abort ended (a wait for pi, say) fails with it, as a prompt does.
|
|
589
|
+
if (cancelled) throw cancelled;
|
|
590
|
+
return done;
|
|
293
591
|
} finally {
|
|
294
592
|
turn?.removeEventListener('abort', onStop);
|
|
295
593
|
await harness.close(withoutAbortSignal(context));
|
|
296
594
|
}
|
|
297
595
|
};
|
|
298
596
|
|
|
299
|
-
/** {@link prompt}, answering with the agent's text. */
|
|
300
|
-
const promptText = (ctx: restate.SessionContext, text: string, options: Options): Promise<string> =>
|
|
301
|
-
withPi(ctx, options, (session) => session.prompt(text));
|
|
302
|
-
|
|
303
597
|
/**
|
|
304
598
|
* Answer `text`, once: a retried attempt resumes the same prompt. Each prompt
|
|
305
599
|
* of an invocation is a prompt of its own.
|
|
@@ -310,7 +604,10 @@ export const prompt = <O extends z.ZodObject | undefined = undefined>(
|
|
|
310
604
|
ctx: restate.SessionContext,
|
|
311
605
|
text: string,
|
|
312
606
|
options: Options<O> = {},
|
|
313
|
-
): Promise<Answer<O>> =>
|
|
607
|
+
): Promise<Answer<O>> =>
|
|
608
|
+
withChecked(text, options, (t, o, check, reminder) =>
|
|
609
|
+
withPi(ctx, o, (session) => session.prompt(t, check, reminder)),
|
|
610
|
+
) as Promise<Answer<O>>;
|
|
314
611
|
|
|
315
612
|
/**
|
|
316
613
|
* A chat handler: each message an invocation, the conversation in the
|
|
@@ -320,49 +617,15 @@ export const prompt = <O extends z.ZodObject | undefined = undefined>(
|
|
|
320
617
|
*/
|
|
321
618
|
export const chat = <O extends z.ZodObject | undefined = undefined>(options: Configure<Options<O>> = {}) => {
|
|
322
619
|
if (typeof options === 'object') checkModelName('pi', options.model);
|
|
323
|
-
return chatHandler(async (ctx, message) => prompt(ctx, message, await configured(options, ctx)));
|
|
620
|
+
return chatHandler(async (ctx, message) => prompt(ctx, message, await configured(options, ctx)), { steers: true });
|
|
324
621
|
};
|
|
325
622
|
|
|
326
623
|
/**
|
|
327
|
-
* A
|
|
328
|
-
*
|
|
329
|
-
*
|
|
330
|
-
*/
|
|
331
|
-
export const messages = () => messagesHandler();
|
|
332
|
-
|
|
333
|
-
/**
|
|
334
|
-
* The transcript of each session's root conversation (`ctx.db`, one per
|
|
335
|
-
* attempt), as far as it was read, to its last entry. pi-durable's entries
|
|
336
|
-
* never change, and a new one takes a greater id than any before it (they
|
|
337
|
-
* are committed one at a time), so each read adds the entries after it.
|
|
624
|
+
* A view of the conversation as clients read it: a page at a time, or what
|
|
625
|
+
* is new or changed since a cursor; `view: 'summary'` for each turn's
|
|
626
|
+
* message and answer. It answers while a message is answered.
|
|
338
627
|
*/
|
|
339
|
-
const
|
|
340
|
-
|
|
341
|
-
/** The root conversation in `db`, `root` of a Harness on it, from pi-durable's entries, as `messages` gives it. */
|
|
342
|
-
const transcribe = async (db: Database, root: Conversation, context: Context) => {
|
|
343
|
-
const read = transcripts.get(db) ?? { transcript: new Transcript() };
|
|
344
|
-
transcripts.set(db, read);
|
|
345
|
-
const { transcript } = read;
|
|
346
|
-
// From the last entry read (the bound is inclusive), or the first.
|
|
347
|
-
const query = { order: 'ascending' as const, ...(read.last === undefined ? {} : { minEntryId: read.last }) };
|
|
348
|
-
for (let cursor: Parameters<typeof root.entries>[2]; ;) {
|
|
349
|
-
const page = await root.entries(query, 100, cursor, context);
|
|
350
|
-
for (const entry of page.items) {
|
|
351
|
-
if (entry.id === read.last) continue;
|
|
352
|
-
read.last = entry.id;
|
|
353
|
-
for (const m of entry.model ?? []) {
|
|
354
|
-
if (m.role === 'user') transcript.say('user', textOf(m.content));
|
|
355
|
-
if (m.role === 'assistant') {
|
|
356
|
-
transcript.say('assistant', textOf(m.content));
|
|
357
|
-
for (const c of m.content) if (c.type === 'toolCall') transcript.call(c.id, c.name, c.arguments);
|
|
358
|
-
}
|
|
359
|
-
if (m.role === 'toolResult') transcript.result(m.toolCallId, textOf(m.content), m.isError);
|
|
360
|
-
}
|
|
361
|
-
}
|
|
362
|
-
cursor = page.next;
|
|
363
|
-
if (cursor === undefined) return transcript;
|
|
364
|
-
}
|
|
365
|
-
};
|
|
628
|
+
export const messages = () => conversationView(items);
|
|
366
629
|
|
|
367
630
|
/** An agent: a virtual object `name`, one per key, whose `chat` handler is {@link chat}, and `messages` {@link messages}. */
|
|
368
631
|
export const agent = <P extends string, O extends z.ZodObject | undefined = undefined>({
|
|
@@ -370,6 +633,8 @@ export const agent = <P extends string, O extends z.ZodObject | undefined = unde
|
|
|
370
633
|
description,
|
|
371
634
|
schema,
|
|
372
635
|
background,
|
|
636
|
+
window,
|
|
637
|
+
budget,
|
|
373
638
|
...options
|
|
374
639
|
}: Options<O> & Definition<P>) =>
|
|
375
640
|
sessionObject({
|
|
@@ -377,6 +642,8 @@ export const agent = <P extends string, O extends z.ZodObject | undefined = unde
|
|
|
377
642
|
description,
|
|
378
643
|
schema,
|
|
379
644
|
background,
|
|
645
|
+
window,
|
|
646
|
+
budget,
|
|
380
647
|
handlers: { chat: chat(options) },
|
|
381
648
|
views: { messages: messages() },
|
|
382
649
|
});
|
package/src/pi/storage.ts
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
//
|
|
11
11
|
// pi-durable's tables and indexes are named `restate_pi_<name>` (its
|
|
12
12
|
// storage's `prefix`), apart from the tables of yours in the same database.
|
|
13
|
-
import type { DatabaseWriter, Database } from '@restatedev/sessions';
|
|
13
|
+
import type { DatabaseWriter, Database, Transaction } from '@restatedev/sessions';
|
|
14
14
|
import {
|
|
15
15
|
SqliteStorage,
|
|
16
16
|
type SqliteDatabase,
|
|
@@ -41,9 +41,16 @@ class Executor implements SqliteExecutor {
|
|
|
41
41
|
}
|
|
42
42
|
}
|
|
43
43
|
|
|
44
|
+
/** What runs at the end of each pi commit, in its transaction: the copy of its entries (index.ts). */
|
|
45
|
+
export type OnCommit = (tx: Transaction) => Promise<void>;
|
|
46
|
+
|
|
44
47
|
/** The `SqliteDatabase` facade over the session `db`. */
|
|
45
|
-
class SqlKvDatabase extends Executor implements SqliteDatabase {
|
|
48
|
+
export class SqlKvDatabase extends Executor implements SqliteDatabase {
|
|
46
49
|
readonly #session: Database;
|
|
50
|
+
/** Runs at the end of each commit, in its transaction, so that what it writes commits with it. */
|
|
51
|
+
onCommit: OnCommit | undefined;
|
|
52
|
+
/** Runs once each commit is done, outside its transaction: to tell others what it stored, say. */
|
|
53
|
+
afterCommit: (() => Promise<void>) | undefined;
|
|
47
54
|
|
|
48
55
|
constructor(db: Database) {
|
|
49
56
|
super(db);
|
|
@@ -51,15 +58,21 @@ class SqlKvDatabase extends Executor implements SqliteDatabase {
|
|
|
51
58
|
}
|
|
52
59
|
|
|
53
60
|
/** Commits when the callback resolves; rolls back, and rejects with its error, when it rejects. */
|
|
54
|
-
transaction<T>(callback: (transaction: SqliteExecutor) => Promise<T>): Promise<T> {
|
|
55
|
-
|
|
61
|
+
async transaction<T>(callback: (transaction: SqliteExecutor) => Promise<T>): Promise<T> {
|
|
62
|
+
const result = await this.#session.transaction(async (tx) => {
|
|
63
|
+
const done = await callback(new Executor(tx));
|
|
64
|
+
if (this.onCommit) await this.onCommit(tx);
|
|
65
|
+
return done;
|
|
66
|
+
});
|
|
67
|
+
if (this.afterCommit) await this.afterCommit();
|
|
68
|
+
return result;
|
|
56
69
|
}
|
|
57
70
|
|
|
58
71
|
/** The session is the caller's to end, after the calls made before. */
|
|
59
72
|
async close() {}
|
|
60
73
|
}
|
|
61
74
|
|
|
62
|
-
/** Open pi-durable storage on the session `db
|
|
63
|
-
export function openSqlKvStorage(db: Database): Promise<SqliteStorage> {
|
|
64
|
-
return SqliteStorage.open(
|
|
75
|
+
/** Open pi-durable storage on the session `db`, through `database`, its facade, if given (to set its `onCommit`). */
|
|
76
|
+
export function openSqlKvStorage(db: Database, database = new SqlKvDatabase(db)): Promise<SqliteStorage> {
|
|
77
|
+
return SqliteStorage.open(database, { prefix: PREFIX });
|
|
65
78
|
}
|