@restatedev/agents 0.0.0 → 0.1.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 +688 -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 +78 -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 +83 -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 +284 -0
  20. package/dist/common.d.ts.map +1 -0
  21. package/dist/common.js +475 -0
  22. package/dist/common.js.map +1 -0
  23. package/dist/deepseek/index.d.ts +69 -0
  24. package/dist/deepseek/index.d.ts.map +1 -0
  25. package/dist/deepseek/index.js +381 -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 +15 -0
  32. package/dist/index.d.ts.map +1 -0
  33. package/dist/index.js +37 -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 +67 -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 +181 -0
  48. package/dist/object.d.ts.map +1 -0
  49. package/dist/object.js +232 -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 +101 -0
  56. package/dist/opencode/index.d.ts.map +1 -0
  57. package/dist/opencode/index.js +464 -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 +90 -0
  64. package/dist/pi/index.d.ts.map +1 -0
  65. package/dist/pi/index.js +313 -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 +195 -0
  72. package/dist/signals.d.ts.map +1 -0
  73. package/dist/signals.js +258 -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 +73 -0
  80. package/dist/webhook.d.ts.map +1 -0
  81. package/dist/webhook.js +104 -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 +179 -0
  89. package/src/common.ts +593 -0
  90. package/src/deepseek/README.md +110 -0
  91. package/src/deepseek/index.ts +487 -0
  92. package/src/deepseek/persistence.ts +293 -0
  93. package/src/index.ts +60 -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 +343 -0
  99. package/src/opencode/README.md +125 -0
  100. package/src/opencode/db.ts +223 -0
  101. package/src/opencode/index.ts +595 -0
  102. package/src/output.ts +95 -0
  103. package/src/pi/README.md +105 -0
  104. package/src/pi/index.ts +402 -0
  105. package/src/pi/storage.ts +65 -0
  106. package/src/signals.ts +426 -0
  107. package/src/tools.ts +343 -0
  108. package/src/webhook.ts +163 -0
package/src/object.ts ADDED
@@ -0,0 +1,343 @@
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 {
5
+ cleared,
6
+ onClear,
7
+ inBackground,
8
+ type Messages,
9
+ type MessagesRequest,
10
+ messageSerde,
11
+ refusal,
12
+ type Turn,
13
+ } from './common.ts';
14
+ import * as log from './log.ts';
15
+ import {
16
+ agentOf,
17
+ type Notifications,
18
+ type Resolved,
19
+ type Signal,
20
+ type Steered,
21
+ signals,
22
+ signalsOf,
23
+ withCompanion,
24
+ type Waiting,
25
+ type Watch,
26
+ } from './signals.ts';
27
+
28
+ /**
29
+ * The options of every object here, beside a session object's: retries for
30
+ * weeks, since each attempt resumes from the database: soon after a crash,
31
+ * then twice as long each time, up to 10 seconds apart (a provider's rate
32
+ * limit, say, is not asked again twice a second).
33
+ */
34
+ const OPTIONS = {
35
+ retryPolicy: { initialInterval: 50, exponentiationFactor: 2, maxInterval: 10_000, maxAttempts: 100_000 },
36
+ } satisfies restate.ObjectOptions;
37
+
38
+ /** What an object is doing: the message it answers, if any, and what its tools wait for. */
39
+ export interface Status {
40
+ /** The message being answered (by a `chat` handler), or null. */
41
+ answering: Turn | null;
42
+ /** The waits of its tools, oldest first (see `pending`). */
43
+ waiting: Waiting[];
44
+ }
45
+
46
+ /** What `stop` did: the invocation of the message it stopped, or null if none was answered. */
47
+ export interface Stopped {
48
+ stopped: string | null;
49
+ }
50
+
51
+ /**
52
+ * A call of the companion's of `ctx`; with `step`, a change, keyed by the
53
+ * request and `step`: a restarted view joins the same call. A read has no
54
+ * key: asked again, it answers again, and Restate keeps nothing of it.
55
+ */
56
+ const companion = (ctx: restate.ViewContext, step?: string) =>
57
+ ctx.rpc(signals, signalsOf(ctx), step === undefined ? {} : { idempotencyKey: `${ctx.request.id}:${step}` });
58
+
59
+ /**
60
+ * Cancel the invocation of the message being answered, if any, and say
61
+ * which. The companion's `status` says which, with a key of the request and
62
+ * `step`: a restarted view gets the same answer, and cancels the same
63
+ * invocation again (which does nothing), not the message that started once
64
+ * it was cancelled.
65
+ */
66
+ async function stopped(ctx: restate.ViewContext, step: string): Promise<Stopped> {
67
+ const turn = (await companion(ctx, step).status()).answering;
68
+ if (turn) ctx.cancel(turn.invocationId);
69
+ return { stopped: turn?.invocationId ?? null };
70
+ }
71
+
72
+ /**
73
+ * Views that wait on the companion (`watch`, `sync`, up to a minute) or on
74
+ * the object (`clear`): Restate
75
+ * suspends one that waits past its inactivity timeout, which restarts it,
76
+ * so it is longer than the wait.
77
+ */
78
+ const WAITS = { inactivityTimeout: { minutes: 5 } } satisfies restate.HandlerOptions;
79
+
80
+ /**
81
+ * The views every object here has, beside its own: `signal`, which resolves
82
+ * a wait of the object's tools (see `signal` in tools.ts), `pending`, the
83
+ * waits, `status`, what the object is doing, `stop`, which stops the message
84
+ * it answers, `steer`, which adds to it, and `notifications` and `watch`,
85
+ * the revision of its conversation, and a wait for a newer one (an agent's
86
+ * has `clear` and `sync` too: {@link followed}). Each asks the object's
87
+ * `signals` companion, which knows what the object does: they run while the
88
+ * object's handler works.
89
+ */
90
+ const BUILT_IN = {
91
+ signal: async (ctx: restate.ViewContext, signal: Signal): Promise<Resolved> =>
92
+ companion(ctx, 'signal').resolve(signal),
93
+ pending: async (ctx: restate.ViewContext): Promise<Waiting[]> => companion(ctx).pending(),
94
+ status: async (ctx: restate.ViewContext): Promise<Status> => companion(ctx).status(),
95
+ /** Cancel the invocation of the message being answered (`status`'s), as Restate's admin API cancels one. */
96
+ stop: async (ctx: restate.ViewContext): Promise<Stopped> => stopped(ctx, 'stop'),
97
+ /**
98
+ * Add `text` to the message being answered (`status`'s), such as "Only
99
+ * Monday, please": the agent takes it at its next tool call, as its
100
+ * framework steers a turn. A turn that ends first answers it as a message
101
+ * of its own, as `chat` does when no message is answered.
102
+ */
103
+ steer: {
104
+ input: messageSerde,
105
+ accept: '*/*',
106
+ handler: async (ctx: restate.ViewContext, text: string): Promise<Steered> =>
107
+ companion(ctx, 'steer').steer({ agent: agentOf(ctx), text }),
108
+ },
109
+ /** The revision of the conversation: each change of what `messages` and `status` give increases it. */
110
+ notifications: async (ctx: restate.ViewContext): Promise<Notifications> => companion(ctx).notifications(),
111
+ /**
112
+ * The revision, once there is one newer than `revision`, or at the timeout (50 s by
113
+ * default, at most 60 s), whichever comes first: a client then reads what
114
+ * changed. It waits in Restate, holding no process; a client that retries
115
+ * it with the same idempotency key joins the same wait.
116
+ */
117
+ watch: {
118
+ ...WAITS,
119
+ handler: async (ctx: restate.ViewContext, watch: Watch): Promise<Notifications> =>
120
+ companion(ctx, 'watch').watch(watch),
121
+ },
122
+ };
123
+
124
+ /**
125
+ * The views that agents (an object with a `messages` view) have beside
126
+ * those of every object: `clear`, which forgets the conversation; and
127
+ * `sync`, the conversation since `cursor` (by default, all of it), what the
128
+ * agent is doing, and the revision, in one request; with `revision`, once
129
+ * there is a newer one, or at the timeout. A client follows the
130
+ * conversation by sending each answer's `revision` and `cursor` back, at
131
+ * once while it has `more`.
132
+ */
133
+ const followed = (messages: (ctx: restate.ViewContext, request: MessagesRequest) => Promise<Messages>) => ({
134
+ /**
135
+ * Forget the conversation: stop the message being answered (as `stop`),
136
+ * then empty the key's database, and what its `signals` hold (waits, kept
137
+ * signals, steered messages). The log's ids and cursors go on (see
138
+ * log.ts), so a follower reads on, and drops the messages before `first`.
139
+ * A message sent before it is answered first, then forgotten too; one sent
140
+ * after starts anew.
141
+ */
142
+ clear: {
143
+ // `erase` waits for the messages sent before it.
144
+ ...WAITS,
145
+ handler: async (ctx: restate.ViewContext): Promise<Stopped> => {
146
+ const stop = await stopped(ctx, 'clear');
147
+ await ctx.rpc({
148
+ service: ctx.request.target.service,
149
+ key: ctx.key,
150
+ handler: 'erase',
151
+ idempotencyKey: `${ctx.request.id}:erase`,
152
+ });
153
+ return stop;
154
+ },
155
+ },
156
+ sync: {
157
+ ...WAITS,
158
+ handler: async (
159
+ ctx: restate.ViewContext,
160
+ { cursor = 0, revision, timeoutSeconds = 50, limit = 100 }: SyncRequest = {},
161
+ ): Promise<Synced> => {
162
+ if (revision !== undefined) await companion(ctx, 'watch').watch({ revision, timeoutSeconds });
163
+ // The revision first: a change after it shows in the next sync. Then
164
+ // what the object does, and its conversation, as they are now.
165
+ const now = await companion(ctx).notifications();
166
+ const status = await companion(ctx).status();
167
+ return { revision: now.revision, status, ...(await messages(ctx, { cursor, limit })) };
168
+ },
169
+ },
170
+ });
171
+
172
+ /**
173
+ * The agents' handlers that only their own views call (Restate's ingress
174
+ * refuses them), and their types leave out: `erase`, `clear`'s work, once
175
+ * the handlers before it are done. It empties the key's database and its
176
+ * signals', and the log goes on where it got to (see log.ts).
177
+ */
178
+ const INTERNAL = {
179
+ erase: {
180
+ ingressPrivate: true,
181
+ handler: async (ctx: restate.SessionContext) => {
182
+ const start = startAfter(await log.page(ctx.db, { limit: 1 }));
183
+ await ctx.db.transaction(async (tx) => {
184
+ await reset(tx);
185
+ await log.restart(tx, start);
186
+ });
187
+ await cleared(ctx);
188
+ await ctx.rpc(signals, signalsOf(ctx), { idempotencyKey: `${ctx.request.id}:reset` }).reset();
189
+ },
190
+ },
191
+ };
192
+
193
+ /** Where the log starts after `latest`, its latest message: past its ids and cursor. */
194
+ const startAfter = ({ messages: [latest], cursor, first = 0 }: Messages): log.Start => ({
195
+ seq: cursor,
196
+ id: latest ? latest.id + 1 : first,
197
+ });
198
+
199
+ /**
200
+ * What `sync` reads: what is new or changed since `cursor` (default 0, all
201
+ * of it), at most `limit` messages (default 100); once the revision is past
202
+ * `revision`, if given, or at `timeoutSeconds` (default 50, at most 60).
203
+ */
204
+ export interface SyncRequest {
205
+ cursor?: number;
206
+ revision?: number;
207
+ timeoutSeconds?: number;
208
+ limit?: number;
209
+ }
210
+
211
+ /** What `sync` answers: the messages since the cursor, as `messages` gives them, the status and the revision. */
212
+ export interface Synced extends Messages {
213
+ revision: number;
214
+ status: Status;
215
+ }
216
+
217
+ /** An object's (or agent's) name, its description, and the tables of your own in its database, if any (see `sessionObject`). */
218
+ export interface Definition<P extends string> {
219
+ name: P;
220
+ /** What it is: for the UI, and for the model of a parent that hands it tasks (`subagent`). */
221
+ description?: string;
222
+ schema?: readonly restate.Step[];
223
+ /**
224
+ * Whether it works unwatched, such as a subagent: its turn calls its
225
+ * `signals` only at its end, not at each step, so a client that follows it
226
+ * sees each turn once it ended, and a steered message waits for the turn's
227
+ * end. `messages` has every turn as before.
228
+ */
229
+ background?: boolean;
230
+ }
231
+
232
+ /** Each entry's function, as clients see it; none for entries left out. */
233
+ type Functions<H> = string extends keyof H ? unknown : { [K in keyof H]: H[K] extends { handler: infer F } ? F : H[K] };
234
+
235
+ /** The names of the handlers and views every object (or agent) has, which its own cannot take. */
236
+ type Reserved = {
237
+ [
238
+ name in keyof typeof BUILT_IN | keyof ReturnType<typeof followed> | keyof typeof INTERNAL
239
+ ]?: 'a handler every object has: name yours otherwise';
240
+ };
241
+
242
+ /** What an object with `handlers` and `views` has: those of every object, an agent's `clear` and `sync`, and its own. */
243
+ type With<H, V> = Functions<typeof BUILT_IN> &
244
+ (V extends { messages: unknown } ? Functions<ReturnType<typeof followed>> : unknown) &
245
+ Functions<H> &
246
+ Functions<V>;
247
+
248
+ /**
249
+ * A Restate virtual object with a SQL database per key, `ctx.db`: a
250
+ * `restate.sessionObject` of @restatedev/sessions, set up for agents.
251
+ *
252
+ * const notes = sessionObject({
253
+ * name: 'notes',
254
+ * handlers: {
255
+ * add: (ctx, note: string) => ctx.db.execute('INSERT INTO notes VALUES (?)', [note]),
256
+ * },
257
+ * });
258
+ *
259
+ * Besides its own handlers and views, it has the views `status`, what it is
260
+ * doing (the message it answers, and what its tools wait for), `stop`,
261
+ * which stops that message, `steer`, which adds to it, `pending`, the waits
262
+ * of its tools (`signal()`), `signal({ id, value })`, which resolves one,
263
+ * and `notifications` and `watch({ revision })`, to follow its
264
+ * conversation. An agent, an object with a `messages` view (such as
265
+ * `claude.messages()`), has `clear` too, which forgets its conversation
266
+ * (its database too), and `sync`, which `follow()` of @restatedev/agents/client
267
+ * reads.
268
+ *
269
+ * `schema`, optional: tables of your own, beside the agent's (which are its
270
+ * own business), made in each key's database as a session object makes
271
+ * them. Any name is yours but those starting with `restate_`, the agent's
272
+ * (`restate_pi_tasks`, `restate_claude_messages`, `restate_agent_log`...);
273
+ * OpenCode's tables are in a database of their own.
274
+ *
275
+ * `options` and `metadata` add to (or replace) the ones set here, such as
276
+ * `options: { retryPolicy: ... }`.
277
+ */
278
+ export const sessionObject = <
279
+ P extends string,
280
+ H extends Record<string, restate.Entry<restate.SessionContext>>,
281
+ V extends Record<string, restate.Entry<restate.ViewContext>>,
282
+ >(
283
+ definition: Definition<P> & {
284
+ handlers?: H & Reserved;
285
+ views?: V & Reserved;
286
+ metadata?: Record<string, string>;
287
+ options?: restate.ObjectOptions;
288
+ },
289
+ ): restate.VirtualObjectDefinition<P, With<H, V>> => {
290
+ const { name, description, schema, background, handlers = {}, views = {}, metadata, options } = definition;
291
+ if (background) inBackground(name);
292
+ const own = [
293
+ ...Object.keys(BUILT_IN),
294
+ ...Object.keys(followed(async () => ({}) as Messages)),
295
+ ...Object.keys(INTERNAL),
296
+ ];
297
+ if ('messages' in handlers) {
298
+ throw new Error(`${name}: \`messages\` is a view: put it in \`views\`, so that the object is an agent`);
299
+ }
300
+ for (const key of own) {
301
+ if (key in handlers || key in views)
302
+ throw new Error(`${name}: \`${key}\` is a handler of @restatedev/agents' own: name yours otherwise`);
303
+ }
304
+ // A model provider's refusal (a missing API key) ends a handler's invocation.
305
+ const yours = Object.fromEntries(
306
+ Object.entries(handlers as Record<string, restate.Entry<restate.SessionContext>>).map(([key, entry]) => [
307
+ key,
308
+ answering(entry),
309
+ ]),
310
+ );
311
+ const messages = (views as Record<string, restate.Entry<restate.ViewContext>>).messages;
312
+ onClear(name, messages);
313
+ const page = (typeof messages === 'function' ? messages : messages?.handler) as
314
+ | ((ctx: restate.ViewContext, request: MessagesRequest) => Promise<Messages>)
315
+ | undefined;
316
+ const agent = page === undefined ? {} : followed(page);
317
+ return withCompanion(
318
+ restate.sessionObject({
319
+ name,
320
+ description,
321
+ schema,
322
+ handlers: { ...(messages === undefined ? {} : INTERNAL), ...yours },
323
+ views: { ...BUILT_IN, ...agent, ...views },
324
+ metadata,
325
+ options: { ...OPTIONS, ...options },
326
+ }),
327
+ );
328
+ };
329
+
330
+ /** `entry`, but a model provider's refusal it fails with ends its invocation, as `chat`'s does. */
331
+ function answering(entry: restate.Entry<restate.SessionContext>): restate.Entry<restate.SessionContext> {
332
+ const { handler, ...options } = typeof entry === 'function' ? { handler: entry } : entry;
333
+ return {
334
+ ...options,
335
+ handler: async (ctx: restate.SessionContext, input: unknown) => {
336
+ try {
337
+ return await handler(ctx, input);
338
+ } catch (error) {
339
+ throw refusal(error) ?? error;
340
+ }
341
+ },
342
+ };
343
+ }
@@ -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.