@restatedev/agents 0.5.0 → 0.7.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 +79 -24
- package/dist/calls.d.ts +20 -1
- package/dist/calls.d.ts.map +1 -1
- package/dist/calls.js +46 -7
- package/dist/calls.js.map +1 -1
- package/dist/claude/index.d.ts +11 -11
- package/dist/claude/index.d.ts.map +1 -1
- package/dist/claude/index.js +12 -6
- package/dist/claude/index.js.map +1 -1
- package/dist/client.d.ts +1 -1
- package/dist/client.d.ts.map +1 -1
- package/dist/common.d.ts +62 -23
- package/dist/common.d.ts.map +1 -1
- package/dist/common.js +67 -38
- package/dist/common.js.map +1 -1
- package/dist/{signals.d.ts → companion.d.ts} +106 -43
- package/dist/companion.d.ts.map +1 -0
- package/dist/companion.js +463 -0
- package/dist/companion.js.map +1 -0
- package/dist/conversation.d.ts +103 -5
- package/dist/conversation.d.ts.map +1 -1
- package/dist/conversation.js +295 -75
- package/dist/conversation.js.map +1 -1
- package/dist/deepseek/index.d.ts +11 -11
- package/dist/deepseek/index.d.ts.map +1 -1
- package/dist/deepseek/index.js +26 -26
- package/dist/deepseek/index.js.map +1 -1
- package/dist/index.d.ts +8 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -3
- package/dist/index.js.map +1 -1
- package/dist/langgraph/checkpointer.d.ts +3 -1
- package/dist/langgraph/checkpointer.d.ts.map +1 -1
- package/dist/langgraph/checkpointer.js +15 -6
- package/dist/langgraph/checkpointer.js.map +1 -1
- package/dist/langgraph/graph.d.ts.map +1 -1
- package/dist/langgraph/graph.js +32 -13
- package/dist/langgraph/graph.js.map +1 -1
- package/dist/langgraph/index.d.ts +11 -11
- package/dist/langgraph/index.d.ts.map +1 -1
- package/dist/langgraph/index.js +19 -13
- package/dist/langgraph/index.js.map +1 -1
- package/dist/langgraph/nodes.d.ts +2 -1
- package/dist/langgraph/nodes.d.ts.map +1 -1
- package/dist/langgraph/nodes.js +23 -20
- package/dist/langgraph/nodes.js.map +1 -1
- package/dist/object.d.ts +24 -22
- package/dist/object.d.ts.map +1 -1
- package/dist/object.js +14 -11
- package/dist/object.js.map +1 -1
- package/dist/opencode/index.d.ts +11 -11
- package/dist/opencode/index.d.ts.map +1 -1
- package/dist/opencode/index.js +25 -27
- package/dist/opencode/index.js.map +1 -1
- package/dist/pi/index.d.ts +13 -13
- package/dist/pi/index.d.ts.map +1 -1
- package/dist/pi/index.js +18 -20
- package/dist/pi/index.js.map +1 -1
- package/dist/pi/storage.d.ts +7 -0
- package/dist/pi/storage.d.ts.map +1 -1
- package/dist/pi/storage.js +12 -0
- package/dist/pi/storage.js.map +1 -1
- package/dist/steering.d.ts +2 -1
- package/dist/steering.d.ts.map +1 -1
- package/dist/steering.js +2 -2
- package/dist/steering.js.map +1 -1
- package/dist/tools.d.ts +21 -0
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +54 -14
- package/dist/tools.js.map +1 -1
- package/dist/webhook.js +1 -1
- package/dist/webhook.js.map +1 -1
- package/package.json +90 -84
- package/src/calls.ts +52 -11
- package/src/claude/README.md +4 -2
- package/src/claude/index.ts +12 -7
- package/src/client.ts +1 -1
- package/src/common.ts +99 -40
- package/src/companion.ts +674 -0
- package/src/conversation.ts +353 -101
- package/src/deepseek/README.md +7 -1
- package/src/deepseek/index.ts +25 -24
- package/src/index.ts +10 -4
- package/src/langgraph/README.md +8 -5
- package/src/langgraph/checkpointer.ts +26 -15
- package/src/langgraph/graph.ts +30 -16
- package/src/langgraph/index.ts +24 -17
- package/src/langgraph/nodes.ts +24 -20
- package/src/object.ts +43 -40
- package/src/opencode/README.md +5 -2
- package/src/opencode/index.ts +26 -27
- package/src/pi/README.md +6 -1
- package/src/pi/index.ts +25 -19
- package/src/pi/storage.ts +13 -0
- package/src/steering.ts +8 -7
- package/src/tools.ts +60 -18
- package/src/webhook.ts +1 -1
- package/dist/signals.d.ts.map +0 -1
- package/dist/signals.js +0 -383
- package/dist/signals.js.map +0 -1
- package/src/signals.ts +0 -590
package/src/object.ts
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
import * as restate from '@restatedev/sessions';
|
|
3
3
|
import { reset } from '@restatedev/sessions/internal';
|
|
4
4
|
import {
|
|
5
|
+
type AgentContext,
|
|
6
|
+
type AgentViewContext,
|
|
5
7
|
type Answering,
|
|
6
8
|
BUDGET,
|
|
7
9
|
type Chat,
|
|
@@ -22,18 +24,17 @@ import {
|
|
|
22
24
|
} from './common.ts';
|
|
23
25
|
import { compact, type Items, nextStart, restart, SCHEMA, settle, steerStored } from './conversation.ts';
|
|
24
26
|
import {
|
|
27
|
+
companionAt,
|
|
25
28
|
type Notifications,
|
|
26
29
|
type Resolved,
|
|
27
30
|
type Signal,
|
|
28
|
-
signals,
|
|
29
|
-
signalsOf,
|
|
30
31
|
type Steer,
|
|
31
32
|
type Steered,
|
|
32
33
|
type Steering,
|
|
33
34
|
withCompanion,
|
|
34
35
|
type Waiting,
|
|
35
36
|
type Watch,
|
|
36
|
-
} from './
|
|
37
|
+
} from './companion.ts';
|
|
37
38
|
|
|
38
39
|
/**
|
|
39
40
|
* The options of every object here, beside a session object's: retries for
|
|
@@ -61,12 +62,13 @@ export interface Stopped {
|
|
|
61
62
|
}
|
|
62
63
|
|
|
63
64
|
/**
|
|
64
|
-
* A call of the companion
|
|
65
|
-
* request and `step`: a restarted view joins
|
|
66
|
-
* key: asked again, it answers again, and
|
|
65
|
+
* A call of the companion of the object of `ctx` (its own, at its key); with
|
|
66
|
+
* `step`, a change, keyed by the request and `step`: a restarted view joins
|
|
67
|
+
* the same call. A read has no key: asked again, it answers again, and
|
|
68
|
+
* Restate keeps nothing of it.
|
|
67
69
|
*/
|
|
68
|
-
const companion = (ctx:
|
|
69
|
-
ctx.rpc(
|
|
70
|
+
const companion = (ctx: AgentViewContext, step?: string) =>
|
|
71
|
+
ctx.rpc(companionAt(ctx), ctx.key, step === undefined ? {} : { idempotencyKey: `${ctx.request.id}:${step}` });
|
|
70
72
|
|
|
71
73
|
/**
|
|
72
74
|
* Cancel the invocation of the message being answered, if any, and say
|
|
@@ -75,7 +77,7 @@ const companion = (ctx: restate.ViewContext, step?: string) =>
|
|
|
75
77
|
* invocation again (which does nothing), not the message that started once
|
|
76
78
|
* it was cancelled.
|
|
77
79
|
*/
|
|
78
|
-
async function stopped(ctx:
|
|
80
|
+
async function stopped(ctx: AgentViewContext, step: string): Promise<Stopped> {
|
|
79
81
|
const turn = (await companion(ctx, step).status()).answering;
|
|
80
82
|
if (turn) ctx.cancel(turn.invocationId);
|
|
81
83
|
return { stopped: turn?.invocationId ?? null };
|
|
@@ -96,18 +98,19 @@ const WAITS = { inactivityTimeout: { minutes: 5 } } satisfies restate.HandlerOpt
|
|
|
96
98
|
* it answers, and `notifications` and `watch`, the revision of its
|
|
97
99
|
* conversation, and a wait for a newer one (an agent's
|
|
98
100
|
* has `clear` and `sync` too: {@link FOLLOWED}). Each asks the object's
|
|
99
|
-
*
|
|
100
|
-
* object's handler works.
|
|
101
|
+
* companion (its own `<name>.prebuilt.restate`, at the same key), which
|
|
102
|
+
* knows what the object does: they run while the object's handler works.
|
|
103
|
+
* They are the only way a client reaches the companion, whose handlers
|
|
104
|
+
* Restate's ingress refuses.
|
|
101
105
|
*/
|
|
102
106
|
const BUILT_IN = {
|
|
103
|
-
signal: async (ctx:
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
status: async (ctx: restate.ViewContext): Promise<Status> => companion(ctx).status(),
|
|
107
|
+
signal: async (ctx: AgentViewContext, signal: Signal): Promise<Resolved> => companion(ctx, 'signal').resolve(signal),
|
|
108
|
+
pending: async (ctx: AgentViewContext): Promise<Waiting[]> => companion(ctx).pending(),
|
|
109
|
+
status: async (ctx: AgentViewContext): Promise<Status> => companion(ctx).status(),
|
|
107
110
|
/** Cancel the invocation of the message being answered (`status`'s), as Restate's admin API cancels one. */
|
|
108
|
-
stop: async (ctx:
|
|
111
|
+
stop: async (ctx: AgentViewContext): Promise<Stopped> => stopped(ctx, 'stop'),
|
|
109
112
|
/** The revision of the conversation: each change of what `messages` and `status` give increases it. */
|
|
110
|
-
notifications: async (ctx:
|
|
113
|
+
notifications: async (ctx: AgentViewContext): Promise<Notifications> => companion(ctx).notifications(),
|
|
111
114
|
/**
|
|
112
115
|
* The revision, once there is one newer than `revision`, or at the timeout (50 s by
|
|
113
116
|
* default, at most 60 s), whichever comes first: a client then reads what
|
|
@@ -116,7 +119,7 @@ const BUILT_IN = {
|
|
|
116
119
|
*/
|
|
117
120
|
watch: {
|
|
118
121
|
...WAITS,
|
|
119
|
-
handler: async (ctx:
|
|
122
|
+
handler: async (ctx: AgentViewContext, watch: Watch): Promise<Notifications> =>
|
|
120
123
|
companion(ctx, 'watch').watch(watch),
|
|
121
124
|
},
|
|
122
125
|
};
|
|
@@ -135,7 +138,7 @@ const BUILT_IN = {
|
|
|
135
138
|
const followed = (steerable: boolean) => ({
|
|
136
139
|
/**
|
|
137
140
|
* Forget the conversation: stop the message being answered (as `stop`),
|
|
138
|
-
* then empty the key's database, and what its
|
|
141
|
+
* then empty the key's database, and what its companion holds (waits and
|
|
139
142
|
* kept signals). The conversation's ids and cursors go on (see
|
|
140
143
|
* conversation.ts), so a follower reads on, and drops the messages before `first`.
|
|
141
144
|
* A message sent before it is answered first, then forgotten too; one sent
|
|
@@ -144,7 +147,7 @@ const followed = (steerable: boolean) => ({
|
|
|
144
147
|
clear: {
|
|
145
148
|
// `erase` waits for the messages sent before it.
|
|
146
149
|
...WAITS,
|
|
147
|
-
handler: async (ctx:
|
|
150
|
+
handler: async (ctx: AgentViewContext): Promise<Stopped> => {
|
|
148
151
|
const stop = await stopped(ctx, 'clear');
|
|
149
152
|
await ctx.rpc({
|
|
150
153
|
service: ctx.request.target.service,
|
|
@@ -168,7 +171,7 @@ const followed = (steerable: boolean) => ({
|
|
|
168
171
|
steer: {
|
|
169
172
|
input: messageSerde,
|
|
170
173
|
accept: '*/*',
|
|
171
|
-
handler: async (ctx:
|
|
174
|
+
handler: async (ctx: AgentViewContext, text: string): Promise<Steered> => {
|
|
172
175
|
if (!steerable) {
|
|
173
176
|
throw new restate.TerminalError(
|
|
174
177
|
`${ctx.request.target.service} takes no steered messages: its \`chat\` handler is no framework's \`chat()\` (chatHandler)`,
|
|
@@ -181,7 +184,7 @@ const followed = (steerable: boolean) => ({
|
|
|
181
184
|
sync: {
|
|
182
185
|
...WAITS,
|
|
183
186
|
handler: async (
|
|
184
|
-
ctx:
|
|
187
|
+
ctx: AgentViewContext,
|
|
185
188
|
{ cursor = 0, revision, timeoutSeconds = 50, limit = 100, view }: SyncRequest = {},
|
|
186
189
|
): Promise<Synced> => {
|
|
187
190
|
if (revision !== undefined) await companion(ctx, 'watch').watch({ revision, timeoutSeconds });
|
|
@@ -211,14 +214,14 @@ const FOLLOWED = followed(false);
|
|
|
211
214
|
/**
|
|
212
215
|
* The agents' handlers that only their own views call (Restate's ingress
|
|
213
216
|
* refuses them), and their types leave out: `erase`, `clear`'s work, once
|
|
214
|
-
* the handlers before it are done. It empties the key's database and its
|
|
215
|
-
*
|
|
217
|
+
* the handlers before it are done. It empties the key's database and what its
|
|
218
|
+
* companion holds, and the conversation's ids and cursors go on where they got to
|
|
216
219
|
* (conversation.ts).
|
|
217
220
|
*/
|
|
218
221
|
const internal = (items: Items<unknown> | undefined) => ({
|
|
219
222
|
erase: {
|
|
220
223
|
ingressPrivate: true,
|
|
221
|
-
handler: async (ctx:
|
|
224
|
+
handler: async (ctx: AgentContext) => {
|
|
222
225
|
// Read first, which also makes the reset apply the conversation's schema again.
|
|
223
226
|
await SCHEMA.ensure(ctx.db);
|
|
224
227
|
const start = await nextStart(ctx.db);
|
|
@@ -228,7 +231,7 @@ const internal = (items: Items<unknown> | undefined) => ({
|
|
|
228
231
|
await reset(tx);
|
|
229
232
|
await restart(tx, start);
|
|
230
233
|
});
|
|
231
|
-
await ctx.rpc(
|
|
234
|
+
await ctx.rpc(companionAt(ctx), ctx.key, { idempotencyKey: `${ctx.request.id}:reset` }).reset();
|
|
232
235
|
},
|
|
233
236
|
},
|
|
234
237
|
/**
|
|
@@ -240,7 +243,7 @@ const internal = (items: Items<unknown> | undefined) => ({
|
|
|
240
243
|
*/
|
|
241
244
|
settle: {
|
|
242
245
|
ingressPrivate: true,
|
|
243
|
-
handler: async (ctx:
|
|
246
|
+
handler: async (ctx: AgentContext, invocationId: string) => {
|
|
244
247
|
if (!items || !(await settle(ctx, items, invocationId))) return false;
|
|
245
248
|
// The companion published as it closed the turn, before this stored how it ended: publish that too.
|
|
246
249
|
await publish(ctx);
|
|
@@ -250,7 +253,7 @@ const internal = (items: Items<unknown> | undefined) => ({
|
|
|
250
253
|
/** Summarize the earliest turns, past the agent's budget. Whether it did. */
|
|
251
254
|
compact: {
|
|
252
255
|
ingressPrivate: true,
|
|
253
|
-
handler: async (ctx:
|
|
256
|
+
handler: async (ctx: AgentContext) => (items ? compact(ctx, items) : false),
|
|
254
257
|
},
|
|
255
258
|
});
|
|
256
259
|
|
|
@@ -264,7 +267,7 @@ const internal = (items: Items<unknown> | undefined) => ({
|
|
|
264
267
|
const steeredOf = ({ answer, steers }: { answer: Chat; steers: Steers }) => ({
|
|
265
268
|
ingressPrivate: true,
|
|
266
269
|
explicitCancellation: true,
|
|
267
|
-
handler: async (ctx:
|
|
270
|
+
handler: async (ctx: AgentContext, { id, text }: Steer) => {
|
|
268
271
|
if (await steerStored(ctx.db, id)) return;
|
|
269
272
|
await chatTurn(ctx, text, answer, steers);
|
|
270
273
|
},
|
|
@@ -297,8 +300,8 @@ export interface Definition<P extends string> {
|
|
|
297
300
|
description?: string;
|
|
298
301
|
schema?: readonly restate.Step[];
|
|
299
302
|
/**
|
|
300
|
-
* Whether it works unwatched, such as a subagent: its turn
|
|
301
|
-
*
|
|
303
|
+
* Whether it works unwatched, such as a subagent: its turn publishes to its
|
|
304
|
+
* companion only at its end, not at each step, so a client that follows it
|
|
302
305
|
* sees each turn once it ended. `messages` has every turn as before.
|
|
303
306
|
*/
|
|
304
307
|
background?: boolean;
|
|
@@ -365,8 +368,8 @@ type With<H, V> = Functions<typeof BUILT_IN> &
|
|
|
365
368
|
*/
|
|
366
369
|
export const sessionObject = <
|
|
367
370
|
P extends string,
|
|
368
|
-
H extends Record<string, restate.Entry<
|
|
369
|
-
V extends Record<string, restate.Entry<
|
|
371
|
+
H extends Record<string, restate.Entry<AgentContext>>,
|
|
372
|
+
V extends Record<string, restate.Entry<AgentViewContext>>,
|
|
370
373
|
>(
|
|
371
374
|
definition: Definition<P> & {
|
|
372
375
|
handlers?: H & Reserved;
|
|
@@ -391,14 +394,14 @@ export const sessionObject = <
|
|
|
391
394
|
}
|
|
392
395
|
// A model provider's refusal (a missing API key) ends a handler's invocation.
|
|
393
396
|
const yours = Object.fromEntries(
|
|
394
|
-
Object.entries(handlers as Record<string, restate.Entry<
|
|
397
|
+
Object.entries(handlers as Record<string, restate.Entry<AgentContext>>).map(([key, entry]) => [
|
|
395
398
|
key,
|
|
396
399
|
answering(entry),
|
|
397
400
|
]),
|
|
398
401
|
);
|
|
399
|
-
const messages = (views as Record<string, restate.Entry<
|
|
402
|
+
const messages = (views as Record<string, restate.Entry<AgentViewContext>>).messages;
|
|
400
403
|
const page = (typeof messages === 'function' ? messages : messages?.handler) as
|
|
401
|
-
| ((ctx:
|
|
404
|
+
| ((ctx: AgentViewContext, request: MessagesRequest) => Promise<Messages>)
|
|
402
405
|
| undefined;
|
|
403
406
|
// A `chat` that `chatHandler` made: its answer answers the steered messages no turn took (`steered`).
|
|
404
407
|
const chatEntry = (handlers as Record<string, unknown>).chat;
|
|
@@ -413,8 +416,8 @@ export const sessionObject = <
|
|
|
413
416
|
);
|
|
414
417
|
}
|
|
415
418
|
const { erase, ...stored } = internal(items);
|
|
416
|
-
const steering: Record<string, restate.Entry<
|
|
417
|
-
const privates: Record<string, restate.Entry<
|
|
419
|
+
const steering: Record<string, restate.Entry<AgentContext>> = chat ? { steered: steeredOf(chat) } : {};
|
|
420
|
+
const privates: Record<string, restate.Entry<AgentContext>> = messages === undefined
|
|
418
421
|
? {}
|
|
419
422
|
: items
|
|
420
423
|
? { erase, ...stored, ...steering }
|
|
@@ -436,11 +439,11 @@ export const sessionObject = <
|
|
|
436
439
|
};
|
|
437
440
|
|
|
438
441
|
/** `entry`, but a model provider's refusal it fails with ends its invocation, as `chat`'s does. */
|
|
439
|
-
function answering(entry: restate.Entry<
|
|
442
|
+
function answering(entry: restate.Entry<AgentContext>): restate.Entry<AgentContext> {
|
|
440
443
|
const { handler, ...options } = typeof entry === 'function' ? { handler: entry } : entry;
|
|
441
444
|
return {
|
|
442
445
|
...options,
|
|
443
|
-
handler: async (ctx:
|
|
446
|
+
handler: async (ctx: AgentContext, input: unknown) => {
|
|
444
447
|
try {
|
|
445
448
|
return await handler(ctx, input);
|
|
446
449
|
} catch (error) {
|
package/src/opencode/README.md
CHANGED
|
@@ -123,8 +123,11 @@ OpenCode keeps its own history, and compacts it itself: `window`, `budget`
|
|
|
123
123
|
and summaries do not apply. What OpenCode stores of a turn (the model's
|
|
124
124
|
replies, the tools' results) is copied into the turn after each of
|
|
125
125
|
OpenCode's commits, in a `ctx.db` transaction of its own, by OpenCode's
|
|
126
|
-
message and part ids, so a copy a crash missed is caught up, before
|
|
127
|
-
|
|
126
|
+
message and part ids, so a copy a crash missed is caught up, before a tool
|
|
127
|
+
call runs, the answer, and any close of the turn. A copy of a reply with
|
|
128
|
+
tool calls, or of tools' results, is published once it is committed, in a
|
|
129
|
+
`chat` turn (a `prompt()` in a handler of your own publishes nothing), and
|
|
130
|
+
nothing else is: a tool call's start publishes nothing. That is what `messages`
|
|
128
131
|
shows ([docs/conversation.md](../../docs/conversation.md)); OpenCode's own
|
|
129
132
|
"Continue" after a restart, its idle markers and its compactions are not
|
|
130
133
|
copied. A reply with tool calls is copied as its stream ends, before the
|
package/src/opencode/index.ts
CHANGED
|
@@ -19,8 +19,10 @@
|
|
|
19
19
|
// what clients read, and how turns end. What OpenCode stores of a turn (the
|
|
20
20
|
// model's replies, the tools' results) is copied into the turn after each of
|
|
21
21
|
// OpenCode's commits, in a `ctx.db` transaction of its own, idempotently (by
|
|
22
|
-
// OpenCode's message and part ids), and caught up before
|
|
23
|
-
// answer, and any close of the turn.
|
|
22
|
+
// OpenCode's message and part ids), and caught up before a tool call runs, the
|
|
23
|
+
// answer, and any close of the turn. A copy of steps (a reply with tool calls,
|
|
24
|
+
// tools' results) is published once it commits, and nothing else is: followers
|
|
25
|
+
// read the conversation then. OpenCode boots lazily, as a turn runs:
|
|
24
26
|
// an answered prompt's retry boots nothing.
|
|
25
27
|
//
|
|
26
28
|
// OpenCode records an execution claim as a turn starts, and every boot sweeps
|
|
@@ -55,8 +57,8 @@
|
|
|
55
57
|
// step, after the round's results. Once, by its steer id (`msg_steer_<id>`,
|
|
56
58
|
// which OpenCode takes once, also from a retried attempt). In such a turn,
|
|
57
59
|
// the tool's `execute.after` hook, which OpenCode awaits before it stores the
|
|
58
|
-
// result, copies the result as the tool returned it and publishes the
|
|
59
|
-
//
|
|
60
|
+
// result, copies the result as the tool returned it and publishes the copy,
|
|
61
|
+
// whose answer lists the messages, then submits them: so OpenCode places
|
|
60
62
|
// them at the step that follows, never past the turn's end. The copy stores
|
|
61
63
|
// each as a steered message of the turn, in its place, and tells the
|
|
62
64
|
// companion it is taken.
|
|
@@ -93,7 +95,6 @@ import {
|
|
|
93
95
|
REFUSED,
|
|
94
96
|
RETURNED_UNRECORDED,
|
|
95
97
|
stopSignalOf,
|
|
96
|
-
toolCallEnded,
|
|
97
98
|
toolCallStarted,
|
|
98
99
|
} from '../common.ts';
|
|
99
100
|
import { answerOnce, invocationOf, type Call, type Items, type Parsed, STEPS, type Turn } from '../conversation.ts';
|
|
@@ -365,8 +366,8 @@ interface Returned {
|
|
|
365
366
|
* companion told it is taken in the transaction). Each once: by OpenCode's
|
|
366
367
|
* ids, a steered message by its steer id too. Not the prompt, nor what asks
|
|
367
368
|
* again (the turn has them), nor OpenCode's synthetic messages, idle markers
|
|
368
|
-
* and compactions. In a `ctx.db` transaction of its own.
|
|
369
|
-
* calls
|
|
369
|
+
* and compactions. In a `ctx.db` transaction of its own. Whether it copied a
|
|
370
|
+
* step that a follower waits for: a reply with tool calls, or a tool's result.
|
|
370
371
|
*
|
|
371
372
|
* With `own`, a call's result as its tool returned it, before OpenCode
|
|
372
373
|
* stores it: copied too (after its reply), under the id OpenCode's part has.
|
|
@@ -377,14 +378,13 @@ async function copyInto(
|
|
|
377
378
|
turn: Turn<Item>,
|
|
378
379
|
own?: Returned,
|
|
379
380
|
steersOnly = false,
|
|
380
|
-
): Promise<
|
|
381
|
-
if (!turn.writable) return
|
|
381
|
+
): Promise<boolean> {
|
|
382
|
+
if (!turn.writable) return false;
|
|
382
383
|
const after = await messagesAfter(host, messageIdOf(turn.id));
|
|
383
|
-
if (!after) return
|
|
384
|
+
if (!after) return false;
|
|
384
385
|
const have = new Set(turn.items.flatMap((e) => (e.item.from ? [e.item.from] : [])));
|
|
385
386
|
const held = new Set(turn.steered().map((e) => e.steer));
|
|
386
387
|
const copied: { item: Item; reply?: boolean; steer?: string }[] = [];
|
|
387
|
-
const resulted: string[] = [];
|
|
388
388
|
for (const m of after) {
|
|
389
389
|
const steer = steerOf(m);
|
|
390
390
|
if (steer !== undefined) {
|
|
@@ -436,15 +436,13 @@ async function copyInto(
|
|
|
436
436
|
...(status === 'error' ? { error: true } : {}),
|
|
437
437
|
};
|
|
438
438
|
copied.push({ item: { type: 'results', results: [result], from } });
|
|
439
|
-
resulted.push(t.id!);
|
|
440
439
|
have.add(from);
|
|
441
440
|
}
|
|
442
441
|
}
|
|
443
442
|
if (own && !have.has(own.from) && have.has(own.from.split('/')[0]!)) {
|
|
444
443
|
copied.push({ item: { type: 'results', results: [own.result], from: own.from } });
|
|
445
|
-
resulted.push(own.result.id);
|
|
446
444
|
}
|
|
447
|
-
if (copied.length === 0) return
|
|
445
|
+
if (copied.length === 0) return false;
|
|
448
446
|
const done = await ctx.db.transaction(async (tx) => {
|
|
449
447
|
if (!(await turn.copyIn(tx, copied))) return false;
|
|
450
448
|
tookSteers(
|
|
@@ -454,7 +452,10 @@ async function copyInto(
|
|
|
454
452
|
);
|
|
455
453
|
return true;
|
|
456
454
|
});
|
|
457
|
-
return
|
|
455
|
+
return (
|
|
456
|
+
done &&
|
|
457
|
+
copied.some(({ item }) => item.type === 'results' || (item.type === 'assistant' && (item.calls?.length ?? 0) > 0))
|
|
458
|
+
);
|
|
458
459
|
}
|
|
459
460
|
|
|
460
461
|
/** Where a prompt is: not in the session, its turn running, or ended with an answer or a failure. */
|
|
@@ -931,19 +932,17 @@ export const withOpenCode = async <T>(
|
|
|
931
932
|
let turn: Turn<Item> | undefined;
|
|
932
933
|
// Once the turn is stopped, nothing more is copied: its close says how it ended.
|
|
933
934
|
let stopping = false;
|
|
934
|
-
// The calls that returned, whose ends are published once their results are copied.
|
|
935
|
-
const returned = new Set<string>();
|
|
936
935
|
// The copies, one after another.
|
|
937
936
|
let copying: Promise<unknown> = Promise.resolve();
|
|
938
937
|
/**
|
|
939
938
|
* Copy what OpenCode has of the turn, and `own`, a call's result as its tool returned it (see {@link copyInto}):
|
|
940
|
-
* once the turn is stopped, only with `steersOnly`, its messages steered to the turn.
|
|
939
|
+
* once the turn is stopped, only with `steersOnly`, its messages steered to the turn. A copy of steps (a reply
|
|
940
|
+
* with tool calls, tools' results) is published once it is committed, for followers to read them there.
|
|
941
941
|
*/
|
|
942
942
|
const copy = (own?: Returned, steersOnly = false) => {
|
|
943
943
|
const next = copying.then(async () => {
|
|
944
944
|
if (!turn || (stopping && !steersOnly) || fence.closed) return undefined;
|
|
945
|
-
|
|
946
|
-
if (resulted.some((id) => returned.delete(id))) await toolCallEnded(ctx);
|
|
945
|
+
if (await copyInto(ctx, await host(), turn, own, steersOnly)) await turn.stepsCommitted();
|
|
947
946
|
return undefined;
|
|
948
947
|
});
|
|
949
948
|
copying = next.catch(() => {});
|
|
@@ -986,12 +985,13 @@ export const withOpenCode = async <T>(
|
|
|
986
985
|
};
|
|
987
986
|
|
|
988
987
|
/**
|
|
989
|
-
*
|
|
990
|
-
*
|
|
991
|
-
* result is copied as the tool returns it
|
|
992
|
-
* hook, and goes on to the round's next step
|
|
993
|
-
* the
|
|
994
|
-
* submitted before OpenCode stores the
|
|
988
|
+
* Copy the reply that makes a tool call before the call runs (its copy is
|
|
989
|
+
* published), then forget the calls whose results are stored. In a turn
|
|
990
|
+
* that takes steered messages, the result is copied as the tool returns it
|
|
991
|
+
* (OpenCode stores it after this hook, and goes on to the round's next step
|
|
992
|
+
* without waiting for a copy): the copy's publish lists the messages
|
|
993
|
+
* steered to the turn, which are submitted before OpenCode stores the
|
|
994
|
+
* result ({@link steer}).
|
|
995
995
|
*/
|
|
996
996
|
const followPlugin: Plugin.Plugin = {
|
|
997
997
|
id: 'restate-agents.follow',
|
|
@@ -1002,7 +1002,6 @@ export const withOpenCode = async <T>(
|
|
|
1002
1002
|
.catch(fail);
|
|
1003
1003
|
});
|
|
1004
1004
|
const after = await plugin.tool.hook('execute.after', async (event) => {
|
|
1005
|
-
returned.add(event.id);
|
|
1006
1005
|
if (!inboxOf(ctx)) return;
|
|
1007
1006
|
const output =
|
|
1008
1007
|
event.status === 'error'
|
package/src/pi/README.md
CHANGED
|
@@ -82,7 +82,12 @@ handler does. A retried attempt opens the Harness again and carries on:
|
|
|
82
82
|
pi keeps its own history (and compacts it); each pi commit of a prompt's run
|
|
83
83
|
copies its new entries (the model's replies, the tools' results) into the
|
|
84
84
|
agent's conversation of turns, in the same transaction: what `messages`
|
|
85
|
-
shows ([docs/conversation.md](../../docs/conversation.md)).
|
|
85
|
+
shows ([docs/conversation.md](../../docs/conversation.md)). A commit that
|
|
86
|
+
copied a reply with tool calls, or tools' results, is published once it is
|
|
87
|
+
done, in a `chat` turn (pi commits each result on its own: one publish each;
|
|
88
|
+
a `prompt()` in a handler of your own publishes nothing), and nothing else
|
|
89
|
+
is: a tool call's start publishes nothing, so a follower reads the calls
|
|
90
|
+
once they are stored, and each output once it is. The views show
|
|
86
91
|
each turn as it was asked and answered, not pi's summaries and handoffs.
|
|
87
92
|
|
|
88
93
|
The files of a `workspace` are not in the database: they last as long as the
|
package/src/pi/index.ts
CHANGED
|
@@ -38,10 +38,15 @@
|
|
|
38
38
|
// and a coding tool cut off by a crash is not run again (the model is told
|
|
39
39
|
// it was interrupted).
|
|
40
40
|
import * as restate from '@restatedev/sessions';
|
|
41
|
-
import
|
|
42
|
-
|
|
41
|
+
import {
|
|
42
|
+
awaitWithContext,
|
|
43
|
+
BACKGROUND_CONTEXT,
|
|
44
|
+
type Context,
|
|
45
|
+
withCancel,
|
|
46
|
+
withoutAbortSignal,
|
|
47
|
+
} from '@earendil-works/chord/context';
|
|
43
48
|
import { mkdir } from 'node:fs/promises';
|
|
44
|
-
import {
|
|
49
|
+
import type { Message, MutableModels } from '@earendil-works/pi-ai';
|
|
45
50
|
import { createModels } from '@earendil-works/pi-ai/models';
|
|
46
51
|
import { builtinProviders } from '@earendil-works/pi-ai/providers/all';
|
|
47
52
|
import {
|
|
@@ -79,7 +84,6 @@ import {
|
|
|
79
84
|
REFUSED,
|
|
80
85
|
RETURNED_UNRECORDED,
|
|
81
86
|
stopSignalOf,
|
|
82
|
-
toolCallEnded,
|
|
83
87
|
toolCallStarted,
|
|
84
88
|
} from '../common.ts';
|
|
85
89
|
import { answerOnce, invocationOf, type Items, type Parsed, type Turn } from '../conversation.ts';
|
|
@@ -194,15 +198,15 @@ const STEER_ENTRY = 'restate.steer';
|
|
|
194
198
|
* its replies, its tools' results, and the messages steered to the turn that
|
|
195
199
|
* pi placed at a step (whose companion is told they are taken, in the
|
|
196
200
|
* commit); nothing once `stopped()`, or once the turn is closed. Each entry
|
|
197
|
-
* once: after the last one copied. `
|
|
198
|
-
*
|
|
201
|
+
* once: after the last one copied. `steps` is told when it copied a step
|
|
202
|
+
* that a follower waits for: a reply with tool calls, or a tool's result.
|
|
199
203
|
*/
|
|
200
204
|
function copying(
|
|
201
205
|
ctx: restate.SessionContext,
|
|
202
206
|
turn: Turn<Item>,
|
|
203
207
|
requestId: string,
|
|
204
208
|
stopped: () => boolean,
|
|
205
|
-
|
|
209
|
+
steps: () => void,
|
|
206
210
|
) {
|
|
207
211
|
let from: { conversation: number; last: number } | undefined;
|
|
208
212
|
return async (tx: Transaction) => {
|
|
@@ -245,10 +249,14 @@ function copying(
|
|
|
245
249
|
tx,
|
|
246
250
|
copied.flatMap(({ steer }) => (steer === undefined ? [] : [steer])),
|
|
247
251
|
);
|
|
248
|
-
|
|
252
|
+
if (copied.some(({ item: { message } }) => isStep(message))) steps();
|
|
249
253
|
};
|
|
250
254
|
}
|
|
251
255
|
|
|
256
|
+
/** Whether `message` is a step of a turn that its followers are told of: a reply with tool calls, or a tool's result. */
|
|
257
|
+
const isStep = (message: Message) =>
|
|
258
|
+
message.role === 'toolResult' || (message.role === 'assistant' && message.content.some((c) => c.type === 'toolCall'));
|
|
259
|
+
|
|
252
260
|
/** An agent's options: `chat`, `prompt` and `withPi` take them. */
|
|
253
261
|
export interface Options<O extends z.ZodObject | undefined = z.ZodObject | undefined> {
|
|
254
262
|
/** The model, as `provider/model-id`: MODEL, or else openai/gpt-6-sol. */
|
|
@@ -297,7 +305,7 @@ const native = (t: AnyTool, ctx: restate.SessionContext): ToolRegistration =>
|
|
|
297
305
|
defineTool({
|
|
298
306
|
name: t.name,
|
|
299
307
|
description: t.description,
|
|
300
|
-
parameters:
|
|
308
|
+
parameters: jsonSchemaOf(t), // JSON Schema, as pi takes it
|
|
301
309
|
replay: 'safe', // a crash runs it again, with the same call id
|
|
302
310
|
// Aborted (the conversation's work, on a cancellation), it waits no more.
|
|
303
311
|
execute: async (args, { callId }, task) => ({
|
|
@@ -424,8 +432,6 @@ export const withPi = async <T>(
|
|
|
424
432
|
cancel(error);
|
|
425
433
|
return awaitWithContext(new Promise<never>(() => {}), context);
|
|
426
434
|
};
|
|
427
|
-
// The tool calls that returned, whose ends are published once pi stored their results (`prompt`).
|
|
428
|
-
const returned = new Set<string>();
|
|
429
435
|
// The messages steered to the turn of a prompt's run, submitted to pi as a publish lists them (`prompt`).
|
|
430
436
|
let steering: ((of: ConversationId) => Promise<void>) | undefined;
|
|
431
437
|
// Whether a tool of the round asks to end the run (`terminate`, a handoff): pi then ends the round at its final
|
|
@@ -438,7 +444,6 @@ export const withPi = async <T>(
|
|
|
438
444
|
await toolCallStarted(ctx);
|
|
439
445
|
const result = await t.execute(args, api, task);
|
|
440
446
|
if (result.control?.terminate === true || result.control?.handoff !== undefined) ending = true;
|
|
441
|
-
returned.add(api.callId);
|
|
442
447
|
return result;
|
|
443
448
|
} catch (error) {
|
|
444
449
|
// The tool's error: never taken for the model's provider refusing (a tool may call a model API).
|
|
@@ -499,22 +504,23 @@ export const withPi = async <T>(
|
|
|
499
504
|
// A run an earlier prompt of this invocation left (its turn failed, say). A steered message is its run's.
|
|
500
505
|
await abortLeft((r) => r === id || r === `${id}:again` || r.startsWith('steer:'));
|
|
501
506
|
// Once stopped, the turn's close says how it ended: not pi's abort of its tools.
|
|
502
|
-
// A
|
|
503
|
-
|
|
507
|
+
// A commit that copied steps (a reply with tool calls, tools' results) is published once it is done,
|
|
508
|
+
// for followers to read them there; its answer lists the messages steered to the turn (`steering`).
|
|
509
|
+
let copiedSteps = false;
|
|
504
510
|
database.onCommit = copying(
|
|
505
511
|
ctx,
|
|
506
512
|
current,
|
|
507
513
|
requestId,
|
|
508
514
|
() => cancelled !== undefined || stopSignalOf(ctx)?.aborted === true,
|
|
509
|
-
(
|
|
510
|
-
|
|
515
|
+
() => {
|
|
516
|
+
copiedSteps = true;
|
|
511
517
|
},
|
|
512
518
|
);
|
|
513
519
|
database.afterCommit = async () => {
|
|
514
|
-
if (!
|
|
515
|
-
|
|
520
|
+
if (!copiedSteps) return;
|
|
521
|
+
copiedSteps = false;
|
|
516
522
|
// Failing, it fails the attempt, as a tool's error does: never pi's commit, which is done.
|
|
517
|
-
await
|
|
523
|
+
await current.stepsCommitted().catch((error: unknown) => {
|
|
518
524
|
failed(error);
|
|
519
525
|
cancel(error);
|
|
520
526
|
});
|
package/src/pi/storage.ts
CHANGED
|
@@ -33,6 +33,11 @@ class Executor implements SqliteExecutor {
|
|
|
33
33
|
async run(sql: string, ...params: SqliteValue[]) {
|
|
34
34
|
await this.db.execute(sql, params);
|
|
35
35
|
}
|
|
36
|
+
/** `run`, resolving with the rows it changed: SQLite's `changes()`, read next on the same connection. */
|
|
37
|
+
async runCounted(sql: string, ...params: SqliteValue[]): Promise<number> {
|
|
38
|
+
await this.db.execute(sql, params);
|
|
39
|
+
return (await this.db.get<{ n: number }>('SELECT changes() AS n'))!.n;
|
|
40
|
+
}
|
|
36
41
|
async get<T extends object>(sql: string, ...params: SqliteValue[]): Promise<T | undefined> {
|
|
37
42
|
return this.db.get<T>(sql, params);
|
|
38
43
|
}
|
|
@@ -68,6 +73,14 @@ export class SqlKvDatabase extends Executor implements SqliteDatabase {
|
|
|
68
73
|
return result;
|
|
69
74
|
}
|
|
70
75
|
|
|
76
|
+
/**
|
|
77
|
+
* Outside a transaction, the statement and its count are one: another
|
|
78
|
+
* statement between them would be what `changes()` counted.
|
|
79
|
+
*/
|
|
80
|
+
override runCounted(sql: string, ...params: SqliteValue[]): Promise<number> {
|
|
81
|
+
return this.#session.transaction((tx) => new Executor(tx).runCounted(sql, ...params));
|
|
82
|
+
}
|
|
83
|
+
|
|
71
84
|
/** The session is the caller's to end, after the calls made before. */
|
|
72
85
|
async close() {}
|
|
73
86
|
}
|
package/src/steering.ts
CHANGED
|
@@ -5,10 +5,11 @@
|
|
|
5
5
|
// queues it at once as a turn of its own (the agent's private `steered`), in
|
|
6
6
|
// order with the messages sent after it, and, if the turn being answered
|
|
7
7
|
// takes steered messages, holds it for that turn too (`steer` of
|
|
8
|
-
//
|
|
8
|
+
// companion.ts).
|
|
9
9
|
//
|
|
10
|
-
// The turn learns of it from its next `publish`, which it makes
|
|
11
|
-
//
|
|
10
|
+
// The turn learns of it from its next `publish`, which it makes anyway as it
|
|
11
|
+
// starts and after each write of steps that commits (a reply with tool
|
|
12
|
+
// calls, the tools' results), and waits for (`Inbox` of common.ts). At its next step, once
|
|
12
13
|
// the model's reply has a result for each of its tool calls and before the
|
|
13
14
|
// next model request, the framework's integration calls `takeSteers`: the
|
|
14
15
|
// turn stores each message once, as a message of the user that is a step of
|
|
@@ -21,9 +22,9 @@
|
|
|
21
22
|
// answered as a turn of its own. So each message is answered once.
|
|
22
23
|
import type * as restate from '@restatedev/sessions';
|
|
23
24
|
import type { Transaction } from '@restatedev/sessions';
|
|
24
|
-
import { inboxOf, stopSignalOf } from './common.ts';
|
|
25
|
+
import { type AgentContext, inboxOf, stopSignalOf } from './common.ts';
|
|
25
26
|
import type { Conversation } from './conversation.ts';
|
|
26
|
-
import {
|
|
27
|
+
import { companionHere } from './companion.ts';
|
|
27
28
|
|
|
28
29
|
/**
|
|
29
30
|
* Take the messages steered to the turn being answered, at a step: store
|
|
@@ -61,7 +62,7 @@ export async function takeSteers<I>(ctx: restate.SessionContext, conversation: C
|
|
|
61
62
|
* stored, and once. A framework that places steered messages itself (pi,
|
|
62
63
|
* DeepSeek) calls it as it copies them into the turn.
|
|
63
64
|
*/
|
|
64
|
-
export function tookSteers(ctx:
|
|
65
|
+
export function tookSteers(ctx: AgentContext, tx: Transaction, ids: string[]) {
|
|
65
66
|
if (ids.length === 0) return;
|
|
66
|
-
tx.send(
|
|
67
|
+
tx.send(companionHere(ctx, 'steering'), ctx.key, { idempotencyKey: `taken:${ids[0]}` }).taken(ids);
|
|
67
68
|
}
|