@restatedev/agents 0.0.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +672 -2
  3. package/dist/calls.d.ts +29 -0
  4. package/dist/calls.d.ts.map +1 -0
  5. package/dist/calls.js +91 -0
  6. package/dist/calls.js.map +1 -0
  7. package/dist/claude/conversation.d.ts +33 -0
  8. package/dist/claude/conversation.d.ts.map +1 -0
  9. package/dist/claude/conversation.js +95 -0
  10. package/dist/claude/conversation.js.map +1 -0
  11. package/dist/claude/index.d.ts +77 -0
  12. package/dist/claude/index.d.ts.map +1 -0
  13. package/dist/claude/index.js +269 -0
  14. package/dist/claude/index.js.map +1 -0
  15. package/dist/client.d.ts +81 -0
  16. package/dist/client.d.ts.map +1 -0
  17. package/dist/client.js +88 -0
  18. package/dist/client.js.map +1 -0
  19. package/dist/common.d.ts +261 -0
  20. package/dist/common.d.ts.map +1 -0
  21. package/dist/common.js +438 -0
  22. package/dist/common.js.map +1 -0
  23. package/dist/deepseek/index.d.ts +68 -0
  24. package/dist/deepseek/index.d.ts.map +1 -0
  25. package/dist/deepseek/index.js +363 -0
  26. package/dist/deepseek/index.js.map +1 -0
  27. package/dist/deepseek/persistence.d.ts +61 -0
  28. package/dist/deepseek/persistence.d.ts.map +1 -0
  29. package/dist/deepseek/persistence.js +224 -0
  30. package/dist/deepseek/persistence.js.map +1 -0
  31. package/dist/index.d.ts +8 -0
  32. package/dist/index.d.ts.map +1 -0
  33. package/dist/index.js +12 -0
  34. package/dist/index.js.map +1 -0
  35. package/dist/langgraph/checkpointer.d.ts +29 -0
  36. package/dist/langgraph/checkpointer.d.ts.map +1 -0
  37. package/dist/langgraph/checkpointer.js +275 -0
  38. package/dist/langgraph/checkpointer.js.map +1 -0
  39. package/dist/langgraph/index.d.ts +66 -0
  40. package/dist/langgraph/index.d.ts.map +1 -0
  41. package/dist/langgraph/index.js +265 -0
  42. package/dist/langgraph/index.js.map +1 -0
  43. package/dist/log.d.ts +29 -0
  44. package/dist/log.d.ts.map +1 -0
  45. package/dist/log.js +145 -0
  46. package/dist/log.js.map +1 -0
  47. package/dist/object.d.ts +169 -0
  48. package/dist/object.d.ts.map +1 -0
  49. package/dist/object.js +221 -0
  50. package/dist/object.js.map +1 -0
  51. package/dist/opencode/db.d.ts +40 -0
  52. package/dist/opencode/db.d.ts.map +1 -0
  53. package/dist/opencode/db.js +161 -0
  54. package/dist/opencode/db.js.map +1 -0
  55. package/dist/opencode/index.d.ts +100 -0
  56. package/dist/opencode/index.d.ts.map +1 -0
  57. package/dist/opencode/index.js +436 -0
  58. package/dist/opencode/index.js.map +1 -0
  59. package/dist/output.d.ts +17 -0
  60. package/dist/output.d.ts.map +1 -0
  61. package/dist/output.js +81 -0
  62. package/dist/output.js.map +1 -0
  63. package/dist/pi/index.d.ts +89 -0
  64. package/dist/pi/index.d.ts.map +1 -0
  65. package/dist/pi/index.js +293 -0
  66. package/dist/pi/index.js.map +1 -0
  67. package/dist/pi/storage.d.ts +5 -0
  68. package/dist/pi/storage.d.ts.map +1 -0
  69. package/dist/pi/storage.js +41 -0
  70. package/dist/pi/storage.js.map +1 -0
  71. package/dist/signals.d.ts +154 -0
  72. package/dist/signals.d.ts.map +1 -0
  73. package/dist/signals.js +256 -0
  74. package/dist/signals.js.map +1 -0
  75. package/dist/tools.d.ts +158 -0
  76. package/dist/tools.d.ts.map +1 -0
  77. package/dist/tools.js +211 -0
  78. package/dist/tools.js.map +1 -0
  79. package/dist/webhook.d.ts +71 -0
  80. package/dist/webhook.d.ts.map +1 -0
  81. package/dist/webhook.js +102 -0
  82. package/dist/webhook.js.map +1 -0
  83. package/package.json +218 -5
  84. package/src/calls.ts +138 -0
  85. package/src/claude/README.md +84 -0
  86. package/src/claude/conversation.ts +114 -0
  87. package/src/claude/index.ts +364 -0
  88. package/src/client.ts +176 -0
  89. package/src/common.ts +550 -0
  90. package/src/deepseek/README.md +110 -0
  91. package/src/deepseek/index.ts +464 -0
  92. package/src/deepseek/persistence.ts +293 -0
  93. package/src/index.ts +24 -0
  94. package/src/langgraph/README.md +87 -0
  95. package/src/langgraph/checkpointer.ts +364 -0
  96. package/src/langgraph/index.ts +349 -0
  97. package/src/log.ts +193 -0
  98. package/src/object.ts +319 -0
  99. package/src/opencode/README.md +125 -0
  100. package/src/opencode/db.ts +223 -0
  101. package/src/opencode/index.ts +559 -0
  102. package/src/output.ts +95 -0
  103. package/src/pi/README.md +105 -0
  104. package/src/pi/index.ts +382 -0
  105. package/src/pi/storage.ts +65 -0
  106. package/src/signals.ts +386 -0
  107. package/src/tools.ts +343 -0
  108. package/src/webhook.ts +161 -0
package/src/object.ts ADDED
@@ -0,0 +1,319 @@
1
+ // Virtual objects set up for SQL and agents.
2
+ import * as restate from '@restatedev/sessions';
3
+ import { reset } from '@restatedev/sessions/internal';
4
+ import { cleared, onClear, inBackground, type Messages, type MessagesRequest, refusal, type Turn } from './common.ts';
5
+ import * as log from './log.ts';
6
+ import {
7
+ type Notifications,
8
+ type Resolved,
9
+ type Signal,
10
+ signals,
11
+ signalsOf,
12
+ withCompanion,
13
+ type Waiting,
14
+ type Watch,
15
+ } from './signals.ts';
16
+
17
+ /**
18
+ * The options of every object here, beside a session object's: retries for
19
+ * weeks, since each attempt resumes from the database: soon after a crash,
20
+ * then twice as long each time, up to 10 seconds apart (a provider's rate
21
+ * limit, say, is not asked again twice a second).
22
+ */
23
+ const OPTIONS = {
24
+ retryPolicy: { initialInterval: 50, exponentiationFactor: 2, maxInterval: 10_000, maxAttempts: 100_000 },
25
+ } satisfies restate.ObjectOptions;
26
+
27
+ /** What an object is doing: the message it answers, if any, and what its tools wait for. */
28
+ export interface Status {
29
+ /** The message being answered (by a `chat` handler), or null. */
30
+ answering: Turn | null;
31
+ /** The waits of its tools, oldest first (see `pending`). */
32
+ waiting: Waiting[];
33
+ }
34
+
35
+ /** What `stop` did: the invocation of the message it stopped, or null if none was answered. */
36
+ export interface Stopped {
37
+ stopped: string | null;
38
+ }
39
+
40
+ /**
41
+ * A call of the companion's of `ctx`; with `step`, a change, keyed by the
42
+ * request and `step`: a restarted view joins the same call. A read has no
43
+ * key: asked again, it answers again, and Restate keeps nothing of it.
44
+ */
45
+ const companion = (ctx: restate.ViewContext, step?: string) =>
46
+ ctx.rpc(signals, signalsOf(ctx), step === undefined ? {} : { idempotencyKey: `${ctx.request.id}:${step}` });
47
+
48
+ /**
49
+ * Cancel the invocation of the message being answered, if any, and say
50
+ * which. The companion's `status` says which, with a key of the request and
51
+ * `step`: a restarted view gets the same answer, and cancels the same
52
+ * invocation again (which does nothing), not the message that started once
53
+ * it was cancelled.
54
+ */
55
+ async function stopped(ctx: restate.ViewContext, step: string): Promise<Stopped> {
56
+ const turn = (await companion(ctx, step).status()).answering;
57
+ if (turn) ctx.cancel(turn.invocationId);
58
+ return { stopped: turn?.invocationId ?? null };
59
+ }
60
+
61
+ /**
62
+ * Views that wait on the companion (`watch`, `sync`, up to a minute) or on
63
+ * the object (`clear`): Restate
64
+ * suspends one that waits past its inactivity timeout, which restarts it,
65
+ * so it is longer than the wait.
66
+ */
67
+ const WAITS = { inactivityTimeout: { minutes: 5 } } satisfies restate.HandlerOptions;
68
+
69
+ /**
70
+ * The views every object here has, beside its own: `signal`, which resolves
71
+ * a wait of the object's tools (see `signal` in tools.ts), `pending`, the
72
+ * waits, `status`, what the object is doing, `stop`, which stops the message
73
+ * it answers, and `notifications` and `watch`, the revision of its
74
+ * conversation, and a wait for a newer one (an agent's
75
+ * has `clear` and `sync` too: {@link followed}). Each asks the object's
76
+ * `signals` companion, which knows what the object does: they run while the
77
+ * object's handler works.
78
+ */
79
+ const BUILT_IN = {
80
+ signal: async (ctx: restate.ViewContext, signal: Signal): Promise<Resolved> =>
81
+ companion(ctx, 'signal').resolve(signal),
82
+ pending: async (ctx: restate.ViewContext): Promise<Waiting[]> => companion(ctx).pending(),
83
+ status: async (ctx: restate.ViewContext): Promise<Status> => companion(ctx).status(),
84
+ /** Cancel the invocation of the message being answered (`status`'s), as Restate's admin API cancels one. */
85
+ stop: async (ctx: restate.ViewContext): Promise<Stopped> => stopped(ctx, 'stop'),
86
+ /** The revision of the conversation: each change of what `messages` and `status` give increases it. */
87
+ notifications: async (ctx: restate.ViewContext): Promise<Notifications> => companion(ctx).notifications(),
88
+ /**
89
+ * The revision, once there is one newer than `revision`, or at the timeout (50 s by
90
+ * default, at most 60 s), whichever comes first: a client then reads what
91
+ * changed. It waits in Restate, holding no process; a client that retries
92
+ * it with the same idempotency key joins the same wait.
93
+ */
94
+ watch: {
95
+ ...WAITS,
96
+ handler: async (ctx: restate.ViewContext, watch: Watch): Promise<Notifications> =>
97
+ companion(ctx, 'watch').watch(watch),
98
+ },
99
+ };
100
+
101
+ /**
102
+ * The views that agents (an object with a `messages` view) have beside
103
+ * those of every object: `clear`, which forgets the conversation; and
104
+ * `sync`, the conversation since `cursor` (by default, all of it), what the
105
+ * agent is doing, and the revision, in one request; with `revision`, once
106
+ * there is a newer one, or at the timeout. A client follows the
107
+ * conversation by sending each answer's `revision` and `cursor` back, at
108
+ * once while it has `more`.
109
+ */
110
+ const followed = (messages: (ctx: restate.ViewContext, request: MessagesRequest) => Promise<Messages>) => ({
111
+ /**
112
+ * Forget the conversation: stop the message being answered (as `stop`),
113
+ * then empty the key's database, and what its `signals` hold (waits and
114
+ * kept signals). The log's ids and cursors go on (see
115
+ * log.ts), so a follower reads on, and drops the messages before `first`.
116
+ * A message sent before it is answered first, then forgotten too; one sent
117
+ * after starts anew.
118
+ */
119
+ clear: {
120
+ // `erase` waits for the messages sent before it.
121
+ ...WAITS,
122
+ handler: async (ctx: restate.ViewContext): Promise<Stopped> => {
123
+ const stop = await stopped(ctx, 'clear');
124
+ await ctx.rpc({
125
+ service: ctx.request.target.service,
126
+ key: ctx.key,
127
+ handler: 'erase',
128
+ idempotencyKey: `${ctx.request.id}:erase`,
129
+ });
130
+ return stop;
131
+ },
132
+ },
133
+ sync: {
134
+ ...WAITS,
135
+ handler: async (
136
+ ctx: restate.ViewContext,
137
+ { cursor = 0, revision, timeoutSeconds = 50, limit = 100 }: SyncRequest = {},
138
+ ): Promise<Synced> => {
139
+ if (revision !== undefined) await companion(ctx, 'watch').watch({ revision, timeoutSeconds });
140
+ // The revision first: a change after it shows in the next sync. Then
141
+ // what the object does, and its conversation, as they are now.
142
+ const now = await companion(ctx).notifications();
143
+ const status = await companion(ctx).status();
144
+ return { revision: now.revision, status, ...(await messages(ctx, { cursor, limit })) };
145
+ },
146
+ },
147
+ });
148
+
149
+ /**
150
+ * The agents' handlers that only their own views call (Restate's ingress
151
+ * refuses them), and their types leave out: `erase`, `clear`'s work, once
152
+ * the handlers before it are done. It empties the key's database and its
153
+ * signals', and the log goes on where it got to (see log.ts).
154
+ */
155
+ const INTERNAL = {
156
+ erase: {
157
+ ingressPrivate: true,
158
+ handler: async (ctx: restate.SessionContext) => {
159
+ const start = startAfter(await log.page(ctx.db, { limit: 1 }));
160
+ await ctx.db.transaction(async (tx) => {
161
+ await reset(tx);
162
+ await log.restart(tx, start);
163
+ });
164
+ await cleared(ctx);
165
+ await ctx.rpc(signals, signalsOf(ctx), { idempotencyKey: `${ctx.request.id}:reset` }).reset();
166
+ },
167
+ },
168
+ };
169
+
170
+ /** Where the log starts after `latest`, its latest message: past its ids and cursor. */
171
+ const startAfter = ({ messages: [latest], cursor, first = 0 }: Messages): log.Start => ({
172
+ seq: cursor,
173
+ id: latest ? latest.id + 1 : first,
174
+ });
175
+
176
+ /**
177
+ * What `sync` reads: what is new or changed since `cursor` (default 0, all
178
+ * of it), at most `limit` messages (default 100); once the revision is past
179
+ * `revision`, if given, or at `timeoutSeconds` (default 50, at most 60).
180
+ */
181
+ export interface SyncRequest {
182
+ cursor?: number;
183
+ revision?: number;
184
+ timeoutSeconds?: number;
185
+ limit?: number;
186
+ }
187
+
188
+ /** What `sync` answers: the messages since the cursor, as `messages` gives them, the status and the revision. */
189
+ export interface Synced extends Messages {
190
+ revision: number;
191
+ status: Status;
192
+ }
193
+
194
+ /** An object's (or agent's) name, its description, and the tables of your own in its database, if any (see `sessionObject`). */
195
+ export interface Definition<P extends string> {
196
+ name: P;
197
+ /** What it is: for the UI, and for the model of a parent that hands it tasks (`subagent`). */
198
+ description?: string;
199
+ schema?: readonly restate.Step[];
200
+ /**
201
+ * Whether it works unwatched, such as a subagent: its turn calls its
202
+ * `signals` only at its end, not at each step, so a client that follows it
203
+ * sees each turn once it ended. `messages` has every turn as before.
204
+ */
205
+ background?: boolean;
206
+ }
207
+
208
+ /** Each entry's function, as clients see it; none for entries left out. */
209
+ type Functions<H> = string extends keyof H ? unknown : { [K in keyof H]: H[K] extends { handler: infer F } ? F : H[K] };
210
+
211
+ /** The names of the handlers and views every object (or agent) has, which its own cannot take. */
212
+ type Reserved = {
213
+ [
214
+ name in keyof typeof BUILT_IN | keyof ReturnType<typeof followed> | keyof typeof INTERNAL
215
+ ]?: 'a handler every object has: name yours otherwise';
216
+ };
217
+
218
+ /** What an object with `handlers` and `views` has: those of every object, an agent's `clear` and `sync`, and its own. */
219
+ type With<H, V> = Functions<typeof BUILT_IN> &
220
+ (V extends { messages: unknown } ? Functions<ReturnType<typeof followed>> : unknown) &
221
+ Functions<H> &
222
+ Functions<V>;
223
+
224
+ /**
225
+ * A Restate virtual object with a SQL database per key, `ctx.db`: a
226
+ * `restate.sessionObject` of @restatedev/sessions, set up for agents.
227
+ *
228
+ * const notes = sessionObject({
229
+ * name: 'notes',
230
+ * handlers: {
231
+ * add: (ctx, note: string) => ctx.db.execute('INSERT INTO notes VALUES (?)', [note]),
232
+ * },
233
+ * });
234
+ *
235
+ * Besides its own handlers and views, it has the views `status`, what it is
236
+ * doing (the message it answers, and what its tools wait for), `stop`,
237
+ * which stops that message, `pending`, the waits
238
+ * of its tools (`signal()`), `signal({ id, value })`, which resolves one,
239
+ * and `notifications` and `watch({ revision })`, to follow its
240
+ * conversation. An agent, an object with a `messages` view (such as
241
+ * `claude.messages()`), has `clear` too, which forgets its conversation
242
+ * (its database too), and `sync`, which `follow()` of @restatedev/agents/client
243
+ * reads.
244
+ *
245
+ * `schema`, optional: tables of your own, beside the agent's (which are its
246
+ * own business), made in each key's database as a session object makes
247
+ * them. Any name is yours but those starting with `restate_`, the agent's
248
+ * (`restate_pi_tasks`, `restate_claude_messages`, `restate_agent_log`...);
249
+ * OpenCode's tables are in a database of their own.
250
+ *
251
+ * `options` and `metadata` add to (or replace) the ones set here, such as
252
+ * `options: { retryPolicy: ... }`.
253
+ */
254
+ export const sessionObject = <
255
+ P extends string,
256
+ H extends Record<string, restate.Entry<restate.SessionContext>>,
257
+ V extends Record<string, restate.Entry<restate.ViewContext>>,
258
+ >(
259
+ definition: Definition<P> & {
260
+ handlers?: H & Reserved;
261
+ views?: V & Reserved;
262
+ metadata?: Record<string, string>;
263
+ options?: restate.ObjectOptions;
264
+ },
265
+ ): restate.VirtualObjectDefinition<P, With<H, V>> => {
266
+ const { name, description, schema, background, handlers = {}, views = {}, metadata, options } = definition;
267
+ if (background) inBackground(name);
268
+ const own = [
269
+ ...Object.keys(BUILT_IN),
270
+ ...Object.keys(followed(async () => ({}) as Messages)),
271
+ ...Object.keys(INTERNAL),
272
+ ];
273
+ if ('messages' in handlers) {
274
+ throw new Error(`${name}: \`messages\` is a view: put it in \`views\`, so that the object is an agent`);
275
+ }
276
+ for (const key of own) {
277
+ if (key in handlers || key in views)
278
+ throw new Error(`${name}: \`${key}\` is a handler of @restatedev/agents' own: name yours otherwise`);
279
+ }
280
+ // A model provider's refusal (a missing API key) ends a handler's invocation.
281
+ const yours = Object.fromEntries(
282
+ Object.entries(handlers as Record<string, restate.Entry<restate.SessionContext>>).map(([key, entry]) => [
283
+ key,
284
+ answering(entry),
285
+ ]),
286
+ );
287
+ const messages = (views as Record<string, restate.Entry<restate.ViewContext>>).messages;
288
+ onClear(name, messages);
289
+ const page = (typeof messages === 'function' ? messages : messages?.handler) as
290
+ | ((ctx: restate.ViewContext, request: MessagesRequest) => Promise<Messages>)
291
+ | undefined;
292
+ const agent = page === undefined ? {} : followed(page);
293
+ return withCompanion(
294
+ restate.sessionObject({
295
+ name,
296
+ description,
297
+ schema,
298
+ handlers: { ...(messages === undefined ? {} : INTERNAL), ...yours },
299
+ views: { ...BUILT_IN, ...agent, ...views },
300
+ metadata,
301
+ options: { ...OPTIONS, ...options },
302
+ }),
303
+ );
304
+ };
305
+
306
+ /** `entry`, but a model provider's refusal it fails with ends its invocation, as `chat`'s does. */
307
+ function answering(entry: restate.Entry<restate.SessionContext>): restate.Entry<restate.SessionContext> {
308
+ const { handler, ...options } = typeof entry === 'function' ? { handler: entry } : entry;
309
+ return {
310
+ ...options,
311
+ handler: async (ctx: restate.SessionContext, input: unknown) => {
312
+ try {
313
+ return await handler(ctx, input);
314
+ } catch (error) {
315
+ throw refusal(error) ?? error;
316
+ }
317
+ },
318
+ };
319
+ }
@@ -0,0 +1,125 @@
1
+ # OpenCode
2
+
3
+ [OpenCode](https://opencode.ai) 2.0 can run embedded: `@opencode/sdk` hosts
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 (sessions,
6
+ messages, the inbox, durable events) is an SQL database of the key's own,
7
+ in the object's state beside `ctx.db` (`database` of @restatedev/sessions): OpenCode
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's log and the tables of yours
10
+ ([SQL in Restate virtual objects](../../../sessions/README.md)). The integration
11
+ pins OpenCode 2.0.32 exactly, with the Effect release it is built on (4.0.1);
12
+ OpenCode needs Node 24.
13
+
14
+ ## Use
15
+
16
+ ```ts
17
+ import { serve } from '@restatedev/agents';
18
+ import * as opencode from '@restatedev/agents/opencode';
19
+
20
+ const coder = opencode.agent({ name: 'coder', workspace: '/work/coder' });
21
+ await serve(coder);
22
+ ```
23
+
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` | The system prompt |
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 to work in, with OpenCode's own tools (read, write, edit, bash, 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` |
31
+ | `plugins` | OpenCode plugins of your own (`@opencode/plugin`), such as one that denies edits outside `src/` ([`examples/intermediate/review.ts`](../../../examples/intermediate/review.ts)) |
32
+
33
+ For a session object of your own, `opencode.chat(options)` is the handler and
34
+ `opencode.messages()` the view (with it, the agent's `clear` empties
35
+ OpenCode's database too); `options` may be a function of the invocation's
36
+ context, such as a directory for each key:
37
+
38
+ ```ts
39
+ chat: opencode.chat((ctx) => ({ workspace: `/work/${ctx.key}` })),
40
+ ```
41
+
42
+ `opencode.prompt(ctx, text, options)` answers a prompt in a handler of your
43
+ own. For more than a prompt, `withOpenCode(ctx, options, work)` runs `work`
44
+ with OpenCode: `prompt(text)` answers a prompt once, and `host` is OpenCode's
45
+ client.
46
+
47
+ ## Through crashes
48
+
49
+ [`db.ts`](db.ts) (`@restatedev/agents/opencode/db`) boots OpenCode's embedded
50
+ host on its database: an Effect `SqlClient` through
51
+ `Database.configuredClient`, OpenCode's seam for an injected client, each
52
+ OpenCode transaction an SQL transaction. The handler is not replayed: a
53
+ retried attempt boots OpenCode again, on the stored database, and OpenCode
54
+ resumes interrupted work on its own: it records an execution claim when a
55
+ turn starts, and resumes every claimed turn when it boots.
56
+
57
+ - **Restate decides how often a turn is retried.** OpenCode fails a turn
58
+ after ten resumes; here `openOpenCode` replaces its restart service with
59
+ one without a limit, and the object's retry policy decides.
60
+ - **A tool runs only once its call is stored.** OpenCode stores the model's
61
+ reply, with its tool calls, before the tools run.
62
+ - **A tool call that was running has an interrupted outcome.** Resuming gives
63
+ it an "interrupted" result, and asks the model to continue without
64
+ repeating completed work. A tool that must not run twice needs a way for a
65
+ retry to name the call it retries (the bank agent's `transfer` takes
66
+ `retryOf`). Restate's own tools
67
+ (`call`, `send`, `workflow`, `subagent`, `signal`) need none: made again
68
+ with the same input, the call is the one the cut-off call made, which
69
+ matters for a long one, such as a wait for an approval, since a suspension
70
+ (after Restate's inactivity timeout) restarts the handler too.
71
+ - **A tool's error fails the attempt**, and Restate retries it; a
72
+ `restate.TerminalError` of a `@restatedev/agents` tool is its answer to the
73
+ model. The failed attempt stores nothing more, so its retry finds the call
74
+ interrupted, as above.
75
+ - **A message is answered once per invocation**: the invocation id is its
76
+ OpenCode message id, and a retried attempt returns the answer of the turn
77
+ that answered it. A prompt that a crash interrupted is finished before the
78
+ next one starts.
79
+
80
+ ## Notes
81
+
82
+ - **Embedded.** OpenCode runs in the handler's own process: its client calls
83
+ the server's HTTP router through an in-process `fetch`. Without a
84
+ `workspace` it spawns nothing (the workerd profile's shell, terminal, file
85
+ and version control services are disabled); with one, its own tools run on
86
+ the local machine. The only other traffic out is the model's, to its
87
+ provider's API.
88
+ - **The Promise API's `OpenCode.create(options)` ignores its second
89
+ argument** (the layer replacements), though its types declare it; the
90
+ Effect API's `create` honours it.
91
+ - **A prompt waits in the inbox before it is a message**, and a prompt
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.
97
+
98
+ ## Run
99
+
100
+ ```sh
101
+ cd packages/examples && OPENAI_API_KEY=… node basic/opencode.ts
102
+ ```
103
+
104
+ With a Restate server, and the agent registered with it: see
105
+ [Run an example](../../../examples/README.md#run-an-example).
106
+ [`examples/intermediate/coding.ts`](../../../examples/intermediate/coding.ts) has OpenCode coders,
107
+ each with a workspace, under a pi coordinator.
108
+
109
+ ## Tests
110
+
111
+ The tests run on a scripted model, [`test/fakes/opencode.ts`](../../test/fakes/opencode.ts),
112
+ 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 (`pnpm --filter @restatedev/agents test opencode`,
114
+ from the repository root):
115
+
116
+ - [`test/storage/opencode.test.ts`](../../test/storage/opencode.test.ts):
117
+ the Effect `SqlClient` of `db.ts`.
118
+ - [`test/opencode.test.ts`](../../test/opencode.test.ts):
119
+ each point above, with crashes that stop an attempt in a tool call, or
120
+ at any of its state requests; the
121
+ system prompt; and `messages`. With a transfer tool that ignores `retryOf`,
122
+ four of its tests fail.
123
+ - [`test/opencode.ts`](../../test/opencode.ts): the
124
+ bank agent, through crashes in [the crash test](../../../e2e/crash.ts)
125
+ (`pnpm --filter e2e crash`): every message moves money exactly once.
@@ -0,0 +1,223 @@
1
+ // OpenCode on the object's database: `openOpenCode(db, fence, options)` boots
2
+ // OpenCode 2.0's embedded host (@opencode/sdk) with its database in a
3
+ // SQL session, `ctx.db`.
4
+ //
5
+ // The host is OpenCode's workerd profile, the one it boots in a Cloudflare
6
+ // Durable Object: no local filesystem, shell, terminal or version control,
7
+ // config given inline, plugins given in code. Only its database differs. The
8
+ // workerd profile reads a Durable Object's SQLite, whose `exec` is
9
+ // synchronous; here OpenCode gets an Effect SqlClient instead, which is
10
+ // asynchronous, through `Database.configuredClient` (OpenCode's), the seam OpenCode keeps
11
+ // for an injected client. Each transaction is an SQL transaction, and the
12
+ // session runs statements one at a time, as OpenCode's own clients do.
13
+ //
14
+ // `fence.closed` refuses every statement from then on: an attempt that is
15
+ // giving up stores nothing more, as Restate fences an attempt that a newer
16
+ // one replaced.
17
+ import { Context, Effect, Exit, Layer, Option, Scope } from 'effect';
18
+ import { Reactivity } from 'effect/reactivity';
19
+ import { SqlClient, Statement } from 'effect/sql';
20
+ import { SqlError, UnknownError } from 'effect/sql/SqlError';
21
+ import type { Connection } from 'effect/sql/SqlConnection';
22
+ import { Database as OpenCodeDatabase } from '@opencode/core/database/database';
23
+ import { SessionRestart } from '@opencode/core/session/execution/restart';
24
+ import { ServerWorkerd } from '@opencode/server/workerd';
25
+ import { fromPromise } from '@opencode/core/plugin/promise';
26
+ import { OpenCode } from '@opencode/sdk/effect';
27
+ import type { Plugin } from '@opencode/plugin';
28
+ import type { DatabaseWriter, Database, SqlValue } from '@restatedev/sessions';
29
+
30
+ /** Closed: every later statement fails. */
31
+ export interface Fence {
32
+ closed: boolean;
33
+ }
34
+
35
+ const error = (operation: string, cause: unknown) =>
36
+ new SqlError({
37
+ reason: new UnknownError({
38
+ cause,
39
+ message: cause instanceof Error ? cause.message : String(cause),
40
+ operation,
41
+ }),
42
+ });
43
+
44
+ /** The connection inside a transaction, for statements of that transaction. */
45
+ const InTransaction = Context.Service<SqlClient.TransactionConnection, SqlClient.TransactionConnection.Service>(
46
+ '@restatedev/agents/OpenCodeTransaction',
47
+ );
48
+
49
+ /**
50
+ * A connection whose statements go to `target`: the session, which runs one
51
+ * call at a time and holds them while a transaction runs, or that
52
+ * transaction's database. Each is refused once `fence` closes.
53
+ */
54
+ function connection(target: DatabaseWriter, fence: Fence): Connection {
55
+ // Effect binds what the compiler made of OpenCode's values: SQL values.
56
+ const exec = <T>(read: (sql: string, params: SqlValue[]) => Promise<T>, sql: string, params: readonly unknown[]) =>
57
+ Effect.tryPromise({
58
+ try: async () => {
59
+ if (fence.closed) throw new Error('the attempt is over');
60
+ return read(sql, params as SqlValue[]);
61
+ },
62
+ catch: (cause) => error('execute', cause),
63
+ });
64
+ const run = (sql: string, params: readonly unknown[] = []) => exec((s, p) => target.query(s, p), sql, params);
65
+ const runValues = (sql: string, params: readonly unknown[] = []) => exec((s, p) => target.values(s, p), sql, params);
66
+ const transformed: Connection['execute'] = (sql, params, transformRows) =>
67
+ transformRows ? Effect.map(run(sql, params), transformRows) : run(sql, params);
68
+ return {
69
+ execute: transformed,
70
+ executeRaw: (sql, params) => run(sql, params),
71
+ executeValues: (sql, params) => runValues(sql, params),
72
+ executeValuesUnprepared: (sql, params) => runValues(sql, params),
73
+ executeUnprepared: transformed,
74
+ executeStream: () => {
75
+ throw new Error('executeStream is not supported');
76
+ },
77
+ };
78
+ }
79
+
80
+ /** An Effect SqlClient over `db`, with its statements refused once `fence` closes. */
81
+ export function sqlClient(db: Database, fence: Fence): Layer.Layer<SqlClient.SqlClient> {
82
+ // `effect` as one SQL transaction: it commits when `effect` succeeds
83
+ // and rolls back when it fails. Its statements go to the transaction's
84
+ // database.
85
+ const withTransaction = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
86
+ Effect.withFiber<A, E | SqlError, R>((fiber) => {
87
+ if (Option.isSome(Context.getOption(fiber.context, InTransaction))) {
88
+ return Effect.fail(error('transaction', new Error('nested transactions are not supported')));
89
+ }
90
+ return Effect.callback<A, E | SqlError, R>((resume) => {
91
+ const rollback = new Error('rollback');
92
+ let interrupted = false;
93
+ let resumed = false;
94
+ // Settles when the transaction has committed, or rejects: with
95
+ // `rollback` once `effect` failed, or with the error of BEGIN or COMMIT.
96
+ const ended: Promise<void> = db.transaction(
97
+ (tx) =>
98
+ new Promise<void>((resolve, reject) => {
99
+ if (interrupted) return reject(rollback);
100
+ const inner = Effect.provideContext(
101
+ effect,
102
+ Context.add(fiber.context, InTransaction, [connection(tx, fence), 0]),
103
+ );
104
+ resumed = true;
105
+ resume(
106
+ // A finalizer, so that the body settles however `effect`
107
+ // ends, an interruption included: otherwise the transaction
108
+ // would hold the session for good.
109
+ Effect.onExit(inner, (exit) => {
110
+ if (Exit.isSuccess(exit)) {
111
+ resolve();
112
+ return Effect.void;
113
+ }
114
+ reject(rollback);
115
+ return Effect.promise(() => settled);
116
+ }).pipe(
117
+ // The commit is part of the transaction: if it fails, so
118
+ // does the transaction.
119
+ Effect.flatMap((value) =>
120
+ Effect.as(Effect.tryPromise({ try: () => ended, catch: (e) => error('commit', e) }), value),
121
+ ),
122
+ ),
123
+ );
124
+ }),
125
+ );
126
+ const settled = ended.catch((cause: unknown) => {
127
+ // BEGIN failed: `effect` never ran.
128
+ if (!resumed && cause !== rollback) resume(Effect.fail(error('transaction', cause)));
129
+ });
130
+ return Effect.suspend(() => {
131
+ interrupted = true;
132
+ return Effect.promise(() => settled);
133
+ });
134
+ });
135
+ });
136
+
137
+ const make = Effect.gen(function* () {
138
+ const client = yield* SqlClient.make({
139
+ acquirer: Effect.succeed(connection(db, fence)),
140
+ compiler: Statement.makeCompilerSqlite(),
141
+ spanAttributes: [['db.system.name', 'sqlite']],
142
+ transactionService: InTransaction,
143
+ });
144
+ return Object.assign(client, { withTransaction, transactionStatements: false });
145
+ });
146
+ return Layer.effect(SqlClient.SqlClient, make).pipe(Layer.provide(Reactivity.layer));
147
+ }
148
+
149
+ export interface OpenOptions {
150
+ /** OpenCode plugins: models, tools, agents. */
151
+ plugins?: Plugin.Plugin[];
152
+ /** OpenCode's config (opencode.json), inline. */
153
+ config?: Record<string, unknown>;
154
+ /**
155
+ * OpenCode's own filesystem, search and shell, on the local machine, for
156
+ * its built-in tools (read, write, edit, bash, glob, grep...) in a
157
+ * session's directory. Without it, the workerd profile has none.
158
+ */
159
+ local?: boolean;
160
+ /**
161
+ * Resume the turns a previous attempt left unfinished, as OpenCode does
162
+ * when it boots (default true). A reader beside a running turn does not.
163
+ */
164
+ resume?: boolean;
165
+ }
166
+
167
+ /** A booted OpenCode: `call` runs one of `client`'s calls (which return Effects); `close` shuts it down. */
168
+ export interface Host {
169
+ client: OpenCode.Interface;
170
+ call<A, E, R>(effect: Effect.Effect<A, E, R>): Promise<A>;
171
+ close(): Promise<void>;
172
+ }
173
+
174
+ /**
175
+ * How OpenCode resumes the turns a previous attempt left unfinished when it
176
+ * boots: each, however often it crashed (Restate's retry policy decides how
177
+ * often an attempt is retried), or, without `resume`, none.
178
+ */
179
+ const restarts = (resume: boolean) =>
180
+ resume
181
+ ? SessionRestart.layer({ maxAttempts: Infinity })
182
+ : Layer.succeed(SessionRestart.Service, { resumeSuspendedSessions: Effect.void });
183
+
184
+ /**
185
+ * Boot OpenCode with its database in `db`. Booting resumes the turns a
186
+ * previous attempt left unfinished. Close the host when done.
187
+ */
188
+ export async function openOpenCode(
189
+ db: Database,
190
+ fence: Fence,
191
+ { plugins = [], config = {}, local = false, resume = true }: OpenOptions,
192
+ ): Promise<Host> {
193
+ // The workerd profile, but for its database, which comes first. (The
194
+ // Promise API's OpenCode.create takes no replacements; the Effect API's does.)
195
+ const profile = { storage: undefined as never, models: { fetch: false } };
196
+ // In 2.0.27's order: database, process spawner, snapshot, version control,
197
+ // filesystem, filesystem search, pty, plugin discovery. Local keeps the
198
+ // stubs of snapshots, the pty and plugin discovery only.
199
+ const [, spawner, snapshot, vcs, fs, search, pty, discovery] = ServerWorkerd.replacements(profile);
200
+ const rest = local ? [snapshot, pty, discovery] : [spawner, snapshot, vcs, fs, search, pty, discovery];
201
+ const scope = Scope.makeUnsafe();
202
+ const client = await Effect.runPromise(
203
+ OpenCode.create(
204
+ {
205
+ ...ServerWorkerd.serverOptions({ ...profile, config: { content: JSON.stringify(config) } }),
206
+ plugins: plugins.map(fromPromise),
207
+ },
208
+ {
209
+ overrides: [
210
+ OpenCodeDatabase.node.replace(OpenCodeDatabase.configuredClient(sqlClient(db, fence))),
211
+ ...rest,
212
+ SessionRestart.node.replace(SessionRestart.node.mapLayer(() => restarts(resume) as never)),
213
+ ],
214
+ },
215
+ ).pipe(Scope.provide(scope)),
216
+ );
217
+ return {
218
+ client,
219
+ // The client's calls need nothing more: OpenCode provided it all.
220
+ call: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.runPromise(effect as Effect.Effect<A, E>),
221
+ close: () => Effect.runPromise(Scope.close(scope, Exit.void)),
222
+ };
223
+ }