@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
package/src/object.ts
CHANGED
|
@@ -1,14 +1,35 @@
|
|
|
1
1
|
// Virtual objects set up for SQL and agents.
|
|
2
2
|
import * as restate from '@restatedev/sessions';
|
|
3
3
|
import { reset } from '@restatedev/sessions/internal';
|
|
4
|
-
import {
|
|
5
|
-
|
|
4
|
+
import {
|
|
5
|
+
type Answering,
|
|
6
|
+
BUDGET,
|
|
7
|
+
type Chat,
|
|
8
|
+
chatOf,
|
|
9
|
+
type Steers,
|
|
10
|
+
chatTurn,
|
|
11
|
+
checkWindow,
|
|
12
|
+
isAgent,
|
|
13
|
+
ITEMS,
|
|
14
|
+
messageSerde,
|
|
15
|
+
type Messages,
|
|
16
|
+
type MessagesRequest,
|
|
17
|
+
publish,
|
|
18
|
+
refusalOf,
|
|
19
|
+
type Summarize,
|
|
20
|
+
WINDOW,
|
|
21
|
+
type Window,
|
|
22
|
+
} from './common.ts';
|
|
23
|
+
import { compact, type Items, nextStart, restart, SCHEMA, settle, steerStored } from './conversation.ts';
|
|
6
24
|
import {
|
|
7
25
|
type Notifications,
|
|
8
26
|
type Resolved,
|
|
9
27
|
type Signal,
|
|
10
28
|
signals,
|
|
11
29
|
signalsOf,
|
|
30
|
+
type Steer,
|
|
31
|
+
type Steered,
|
|
32
|
+
type Steering,
|
|
12
33
|
withCompanion,
|
|
13
34
|
type Waiting,
|
|
14
35
|
type Watch,
|
|
@@ -27,9 +48,11 @@ const OPTIONS = {
|
|
|
27
48
|
/** What an object is doing: the message it answers, if any, and what its tools wait for. */
|
|
28
49
|
export interface Status {
|
|
29
50
|
/** The message being answered (by a `chat` handler), or null. */
|
|
30
|
-
answering:
|
|
51
|
+
answering: Answering | null;
|
|
31
52
|
/** The waits of its tools, oldest first (see `pending`). */
|
|
32
53
|
waiting: Waiting[];
|
|
54
|
+
/** The messages steered to the message being answered that it has not taken yet, oldest first; absent if none. */
|
|
55
|
+
steering?: Steering[];
|
|
33
56
|
}
|
|
34
57
|
|
|
35
58
|
/** What `stop` did: the invocation of the message it stopped, or null if none was answered. */
|
|
@@ -72,7 +95,7 @@ const WAITS = { inactivityTimeout: { minutes: 5 } } satisfies restate.HandlerOpt
|
|
|
72
95
|
* waits, `status`, what the object is doing, `stop`, which stops the message
|
|
73
96
|
* it answers, and `notifications` and `watch`, the revision of its
|
|
74
97
|
* conversation, and a wait for a newer one (an agent's
|
|
75
|
-
* has `clear` and `sync` too: {@link
|
|
98
|
+
* has `clear` and `sync` too: {@link FOLLOWED}). Each asks the object's
|
|
76
99
|
* `signals` companion, which knows what the object does: they run while the
|
|
77
100
|
* object's handler works.
|
|
78
101
|
*/
|
|
@@ -100,19 +123,21 @@ const BUILT_IN = {
|
|
|
100
123
|
|
|
101
124
|
/**
|
|
102
125
|
* The views that agents (an object with a `messages` view) have beside
|
|
103
|
-
* those of every object: `clear`, which forgets the conversation;
|
|
104
|
-
*
|
|
105
|
-
*
|
|
106
|
-
*
|
|
107
|
-
*
|
|
108
|
-
* once
|
|
126
|
+
* those of every object: `clear`, which forgets the conversation; `steer`,
|
|
127
|
+
* which sends a message while a turn is answered (for an agent whose `chat`
|
|
128
|
+
* a framework's `chat()` made: `chatHandler`'s, which answers it as a turn
|
|
129
|
+
* of its own if no turn takes it); and `sync`, the conversation since
|
|
130
|
+
* `cursor` (by default, all of it), what the agent is doing, and the
|
|
131
|
+
* revision, in one request; with `revision`, once there is a newer one, or
|
|
132
|
+
* at the timeout. A client follows the conversation by sending each
|
|
133
|
+
* answer's `revision` and `cursor` back, at once while it has `more`.
|
|
109
134
|
*/
|
|
110
|
-
const followed = (
|
|
135
|
+
const followed = (steerable: boolean) => ({
|
|
111
136
|
/**
|
|
112
137
|
* Forget the conversation: stop the message being answered (as `stop`),
|
|
113
138
|
* then empty the key's database, and what its `signals` hold (waits and
|
|
114
|
-
* kept signals). The
|
|
115
|
-
*
|
|
139
|
+
* kept signals). The conversation's ids and cursors go on (see
|
|
140
|
+
* conversation.ts), so a follower reads on, and drops the messages before `first`.
|
|
116
141
|
* A message sent before it is answered first, then forgotten too; one sent
|
|
117
142
|
* after starts anew.
|
|
118
143
|
*/
|
|
@@ -130,47 +155,119 @@ const followed = (messages: (ctx: restate.ViewContext, request: MessagesRequest)
|
|
|
130
155
|
return stop;
|
|
131
156
|
},
|
|
132
157
|
},
|
|
158
|
+
/**
|
|
159
|
+
* Send a message to the agent while it answers another: the turn being
|
|
160
|
+
* answered takes it at its next step (once the model's tool calls have
|
|
161
|
+
* their results), if its framework takes steered messages and it reaches
|
|
162
|
+
* one; otherwise the message is answered as a turn of its own, after the
|
|
163
|
+
* messages before it, in the order it was sent. With no message being
|
|
164
|
+
* answered, it starts a turn. Either way it is answered once: send it with
|
|
165
|
+
* an idempotency key, so that a retried request is the same message. It
|
|
166
|
+
* takes the message as plain text or as a JSON string, as `chat` does.
|
|
167
|
+
*/
|
|
168
|
+
steer: {
|
|
169
|
+
input: messageSerde,
|
|
170
|
+
accept: '*/*',
|
|
171
|
+
handler: async (ctx: restate.ViewContext, text: string): Promise<Steered> => {
|
|
172
|
+
if (!steerable) {
|
|
173
|
+
throw new restate.TerminalError(
|
|
174
|
+
`${ctx.request.target.service} takes no steered messages: its \`chat\` handler is no framework's \`chat()\` (chatHandler)`,
|
|
175
|
+
{ errorCode: 400 },
|
|
176
|
+
);
|
|
177
|
+
}
|
|
178
|
+
return companion(ctx, 'steer').steer({ id: ctx.request.id, text });
|
|
179
|
+
},
|
|
180
|
+
},
|
|
133
181
|
sync: {
|
|
134
182
|
...WAITS,
|
|
135
183
|
handler: async (
|
|
136
184
|
ctx: restate.ViewContext,
|
|
137
|
-
{ cursor = 0, revision, timeoutSeconds = 50, limit = 100 }: SyncRequest = {},
|
|
185
|
+
{ cursor = 0, revision, timeoutSeconds = 50, limit = 100, view }: SyncRequest = {},
|
|
138
186
|
): Promise<Synced> => {
|
|
139
187
|
if (revision !== undefined) await companion(ctx, 'watch').watch({ revision, timeoutSeconds });
|
|
140
188
|
// The revision first: a change after it shows in the next sync. Then
|
|
141
|
-
// what the object does, and its conversation,
|
|
189
|
+
// what the object does, and its conversation, in an invocation of its
|
|
190
|
+
// own, which starts after the revision: a view reads the database as
|
|
191
|
+
// committed when it started, and this one started before the revision
|
|
192
|
+
// (by the whole wait, when it waited). So the page has every change the
|
|
193
|
+
// revision counts.
|
|
142
194
|
const now = await companion(ctx).notifications();
|
|
143
195
|
const status = await companion(ctx).status();
|
|
144
|
-
|
|
196
|
+
const request: MessagesRequest = { cursor, limit, ...(view ? { view } : {}) };
|
|
197
|
+
const page = (await ctx.rpc({
|
|
198
|
+
service: ctx.request.target.service,
|
|
199
|
+
key: ctx.key,
|
|
200
|
+
handler: 'messages',
|
|
201
|
+
input: request,
|
|
202
|
+
})) as Messages;
|
|
203
|
+
return { revision: now.revision, status, ...page };
|
|
145
204
|
},
|
|
146
205
|
},
|
|
147
206
|
});
|
|
148
207
|
|
|
208
|
+
/** The views of every agent: {@link followed}'s. */
|
|
209
|
+
const FOLLOWED = followed(false);
|
|
210
|
+
|
|
149
211
|
/**
|
|
150
212
|
* The agents' handlers that only their own views call (Restate's ingress
|
|
151
213
|
* refuses them), and their types leave out: `erase`, `clear`'s work, once
|
|
152
214
|
* the handlers before it are done. It empties the key's database and its
|
|
153
|
-
* signals', and the
|
|
215
|
+
* signals', and the conversation's ids and cursors go on where they got to
|
|
216
|
+
* (conversation.ts).
|
|
154
217
|
*/
|
|
155
|
-
const
|
|
218
|
+
const internal = (items: Items<unknown> | undefined) => ({
|
|
156
219
|
erase: {
|
|
157
220
|
ingressPrivate: true,
|
|
158
221
|
handler: async (ctx: restate.SessionContext) => {
|
|
159
|
-
|
|
222
|
+
// Read first, which also makes the reset apply the conversation's schema again.
|
|
223
|
+
await SCHEMA.ensure(ctx.db);
|
|
224
|
+
const start = await nextStart(ctx.db);
|
|
225
|
+
// A framework's database of its own first: the conversation's rows say what is left.
|
|
226
|
+
await items?.erase?.(ctx);
|
|
160
227
|
await ctx.db.transaction(async (tx) => {
|
|
161
228
|
await reset(tx);
|
|
162
|
-
await
|
|
229
|
+
await restart(tx, start);
|
|
163
230
|
});
|
|
164
|
-
await cleared(ctx);
|
|
165
231
|
await ctx.rpc(signals, signalsOf(ctx), { idempotencyKey: `${ctx.request.id}:reset` }).reset();
|
|
166
232
|
},
|
|
167
233
|
},
|
|
168
|
-
|
|
234
|
+
/**
|
|
235
|
+
* Close the latest turn, unanswered, if invocation `invocationId` ran it
|
|
236
|
+
* and is gone: the companion sends this once it finds the turn's
|
|
237
|
+
* invocation ended without answering (killed, say), so that the
|
|
238
|
+
* conversation shows the turn closed before the next message. Whether it
|
|
239
|
+
* closed it.
|
|
240
|
+
*/
|
|
241
|
+
settle: {
|
|
242
|
+
ingressPrivate: true,
|
|
243
|
+
handler: async (ctx: restate.SessionContext, invocationId: string) => {
|
|
244
|
+
if (!items || !(await settle(ctx, items, invocationId))) return false;
|
|
245
|
+
// The companion published as it closed the turn, before this stored how it ended: publish that too.
|
|
246
|
+
await publish(ctx);
|
|
247
|
+
return true;
|
|
248
|
+
},
|
|
249
|
+
},
|
|
250
|
+
/** Summarize the earliest turns, past the agent's budget. Whether it did. */
|
|
251
|
+
compact: {
|
|
252
|
+
ingressPrivate: true,
|
|
253
|
+
handler: async (ctx: restate.SessionContext) => (items ? compact(ctx, items) : false),
|
|
254
|
+
},
|
|
255
|
+
});
|
|
169
256
|
|
|
170
|
-
/**
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
257
|
+
/**
|
|
258
|
+
* The private `steered` of an agent whose `chat` is `chat` (`chatHandler`'s):
|
|
259
|
+
* it answers a message sent to `steer` as a turn of its own, with that
|
|
260
|
+
* `chat`, unless the turn it was sent to took it. The companion sends it as
|
|
261
|
+
* the message is sent, so that it keeps its place in the key's queue: it runs
|
|
262
|
+
* once the messages before it are answered.
|
|
263
|
+
*/
|
|
264
|
+
const steeredOf = ({ answer, steers }: { answer: Chat; steers: Steers }) => ({
|
|
265
|
+
ingressPrivate: true,
|
|
266
|
+
explicitCancellation: true,
|
|
267
|
+
handler: async (ctx: restate.SessionContext, { id, text }: Steer) => {
|
|
268
|
+
if (await steerStored(ctx.db, id)) return;
|
|
269
|
+
await chatTurn(ctx, text, answer, steers);
|
|
270
|
+
},
|
|
174
271
|
});
|
|
175
272
|
|
|
176
273
|
/**
|
|
@@ -179,6 +276,8 @@ const startAfter = ({ messages: [latest], cursor, first = 0 }: Messages): log.St
|
|
|
179
276
|
* `revision`, if given, or at `timeoutSeconds` (default 50, at most 60).
|
|
180
277
|
*/
|
|
181
278
|
export interface SyncRequest {
|
|
279
|
+
/** The messages' view: `full` (the default), or `summary` (see `MessagesRequest`). */
|
|
280
|
+
view?: MessagesRequest['view'];
|
|
182
281
|
cursor?: number;
|
|
183
282
|
revision?: number;
|
|
184
283
|
timeoutSeconds?: number;
|
|
@@ -203,6 +302,20 @@ export interface Definition<P extends string> {
|
|
|
203
302
|
* sees each turn once it ended. `messages` has every turn as before.
|
|
204
303
|
*/
|
|
205
304
|
background?: boolean;
|
|
305
|
+
/**
|
|
306
|
+
* For an agent on the conversation of turns: how many of the latest
|
|
307
|
+
* answered turns its model sees whole, with their tool calls and results
|
|
308
|
+
* (default 1), or `'all'`.
|
|
309
|
+
*/
|
|
310
|
+
window?: Window;
|
|
311
|
+
/** For an agent on the conversation of turns: how many tokens of the turns before the window its model sees (default 32 000). */
|
|
312
|
+
budget?: number;
|
|
313
|
+
/**
|
|
314
|
+
* For an agent on the conversation of turns: how it summarizes the turns
|
|
315
|
+
* before the window once they outgrow `budget`, in an invocation of its
|
|
316
|
+
* own (`compact`), after the answer. Without, they are only left out.
|
|
317
|
+
*/
|
|
318
|
+
summarize?: Summarize;
|
|
206
319
|
}
|
|
207
320
|
|
|
208
321
|
/** Each entry's function, as clients see it; none for entries left out. */
|
|
@@ -211,13 +324,13 @@ type Functions<H> = string extends keyof H ? unknown : { [K in keyof H]: H[K] ex
|
|
|
211
324
|
/** The names of the handlers and views every object (or agent) has, which its own cannot take. */
|
|
212
325
|
type Reserved = {
|
|
213
326
|
[
|
|
214
|
-
name in keyof typeof BUILT_IN | keyof
|
|
327
|
+
name in keyof typeof BUILT_IN | keyof typeof FOLLOWED | keyof ReturnType<typeof internal> | 'steered'
|
|
215
328
|
]?: 'a handler every object has: name yours otherwise';
|
|
216
329
|
};
|
|
217
330
|
|
|
218
331
|
/** What an object with `handlers` and `views` has: those of every object, an agent's `clear` and `sync`, and its own. */
|
|
219
332
|
type With<H, V> = Functions<typeof BUILT_IN> &
|
|
220
|
-
(V extends { messages: unknown } ? Functions<
|
|
333
|
+
(V extends { messages: unknown } ? Functions<typeof FOLLOWED> : unknown) &
|
|
221
334
|
Functions<H> &
|
|
222
335
|
Functions<V>;
|
|
223
336
|
|
|
@@ -245,8 +358,7 @@ type With<H, V> = Functions<typeof BUILT_IN> &
|
|
|
245
358
|
* `schema`, optional: tables of your own, beside the agent's (which are its
|
|
246
359
|
* own business), made in each key's database as a session object makes
|
|
247
360
|
* them. Any name is yours but those starting with `restate_`, the agent's
|
|
248
|
-
* (`restate_pi_tasks`, `
|
|
249
|
-
* OpenCode's tables are in a database of their own.
|
|
361
|
+
* (`restate_pi_tasks`, `restate_agent_turns`, `restate_agent_items`...).
|
|
250
362
|
*
|
|
251
363
|
* `options` and `metadata` add to (or replace) the ones set here, such as
|
|
252
364
|
* `options: { retryPolicy: ... }`.
|
|
@@ -264,11 +376,12 @@ export const sessionObject = <
|
|
|
264
376
|
},
|
|
265
377
|
): restate.VirtualObjectDefinition<P, With<H, V>> => {
|
|
266
378
|
const { name, description, schema, background, handlers = {}, views = {}, metadata, options } = definition;
|
|
267
|
-
const
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
379
|
+
const { window = WINDOW, budget = BUDGET, summarize } = definition;
|
|
380
|
+
checkWindow(window);
|
|
381
|
+
if (!(Number.isInteger(budget) && budget >= 0)) {
|
|
382
|
+
throw new Error(`${name}: budget must be a number of tokens (0 or more), not ${JSON.stringify(budget)}`);
|
|
383
|
+
}
|
|
384
|
+
const own = [...Object.keys(BUILT_IN), ...Object.keys(FOLLOWED), ...Object.keys(internal(undefined)), 'steered'];
|
|
272
385
|
if ('messages' in handlers) {
|
|
273
386
|
throw new Error(`${name}: \`messages\` is a view: put it in \`views\`, so that the object is an agent`);
|
|
274
387
|
}
|
|
@@ -287,19 +400,37 @@ export const sessionObject = <
|
|
|
287
400
|
const page = (typeof messages === 'function' ? messages : messages?.handler) as
|
|
288
401
|
| ((ctx: restate.ViewContext, request: MessagesRequest) => Promise<Messages>)
|
|
289
402
|
| undefined;
|
|
290
|
-
|
|
403
|
+
// A `chat` that `chatHandler` made: its answer answers the steered messages no turn took (`steered`).
|
|
404
|
+
const chatEntry = (handlers as Record<string, unknown>).chat;
|
|
405
|
+
const chat = typeof chatEntry === 'object' || typeof chatEntry === 'function' ? chatOf(chatEntry!) : undefined;
|
|
406
|
+
const agent = page === undefined ? {} : followed(chat !== undefined);
|
|
407
|
+
// A framework on the conversation of turns: its view carries its items.
|
|
408
|
+
const items = (page && ITEMS.of(page)) as Items<unknown> | undefined;
|
|
409
|
+
// Its `compact` summarizes: without the conversation of turns, it has none, and nothing would.
|
|
410
|
+
if (summarize && !items) {
|
|
411
|
+
throw new Error(
|
|
412
|
+
`${name}: \`summarize\` needs the conversation of turns: a framework's \`messages\` view (\`claude.messages()\`, say)`,
|
|
413
|
+
);
|
|
414
|
+
}
|
|
415
|
+
const { erase, ...stored } = internal(items);
|
|
416
|
+
const steering: Record<string, restate.Entry<restate.SessionContext>> = chat ? { steered: steeredOf(chat) } : {};
|
|
417
|
+
const privates: Record<string, restate.Entry<restate.SessionContext>> = messages === undefined
|
|
418
|
+
? {}
|
|
419
|
+
: items
|
|
420
|
+
? { erase, ...stored, ...steering }
|
|
421
|
+
: { erase, ...steering };
|
|
291
422
|
return withCompanion(
|
|
292
423
|
isAgent(
|
|
293
424
|
restate.sessionObject({
|
|
294
425
|
name,
|
|
295
426
|
description,
|
|
296
427
|
schema,
|
|
297
|
-
handlers: { ...
|
|
428
|
+
handlers: { ...privates, ...yours },
|
|
298
429
|
views: { ...BUILT_IN, ...agent, ...views },
|
|
299
430
|
metadata,
|
|
300
431
|
options: { ...OPTIONS, ...options },
|
|
301
432
|
}),
|
|
302
|
-
{ background,
|
|
433
|
+
{ background, items, window, budget, summarize },
|
|
303
434
|
),
|
|
304
435
|
);
|
|
305
436
|
};
|
package/src/opencode/README.md
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
# OpenCode
|
|
2
2
|
|
|
3
|
-
[OpenCode](https://opencode.ai) 2.
|
|
3
|
+
[OpenCode](https://opencode.ai) 2.2 can run embedded: `@opencode/sdk` hosts
|
|
4
4
|
the whole OpenCode server in your process, with no HTTP listener. Here it
|
|
5
|
-
runs in the agent's virtual object, and OpenCode's database (
|
|
6
|
-
messages,
|
|
7
|
-
|
|
5
|
+
runs in the agent's virtual object, and OpenCode's database (its session,
|
|
6
|
+
messages, inbox and events) is an SQL database of the key's own, in the
|
|
7
|
+
object's state beside `ctx.db` (`database` of @restatedev/sessions): OpenCode
|
|
8
8
|
boots only on a database that is empty or its own, so its tables are alone
|
|
9
|
-
there, and `ctx.db` keeps the conversation
|
|
10
|
-
([SQL in Restate virtual objects](../../../sessions/README.md)). The
|
|
11
|
-
pins OpenCode 2.
|
|
12
|
-
|
|
9
|
+
there, and `ctx.db` keeps the conversation of turns and the tables of yours
|
|
10
|
+
([SQL in Restate virtual objects](../../../sessions/README.md)). The
|
|
11
|
+
integration pins OpenCode 2.2.6 exactly (`@opencode/core`, `sdk`, `server`
|
|
12
|
+
and `plugin`), with the Effect release it is built on (4.1.0); OpenCode
|
|
13
|
+
needs Node 24.
|
|
13
14
|
|
|
14
15
|
## Use
|
|
15
16
|
|
|
@@ -17,18 +18,26 @@ OpenCode needs Node 24.
|
|
|
17
18
|
import { serve } from '@restatedev/agents';
|
|
18
19
|
import * as opencode from '@restatedev/agents/opencode';
|
|
19
20
|
|
|
20
|
-
const coder = opencode.agent({ name: 'coder', workspace:
|
|
21
|
+
const coder = opencode.agent({ name: 'coder', workspace: (ctx) => `/work/${ctx.key}` });
|
|
21
22
|
await serve(coder);
|
|
22
23
|
```
|
|
23
24
|
|
|
24
|
-
| Option | What
|
|
25
|
-
| ----------- |
|
|
26
|
-
| `model` | `provider/model-id`, of any provider OpenCode serves; or else `MODEL`, or else `openai/gpt-6-sol` (`OPENAI_API_KEY`)
|
|
27
|
-
| `system` |
|
|
28
|
-
| `tools` | `tool()`s and Restate's tools of `@restatedev/agents`, or OpenCode tools of your own (`OpenCodeTool`)
|
|
29
|
-
| `output` | A zod object: the answer as data, which the agent replies with as JSON, and `chat` answers with (see [Structured answers](../../README.md#structured-answers))
|
|
30
|
-
| `workspace` | A directory of the local machine
|
|
31
|
-
| `plugins` | OpenCode plugins of your own (`@opencode/plugin`)
|
|
25
|
+
| Option | What |
|
|
26
|
+
| ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
27
|
+
| `model` | `provider/model-id`, of any provider OpenCode serves; or else `MODEL`, or else `openai/gpt-6-sol` (`OPENAI_API_KEY`). A key's session keeps the model it was created with (see [Not yet](#not-yet)) |
|
|
28
|
+
| `system` | Added to OpenCode's own system prompt, on each model request |
|
|
29
|
+
| `tools` | `tool()`s and Restate's tools of `@restatedev/agents`, or OpenCode tools of your own (`OpenCodeTool`: `execute(input, callId)`) |
|
|
30
|
+
| `output` | A zod object: the answer as data, which the agent replies with as JSON, and `chat` answers with (see [Structured answers](../../README.md#structured-answers)) |
|
|
31
|
+
| `workspace` | A directory of the local machine, made if missing, for OpenCode's own tools (read, write, edit, shell, glob, grep...), or a function of the context that gives one (`(ctx) => \`/work/${ctx.key}\``); use a sandbox. Without one, the agent has only `tools` |
|
|
32
|
+
| `plugins` | OpenCode plugins of your own (`@opencode/plugin`) |
|
|
33
|
+
| `retry` | How OpenCode asks the model again after a request failed for a reason that passes (an outage, a rate limit), as pi's `retry`: by default without limit, 2 s to a minute apart (`baseDelayMs`, `maxAgentDelayMs`, `maxRetries`, `enabled`; see [Through crashes](#through-crashes)) |
|
|
34
|
+
| `approval` | With a workspace, `true` has what OpenCode's permission rules ask about wait for a person's approval, the signal `approval`; without it, such an ask is denied ([Permissions](#permissions)) |
|
|
35
|
+
|
|
36
|
+
With a workspace, OpenCode's tools of background work are left out: its
|
|
37
|
+
subagent and question tools are removed, and its shell runs a command in
|
|
38
|
+
the tool call, never as a background job (one asked for is refused, and the
|
|
39
|
+
model told to run it in the foreground). Restate's `subagent` tool is the
|
|
40
|
+
way to delegate: its calls are made once.
|
|
32
41
|
|
|
33
42
|
For a session object of your own, `opencode.chat(options)` is the handler and
|
|
34
43
|
`opencode.messages()` the view (with it, the agent's `clear` empties
|
|
@@ -41,8 +50,8 @@ chat: opencode.chat((ctx) => ({ workspace: `/work/${ctx.key}` })),
|
|
|
41
50
|
|
|
42
51
|
`opencode.prompt(ctx, text, options)` answers a prompt in a handler of your
|
|
43
52
|
own. For more than a prompt, `withOpenCode(ctx, options, work)` runs `work`
|
|
44
|
-
with OpenCode: `prompt(text)` answers a prompt once, and `host`
|
|
45
|
-
client.
|
|
53
|
+
with OpenCode: `prompt(text)` answers a prompt once, and `host()` boots
|
|
54
|
+
OpenCode (once) and gives its client.
|
|
46
55
|
|
|
47
56
|
## Through crashes
|
|
48
57
|
|
|
@@ -50,50 +59,144 @@ client.
|
|
|
50
59
|
host on its database: an Effect `SqlClient` through
|
|
51
60
|
`Database.configuredClient`, OpenCode's seam for an injected client, each
|
|
52
61
|
OpenCode transaction an SQL transaction. The handler is not replayed: a
|
|
53
|
-
retried attempt boots OpenCode again, on the stored database
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
62
|
+
retried attempt boots OpenCode again, on the stored database. OpenCode
|
|
63
|
+
records an execution claim when a turn starts, and every boot sweeps the
|
|
64
|
+
claims left behind. Whose claim it is comes from `ctx.db`: the prompt last
|
|
65
|
+
submitted to OpenCode is recorded there before it is submitted
|
|
66
|
+
(`restate_agents_opencode`). So:
|
|
67
|
+
|
|
68
|
+
- **A message is answered once per invocation** (`answerOnce`): the prompt's
|
|
69
|
+
id is its OpenCode message id (`msg_<id>`), and a retried attempt of an
|
|
70
|
+
answered prompt returns its answer without booting OpenCode. So does one
|
|
71
|
+
whose turn holds its final reply, copied before the attempt died. A
|
|
72
|
+
retried attempt of the recorded prompt boots OpenCode twice: first
|
|
73
|
+
without its sweep, to copy what OpenCode stored of the turn; a final
|
|
74
|
+
reply stored before the attempt died (before its copy, or before
|
|
75
|
+
OpenCode's turn ended) is then the answer, and the second boot closes
|
|
76
|
+
OpenCode's claim without the model, rather than resume the turn, which
|
|
77
|
+
would ask it again; without one, the second boot resumes the turn.
|
|
60
78
|
- **A tool runs only once its call is stored.** OpenCode stores the model's
|
|
61
79
|
reply, with its tool calls, before the tools run.
|
|
62
|
-
- **A
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
80
|
+
- **A crashed attempt's turn goes on.** A boot for the recorded prompt
|
|
81
|
+
resumes its turn, as OpenCode does: a tool call that was running gets an
|
|
82
|
+
"interrupted" result, and the model makes it again under a new id. OpenCode
|
|
83
|
+
gives up on a turn after ten resumes; here the object's retry policy
|
|
84
|
+
decides. A tool that must not run twice needs a way for a retry to name
|
|
85
|
+
the call it retries (the bank agent's `transfer` takes `retryOf`).
|
|
86
|
+
Restate's own tools (`call`, `send`, `workflow`, `subagent`, `signal`)
|
|
87
|
+
need none: made again with the same input, the call is the one the
|
|
88
|
+
cut-off call made.
|
|
71
89
|
- **A tool's error fails the attempt**, and Restate retries it; a
|
|
72
90
|
`restate.TerminalError` of a `@restatedev/agents` tool is its answer to the
|
|
73
91
|
model. The failed attempt stores nothing more, so its retry finds the call
|
|
74
92
|
interrupted, as above.
|
|
75
|
-
- **A
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
93
|
+
- **A killed invocation's turn is closed, never finished.** A boot for any
|
|
94
|
+
other prompt (the next message, or the companion's `settle`) closes the
|
|
95
|
+
claim without asking the model, through OpenCode's own resume budget
|
|
96
|
+
(`maxAttempts: 0`), and waits for that before anything is submitted; then
|
|
97
|
+
the turn's copy catches up, and the conversation closes the turn
|
|
98
|
+
(`ended`). The next prompt tells the model how the turn before it ended,
|
|
99
|
+
and which of its calls did happen (OpenCode's history says only that they
|
|
100
|
+
were interrupted). A final reply OpenCode stored before the kill is kept
|
|
101
|
+
in the turn, then its `Ended` note. A prompt killed once OpenCode queued
|
|
102
|
+
it, before its turn began, never runs: what waits in OpenCode's inbox is
|
|
103
|
+
cancelled.
|
|
104
|
+
- **A stopped turn** (`stop`) is interrupted in OpenCode, and closed
|
|
105
|
+
cancelled, also when a tool's error ended the attempt as it stopped;
|
|
106
|
+
the next prompt tells the model.
|
|
107
|
+
- **A provider's outage never ends the turn.** OpenCode asks the model
|
|
108
|
+
again as its `session.retry` hook decides, with pi's backoff (`retry`):
|
|
109
|
+
2 s after the first failure, twice as long each time, a minute apart at
|
|
110
|
+
most, but never before the provider's `retry-after` (up to 15 minutes, as
|
|
111
|
+
OpenCode takes it, which `maxAgentDelayMs` does not shorten). Unlike pi,
|
|
112
|
+
OpenCode retries a step 10 times at most, and not after its 4th timeout:
|
|
113
|
+
an outage it would retry for the last time, or no longer retries, fails
|
|
114
|
+
the attempt instead (not terminal), as a tool's error does, and the next
|
|
115
|
+
attempt resumes the turn, its retries afresh. With a finite `maxRetries`,
|
|
116
|
+
a failure past that many retries of a step ends the turn instead, as
|
|
117
|
+
does one OpenCode no longer retries; `enabled: false` retries nothing.
|
|
118
|
+
- **A refused prompt** (a wrong API key, an unknown model) is never asked
|
|
119
|
+
again: it fails at once with a terminal error, 424, and closes its turn;
|
|
120
|
+
any other turn OpenCode ends unanswered fails with a terminal error.
|
|
121
|
+
|
|
122
|
+
OpenCode keeps its own history, and compacts it itself: `window`, `budget`
|
|
123
|
+
and summaries do not apply. What OpenCode stores of a turn (the model's
|
|
124
|
+
replies, the tools' results) is copied into the turn after each of
|
|
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 each
|
|
127
|
+
publish, the answer, and any close of the turn. That is what `messages`
|
|
128
|
+
shows ([docs/conversation.md](../../docs/conversation.md)); OpenCode's own
|
|
129
|
+
"Continue" after a restart, its idle markers and its compactions are not
|
|
130
|
+
copied. A reply with tool calls is copied as its stream ends, before the
|
|
131
|
+
calls run; one without, once OpenCode stored how its step ended, and never
|
|
132
|
+
if the step failed or the model's output limit cut it off (OpenCode asks
|
|
133
|
+
the model again, or to go on). A step a crash left without its end is
|
|
134
|
+
never a reply either: a retry of such a turn resumes it, and the model is
|
|
135
|
+
asked again. The two databases share no transaction: a follower may see a
|
|
136
|
+
step late after a crash, never the model.
|
|
137
|
+
|
|
138
|
+
**A message steered to the turn** (`steer`) is submitted to OpenCode as a
|
|
139
|
+
tool call of a round returns, as a steered prompt (`delivery: 'steer'`,
|
|
140
|
+
once, by its id), which OpenCode places at the round's next step, after its
|
|
141
|
+
results; the copy stores it in the turn, in its place. One sent while the
|
|
142
|
+
model writes its final answer is answered as a turn of its own. One
|
|
143
|
+
OpenCode placed as the turn was stopped is the stopped turn's: the turn
|
|
144
|
+
holds it, and it is not answered again as a turn of its own.
|
|
145
|
+
|
|
146
|
+
The files of a `workspace` are not in the database: they last as long as the
|
|
147
|
+
disk does.
|
|
148
|
+
|
|
149
|
+
## Permissions
|
|
150
|
+
|
|
151
|
+
With a workspace, OpenCode's permission rules allow its tools everything
|
|
152
|
+
but a few asks (by default, a read of a `*.env` file). OpenCode alone would
|
|
153
|
+
keep an ask in memory, waiting for a reply nothing gives, and its turn
|
|
154
|
+
would never end. Here each ask is settled through OpenCode's
|
|
155
|
+
`permission.evaluate` hook:
|
|
156
|
+
|
|
157
|
+
- **Without `approval`**, it is denied, as OpenCode denies an ask nobody is
|
|
158
|
+
present for: the model gets the denial as the tool's error. So is an ask
|
|
159
|
+
of no tool call, with `approval` too.
|
|
160
|
+
- **With `approval: true`**, the tool call waits for the signal `approval`
|
|
161
|
+
(`opencode.APPROVAL`) to the agent, as a `signal()` tool waits
|
|
162
|
+
([Signals](../../README.md#signals)). `pending` shows the wait with the
|
|
163
|
+
call's tool and arguments, and the permission asked (`action`,
|
|
164
|
+
`resources`). `true`, `{"approved": true}`, or a text such as `approved`,
|
|
165
|
+
`yes` or `ok` allows the call; anything else denies it, and the model is
|
|
166
|
+
told why (`The user denied tool "shell": <the text, or the reason>`).
|
|
167
|
+
|
|
168
|
+
```ts
|
|
169
|
+
opencode.agent({ name: 'coder', workspace: (ctx) => `/work/${ctx.key}`, approval: true });
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
The wait outlasts a crash, or a suspension: the resumed turn gives the call
|
|
173
|
+
OpenCode's "interrupted" result, the model makes it again under a new id,
|
|
174
|
+
and the call, with the same tool and arguments, joins the wait. The person
|
|
175
|
+
is asked once, and the tool runs once, after the decision. A turn stopped
|
|
176
|
+
while the call waits ends cancelled, and the tool never runs.
|
|
177
|
+
|
|
178
|
+
The wait is the tool call's: a call that asks more than once (a directory,
|
|
179
|
+
then the file) has each ask answered by the first's answer. OpenCode's hook
|
|
180
|
+
does not tell an ask from a probe (an edit's hint on a miss), so a probe
|
|
181
|
+
that would ask waits too.
|
|
182
|
+
|
|
183
|
+
## Not yet
|
|
184
|
+
|
|
185
|
+
- **A change of `model`** for a key that has a session already: the session
|
|
186
|
+
keeps the model it was created with.
|
|
79
187
|
|
|
80
188
|
## Notes
|
|
81
189
|
|
|
82
|
-
- **Embedded.** OpenCode runs in the handler's own process
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
queued while a turn runs is answered in that turn's run. So a new prompt
|
|
93
|
-
waits for an unfinished one.
|
|
94
|
-
- **Cost.** A prompt makes some hundreds of SQL statements; booting OpenCode
|
|
95
|
-
takes about 100 ms per attempt, after a one-time import of about 2 s per
|
|
96
|
-
process.
|
|
190
|
+
- **Embedded.** OpenCode runs in the handler's own process, on OpenCode's
|
|
191
|
+
workerd profile (the one it boots in a Cloudflare Durable Object), with
|
|
192
|
+
the object's database for its own. Without a `workspace` it has no
|
|
193
|
+
filesystem, shell or terminal; with one, its own tools run on the local
|
|
194
|
+
machine. The only other traffic out is the model's, to its provider's API.
|
|
195
|
+
- **Boots lazily**: OpenCode boots as a turn runs, once per attempt.
|
|
196
|
+
Booting takes about 100 ms, after a one-time import of about 2 s per
|
|
197
|
+
process; a prompt makes some hundreds of SQL statements.
|
|
198
|
+
- **A turn that neither runs nor ends** for 5 s fails the attempt: the
|
|
199
|
+
retry boots OpenCode again, which resumes it.
|
|
97
200
|
|
|
98
201
|
## Run
|
|
99
202
|
|
|
@@ -103,23 +206,26 @@ cd packages/examples && OPENAI_API_KEY=… node basic/opencode.ts
|
|
|
103
206
|
|
|
104
207
|
With a Restate server, and the agent registered with it: see
|
|
105
208
|
[Run an example](../../../examples/README.md#run-an-example).
|
|
106
|
-
[`examples/
|
|
107
|
-
|
|
209
|
+
[`examples/advanced/foreman`](../../../examples/advanced/foreman/README.md) has
|
|
210
|
+
OpenCode agents, a worker and a senior with a workspace and a reviewer
|
|
211
|
+
without one, under a pi boss.
|
|
108
212
|
|
|
109
213
|
## Tests
|
|
110
214
|
|
|
111
215
|
The tests run on a scripted model, [`test/fakes/opencode.ts`](../../test/fakes/opencode.ts),
|
|
112
216
|
an AI SDK language model that OpenCode calls through a plugin's `language`
|
|
113
|
-
hook, and makes a fresh tool call id for every call
|
|
114
|
-
from the repository root
|
|
217
|
+
hook, and makes a fresh tool call id for every call
|
|
218
|
+
(`pnpm --filter @restatedev/agents test opencode`, from the repository root,
|
|
219
|
+
on Node 24: on older Node the suites are skipped):
|
|
115
220
|
|
|
116
|
-
- [`test/storage/opencode.test.ts`](../../test/storage/opencode.test.ts):
|
|
117
|
-
the Effect `SqlClient` of `db.ts`.
|
|
118
221
|
- [`test/opencode.test.ts`](../../test/opencode.test.ts):
|
|
119
222
|
each point above, with crashes that stop an attempt in a tool call, or
|
|
120
|
-
at any of its state requests;
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
- [`test/opencode.ts`](../../test/opencode.ts):
|
|
124
|
-
|
|
125
|
-
|
|
223
|
+
at any of its state requests, and kills, at a turn's end too; a stop, a
|
|
224
|
+
refusal, an outage, asking again for `output`, the system prompt,
|
|
225
|
+
`messages`, `clear`, steering, and permission asks, denied or approved.
|
|
226
|
+
- [`test/opencode-spike.test.ts`](../../test/opencode-spike.test.ts): `db.ts`
|
|
227
|
+
alone, a killed turn closed at boot without the model (by OpenCode's
|
|
228
|
+
budget, or by a closer of our own), and a crashed one resumed.
|
|
229
|
+
- [`test/opencode.ts`](../../test/opencode.ts): the bank agent, through
|
|
230
|
+
crashes and kills in [the crash test](../../../e2e/crash.ts)
|
|
231
|
+
(`pnpm --filter e2e crash`).
|