@restatedev/agents 0.4.0 → 0.6.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 (101) hide show
  1. package/README.md +104 -38
  2. package/dist/calls.d.ts +20 -1
  3. package/dist/calls.d.ts.map +1 -1
  4. package/dist/calls.js +46 -7
  5. package/dist/calls.js.map +1 -1
  6. package/dist/claude/index.d.ts +11 -11
  7. package/dist/claude/index.d.ts.map +1 -1
  8. package/dist/claude/index.js +9 -6
  9. package/dist/claude/index.js.map +1 -1
  10. package/dist/client.d.ts +1 -1
  11. package/dist/client.d.ts.map +1 -1
  12. package/dist/common.d.ts +62 -23
  13. package/dist/common.d.ts.map +1 -1
  14. package/dist/common.js +67 -38
  15. package/dist/common.js.map +1 -1
  16. package/dist/{signals.d.ts → companion.d.ts} +106 -43
  17. package/dist/companion.d.ts.map +1 -0
  18. package/dist/companion.js +463 -0
  19. package/dist/companion.js.map +1 -0
  20. package/dist/conversation.d.ts +115 -5
  21. package/dist/conversation.d.ts.map +1 -1
  22. package/dist/conversation.js +308 -79
  23. package/dist/conversation.js.map +1 -1
  24. package/dist/deepseek/index.d.ts +11 -11
  25. package/dist/deepseek/index.d.ts.map +1 -1
  26. package/dist/deepseek/index.js +23 -26
  27. package/dist/deepseek/index.js.map +1 -1
  28. package/dist/index.d.ts +8 -4
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +7 -3
  31. package/dist/index.js.map +1 -1
  32. package/dist/langgraph/checkpointer.d.ts +2 -0
  33. package/dist/langgraph/checkpointer.d.ts.map +1 -1
  34. package/dist/langgraph/checkpointer.js +1 -1
  35. package/dist/langgraph/checkpointer.js.map +1 -1
  36. package/dist/langgraph/graph.d.ts.map +1 -1
  37. package/dist/langgraph/graph.js +32 -13
  38. package/dist/langgraph/graph.js.map +1 -1
  39. package/dist/langgraph/index.d.ts +11 -11
  40. package/dist/langgraph/index.d.ts.map +1 -1
  41. package/dist/langgraph/index.js +19 -13
  42. package/dist/langgraph/index.js.map +1 -1
  43. package/dist/langgraph/nodes.d.ts +2 -1
  44. package/dist/langgraph/nodes.d.ts.map +1 -1
  45. package/dist/langgraph/nodes.js +23 -20
  46. package/dist/langgraph/nodes.js.map +1 -1
  47. package/dist/object.d.ts +24 -22
  48. package/dist/object.d.ts.map +1 -1
  49. package/dist/object.js +16 -11
  50. package/dist/object.js.map +1 -1
  51. package/dist/opencode/db.d.ts +81 -0
  52. package/dist/opencode/db.d.ts.map +1 -0
  53. package/dist/opencode/db.js +249 -0
  54. package/dist/opencode/db.js.map +1 -0
  55. package/dist/opencode/index.d.ts +184 -0
  56. package/dist/opencode/index.d.ts.map +1 -0
  57. package/dist/opencode/index.js +982 -0
  58. package/dist/opencode/index.js.map +1 -0
  59. package/dist/pi/index.d.ts +11 -11
  60. package/dist/pi/index.d.ts.map +1 -1
  61. package/dist/pi/index.js +16 -17
  62. package/dist/pi/index.js.map +1 -1
  63. package/dist/steering.d.ts +2 -1
  64. package/dist/steering.d.ts.map +1 -1
  65. package/dist/steering.js +2 -2
  66. package/dist/steering.js.map +1 -1
  67. package/dist/tools.d.ts +21 -0
  68. package/dist/tools.d.ts.map +1 -1
  69. package/dist/tools.js +54 -14
  70. package/dist/tools.js.map +1 -1
  71. package/dist/webhook.js +1 -1
  72. package/dist/webhook.js.map +1 -1
  73. package/package.json +37 -4
  74. package/src/calls.ts +52 -11
  75. package/src/claude/README.md +4 -2
  76. package/src/claude/index.ts +9 -7
  77. package/src/client.ts +1 -1
  78. package/src/common.ts +99 -40
  79. package/src/companion.ts +674 -0
  80. package/src/conversation.ts +377 -105
  81. package/src/deepseek/README.md +7 -1
  82. package/src/deepseek/index.ts +22 -24
  83. package/src/index.ts +10 -4
  84. package/src/langgraph/README.md +8 -5
  85. package/src/langgraph/checkpointer.ts +1 -1
  86. package/src/langgraph/graph.ts +30 -16
  87. package/src/langgraph/index.ts +24 -17
  88. package/src/langgraph/nodes.ts +24 -20
  89. package/src/object.ts +45 -40
  90. package/src/opencode/README.md +234 -0
  91. package/src/opencode/db.ts +387 -0
  92. package/src/opencode/index.ts +1243 -0
  93. package/src/pi/README.md +6 -1
  94. package/src/pi/index.ts +16 -15
  95. package/src/steering.ts +8 -7
  96. package/src/tools.ts +60 -18
  97. package/src/webhook.ts +1 -1
  98. package/dist/signals.d.ts.map +0 -1
  99. package/dist/signals.js +0 -383
  100. package/dist/signals.js.map +0 -1
  101. package/src/signals.ts +0 -590
package/src/object.ts CHANGED
@@ -2,6 +2,8 @@
2
2
  import * as restate from '@restatedev/sessions';
3
3
  import { reset } from '@restatedev/sessions/internal';
4
4
  import {
5
+ type AgentContext,
6
+ type AgentViewContext,
5
7
  type Answering,
6
8
  BUDGET,
7
9
  type Chat,
@@ -22,18 +24,17 @@ import {
22
24
  } from './common.ts';
23
25
  import { compact, type Items, nextStart, restart, SCHEMA, settle, steerStored } from './conversation.ts';
24
26
  import {
27
+ companionAt,
25
28
  type Notifications,
26
29
  type Resolved,
27
30
  type Signal,
28
- signals,
29
- signalsOf,
30
31
  type Steer,
31
32
  type Steered,
32
33
  type Steering,
33
34
  withCompanion,
34
35
  type Waiting,
35
36
  type Watch,
36
- } from './signals.ts';
37
+ } from './companion.ts';
37
38
 
38
39
  /**
39
40
  * The options of every object here, beside a session object's: retries for
@@ -61,12 +62,13 @@ export interface Stopped {
61
62
  }
62
63
 
63
64
  /**
64
- * A call of the companion's of `ctx`; with `step`, a change, keyed by the
65
- * request and `step`: a restarted view joins the same call. A read has no
66
- * key: asked again, it answers again, and Restate keeps nothing of it.
65
+ * A call of the companion of the object of `ctx` (its own, at its key); with
66
+ * `step`, a change, keyed by the request and `step`: a restarted view joins
67
+ * the same call. A read has no key: asked again, it answers again, and
68
+ * Restate keeps nothing of it.
67
69
  */
68
- const companion = (ctx: restate.ViewContext, step?: string) =>
69
- ctx.rpc(signals, signalsOf(ctx), step === undefined ? {} : { idempotencyKey: `${ctx.request.id}:${step}` });
70
+ const companion = (ctx: AgentViewContext, step?: string) =>
71
+ ctx.rpc(companionAt(ctx), ctx.key, step === undefined ? {} : { idempotencyKey: `${ctx.request.id}:${step}` });
70
72
 
71
73
  /**
72
74
  * Cancel the invocation of the message being answered, if any, and say
@@ -75,7 +77,7 @@ const companion = (ctx: restate.ViewContext, step?: string) =>
75
77
  * invocation again (which does nothing), not the message that started once
76
78
  * it was cancelled.
77
79
  */
78
- async function stopped(ctx: restate.ViewContext, step: string): Promise<Stopped> {
80
+ async function stopped(ctx: AgentViewContext, step: string): Promise<Stopped> {
79
81
  const turn = (await companion(ctx, step).status()).answering;
80
82
  if (turn) ctx.cancel(turn.invocationId);
81
83
  return { stopped: turn?.invocationId ?? null };
@@ -96,18 +98,19 @@ const WAITS = { inactivityTimeout: { minutes: 5 } } satisfies restate.HandlerOpt
96
98
  * it answers, and `notifications` and `watch`, the revision of its
97
99
  * conversation, and a wait for a newer one (an agent's
98
100
  * has `clear` and `sync` too: {@link FOLLOWED}). Each asks the object's
99
- * `signals` companion, which knows what the object does: they run while the
100
- * object's handler works.
101
+ * companion (its own `<name>.prebuilt.restate`, at the same key), which
102
+ * knows what the object does: they run while the object's handler works.
103
+ * They are the only way a client reaches the companion, whose handlers
104
+ * Restate's ingress refuses.
101
105
  */
102
106
  const BUILT_IN = {
103
- signal: async (ctx: restate.ViewContext, signal: Signal): Promise<Resolved> =>
104
- companion(ctx, 'signal').resolve(signal),
105
- pending: async (ctx: restate.ViewContext): Promise<Waiting[]> => companion(ctx).pending(),
106
- status: async (ctx: restate.ViewContext): Promise<Status> => companion(ctx).status(),
107
+ signal: async (ctx: AgentViewContext, signal: Signal): Promise<Resolved> => companion(ctx, 'signal').resolve(signal),
108
+ pending: async (ctx: AgentViewContext): Promise<Waiting[]> => companion(ctx).pending(),
109
+ status: async (ctx: AgentViewContext): Promise<Status> => companion(ctx).status(),
107
110
  /** Cancel the invocation of the message being answered (`status`'s), as Restate's admin API cancels one. */
108
- stop: async (ctx: restate.ViewContext): Promise<Stopped> => stopped(ctx, 'stop'),
111
+ stop: async (ctx: AgentViewContext): Promise<Stopped> => stopped(ctx, 'stop'),
109
112
  /** The revision of the conversation: each change of what `messages` and `status` give increases it. */
110
- notifications: async (ctx: restate.ViewContext): Promise<Notifications> => companion(ctx).notifications(),
113
+ notifications: async (ctx: AgentViewContext): Promise<Notifications> => companion(ctx).notifications(),
111
114
  /**
112
115
  * The revision, once there is one newer than `revision`, or at the timeout (50 s by
113
116
  * default, at most 60 s), whichever comes first: a client then reads what
@@ -116,7 +119,7 @@ const BUILT_IN = {
116
119
  */
117
120
  watch: {
118
121
  ...WAITS,
119
- handler: async (ctx: restate.ViewContext, watch: Watch): Promise<Notifications> =>
122
+ handler: async (ctx: AgentViewContext, watch: Watch): Promise<Notifications> =>
120
123
  companion(ctx, 'watch').watch(watch),
121
124
  },
122
125
  };
@@ -135,7 +138,7 @@ const BUILT_IN = {
135
138
  const followed = (steerable: boolean) => ({
136
139
  /**
137
140
  * Forget the conversation: stop the message being answered (as `stop`),
138
- * then empty the key's database, and what its `signals` hold (waits and
141
+ * then empty the key's database, and what its companion holds (waits and
139
142
  * kept signals). The conversation's ids and cursors go on (see
140
143
  * conversation.ts), so a follower reads on, and drops the messages before `first`.
141
144
  * A message sent before it is answered first, then forgotten too; one sent
@@ -144,7 +147,7 @@ const followed = (steerable: boolean) => ({
144
147
  clear: {
145
148
  // `erase` waits for the messages sent before it.
146
149
  ...WAITS,
147
- handler: async (ctx: restate.ViewContext): Promise<Stopped> => {
150
+ handler: async (ctx: AgentViewContext): Promise<Stopped> => {
148
151
  const stop = await stopped(ctx, 'clear');
149
152
  await ctx.rpc({
150
153
  service: ctx.request.target.service,
@@ -168,7 +171,7 @@ const followed = (steerable: boolean) => ({
168
171
  steer: {
169
172
  input: messageSerde,
170
173
  accept: '*/*',
171
- handler: async (ctx: restate.ViewContext, text: string): Promise<Steered> => {
174
+ handler: async (ctx: AgentViewContext, text: string): Promise<Steered> => {
172
175
  if (!steerable) {
173
176
  throw new restate.TerminalError(
174
177
  `${ctx.request.target.service} takes no steered messages: its \`chat\` handler is no framework's \`chat()\` (chatHandler)`,
@@ -181,7 +184,7 @@ const followed = (steerable: boolean) => ({
181
184
  sync: {
182
185
  ...WAITS,
183
186
  handler: async (
184
- ctx: restate.ViewContext,
187
+ ctx: AgentViewContext,
185
188
  { cursor = 0, revision, timeoutSeconds = 50, limit = 100, view }: SyncRequest = {},
186
189
  ): Promise<Synced> => {
187
190
  if (revision !== undefined) await companion(ctx, 'watch').watch({ revision, timeoutSeconds });
@@ -211,22 +214,24 @@ const FOLLOWED = followed(false);
211
214
  /**
212
215
  * The agents' handlers that only their own views call (Restate's ingress
213
216
  * refuses them), and their types leave out: `erase`, `clear`'s work, once
214
- * the handlers before it are done. It empties the key's database and its
215
- * signals', and the conversation's ids and cursors go on where they got to
217
+ * the handlers before it are done. It empties the key's database and what its
218
+ * companion holds, and the conversation's ids and cursors go on where they got to
216
219
  * (conversation.ts).
217
220
  */
218
221
  const internal = (items: Items<unknown> | undefined) => ({
219
222
  erase: {
220
223
  ingressPrivate: true,
221
- handler: async (ctx: restate.SessionContext) => {
224
+ handler: async (ctx: AgentContext) => {
222
225
  // Read first, which also makes the reset apply the conversation's schema again.
223
226
  await SCHEMA.ensure(ctx.db);
224
227
  const start = await nextStart(ctx.db);
228
+ // A framework's database of its own first: the conversation's rows say what is left.
229
+ await items?.erase?.(ctx);
225
230
  await ctx.db.transaction(async (tx) => {
226
231
  await reset(tx);
227
232
  await restart(tx, start);
228
233
  });
229
- await ctx.rpc(signals, signalsOf(ctx), { idempotencyKey: `${ctx.request.id}:reset` }).reset();
234
+ await ctx.rpc(companionAt(ctx), ctx.key, { idempotencyKey: `${ctx.request.id}:reset` }).reset();
230
235
  },
231
236
  },
232
237
  /**
@@ -238,7 +243,7 @@ const internal = (items: Items<unknown> | undefined) => ({
238
243
  */
239
244
  settle: {
240
245
  ingressPrivate: true,
241
- handler: async (ctx: restate.SessionContext, invocationId: string) => {
246
+ handler: async (ctx: AgentContext, invocationId: string) => {
242
247
  if (!items || !(await settle(ctx, items, invocationId))) return false;
243
248
  // The companion published as it closed the turn, before this stored how it ended: publish that too.
244
249
  await publish(ctx);
@@ -248,7 +253,7 @@ const internal = (items: Items<unknown> | undefined) => ({
248
253
  /** Summarize the earliest turns, past the agent's budget. Whether it did. */
249
254
  compact: {
250
255
  ingressPrivate: true,
251
- handler: async (ctx: restate.SessionContext) => (items ? compact(ctx, items) : false),
256
+ handler: async (ctx: AgentContext) => (items ? compact(ctx, items) : false),
252
257
  },
253
258
  });
254
259
 
@@ -262,7 +267,7 @@ const internal = (items: Items<unknown> | undefined) => ({
262
267
  const steeredOf = ({ answer, steers }: { answer: Chat; steers: Steers }) => ({
263
268
  ingressPrivate: true,
264
269
  explicitCancellation: true,
265
- handler: async (ctx: restate.SessionContext, { id, text }: Steer) => {
270
+ handler: async (ctx: AgentContext, { id, text }: Steer) => {
266
271
  if (await steerStored(ctx.db, id)) return;
267
272
  await chatTurn(ctx, text, answer, steers);
268
273
  },
@@ -295,8 +300,8 @@ export interface Definition<P extends string> {
295
300
  description?: string;
296
301
  schema?: readonly restate.Step[];
297
302
  /**
298
- * Whether it works unwatched, such as a subagent: its turn calls its
299
- * `signals` only at its end, not at each step, so a client that follows it
303
+ * Whether it works unwatched, such as a subagent: its turn publishes to its
304
+ * companion only at its end, not at each step, so a client that follows it
300
305
  * sees each turn once it ended. `messages` has every turn as before.
301
306
  */
302
307
  background?: boolean;
@@ -363,8 +368,8 @@ type With<H, V> = Functions<typeof BUILT_IN> &
363
368
  */
364
369
  export const sessionObject = <
365
370
  P extends string,
366
- H extends Record<string, restate.Entry<restate.SessionContext>>,
367
- V extends Record<string, restate.Entry<restate.ViewContext>>,
371
+ H extends Record<string, restate.Entry<AgentContext>>,
372
+ V extends Record<string, restate.Entry<AgentViewContext>>,
368
373
  >(
369
374
  definition: Definition<P> & {
370
375
  handlers?: H & Reserved;
@@ -389,14 +394,14 @@ export const sessionObject = <
389
394
  }
390
395
  // A model provider's refusal (a missing API key) ends a handler's invocation.
391
396
  const yours = Object.fromEntries(
392
- Object.entries(handlers as Record<string, restate.Entry<restate.SessionContext>>).map(([key, entry]) => [
397
+ Object.entries(handlers as Record<string, restate.Entry<AgentContext>>).map(([key, entry]) => [
393
398
  key,
394
399
  answering(entry),
395
400
  ]),
396
401
  );
397
- const messages = (views as Record<string, restate.Entry<restate.ViewContext>>).messages;
402
+ const messages = (views as Record<string, restate.Entry<AgentViewContext>>).messages;
398
403
  const page = (typeof messages === 'function' ? messages : messages?.handler) as
399
- | ((ctx: restate.ViewContext, request: MessagesRequest) => Promise<Messages>)
404
+ | ((ctx: AgentViewContext, request: MessagesRequest) => Promise<Messages>)
400
405
  | undefined;
401
406
  // A `chat` that `chatHandler` made: its answer answers the steered messages no turn took (`steered`).
402
407
  const chatEntry = (handlers as Record<string, unknown>).chat;
@@ -411,8 +416,8 @@ export const sessionObject = <
411
416
  );
412
417
  }
413
418
  const { erase, ...stored } = internal(items);
414
- const steering: Record<string, restate.Entry<restate.SessionContext>> = chat ? { steered: steeredOf(chat) } : {};
415
- const privates: Record<string, restate.Entry<restate.SessionContext>> = messages === undefined
419
+ const steering: Record<string, restate.Entry<AgentContext>> = chat ? { steered: steeredOf(chat) } : {};
420
+ const privates: Record<string, restate.Entry<AgentContext>> = messages === undefined
416
421
  ? {}
417
422
  : items
418
423
  ? { erase, ...stored, ...steering }
@@ -434,11 +439,11 @@ export const sessionObject = <
434
439
  };
435
440
 
436
441
  /** `entry`, but a model provider's refusal it fails with ends its invocation, as `chat`'s does. */
437
- function answering(entry: restate.Entry<restate.SessionContext>): restate.Entry<restate.SessionContext> {
442
+ function answering(entry: restate.Entry<AgentContext>): restate.Entry<AgentContext> {
438
443
  const { handler, ...options } = typeof entry === 'function' ? { handler: entry } : entry;
439
444
  return {
440
445
  ...options,
441
- handler: async (ctx: restate.SessionContext, input: unknown) => {
446
+ handler: async (ctx: AgentContext, input: unknown) => {
442
447
  try {
443
448
  return await handler(ctx, input);
444
449
  } catch (error) {
@@ -0,0 +1,234 @@
1
+ # OpenCode
2
+
3
+ [OpenCode](https://opencode.ai) 2.2 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 (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
+ boots only on a database that is empty or its own, so its tables are alone
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.
14
+
15
+ ## Use
16
+
17
+ ```ts
18
+ import { serve } from '@restatedev/agents';
19
+ import * as opencode from '@restatedev/agents/opencode';
20
+
21
+ const coder = opencode.agent({ name: 'coder', workspace: (ctx) => `/work/${ctx.key}` });
22
+ await serve(coder);
23
+ ```
24
+
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.
41
+
42
+ For a session object of your own, `opencode.chat(options)` is the handler and
43
+ `opencode.messages()` the view (with it, the agent's `clear` empties
44
+ OpenCode's database too); `options` may be a function of the invocation's
45
+ context, such as a directory for each key:
46
+
47
+ ```ts
48
+ chat: opencode.chat((ctx) => ({ workspace: `/work/${ctx.key}` })),
49
+ ```
50
+
51
+ `opencode.prompt(ctx, text, options)` answers a prompt in a handler of your
52
+ own. For more than a prompt, `withOpenCode(ctx, options, work)` runs `work`
53
+ with OpenCode: `prompt(text)` answers a prompt once, and `host()` boots
54
+ OpenCode (once) and gives its client.
55
+
56
+ ## Through crashes
57
+
58
+ [`db.ts`](db.ts) (`@restatedev/agents/opencode/db`) boots OpenCode's embedded
59
+ host on its database: an Effect `SqlClient` through
60
+ `Database.configuredClient`, OpenCode's seam for an injected client, each
61
+ OpenCode transaction an SQL transaction. The handler is not replayed: a
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.
78
+ - **A tool runs only once its call is stored.** OpenCode stores the model's
79
+ reply, with its tool calls, before the tools run.
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.
89
+ - **A tool's error fails the attempt**, and Restate retries it; a
90
+ `restate.TerminalError` of a `@restatedev/agents` tool is its answer to the
91
+ model. The failed attempt stores nothing more, so its retry finds the call
92
+ interrupted, as above.
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 a tool
127
+ call runs, the answer, and any close of the turn. A copy of a reply with
128
+ tool calls, or of tools' results, is published once it is committed, in a
129
+ `chat` turn (a `prompt()` in a handler of your own publishes nothing), and
130
+ nothing else is: a tool call's start publishes nothing. That is what `messages`
131
+ shows ([docs/conversation.md](../../docs/conversation.md)); OpenCode's own
132
+ "Continue" after a restart, its idle markers and its compactions are not
133
+ copied. A reply with tool calls is copied as its stream ends, before the
134
+ calls run; one without, once OpenCode stored how its step ended, and never
135
+ if the step failed or the model's output limit cut it off (OpenCode asks
136
+ the model again, or to go on). A step a crash left without its end is
137
+ never a reply either: a retry of such a turn resumes it, and the model is
138
+ asked again. The two databases share no transaction: a follower may see a
139
+ step late after a crash, never the model.
140
+
141
+ **A message steered to the turn** (`steer`) is submitted to OpenCode as a
142
+ tool call of a round returns, as a steered prompt (`delivery: 'steer'`,
143
+ once, by its id), which OpenCode places at the round's next step, after its
144
+ results; the copy stores it in the turn, in its place. One sent while the
145
+ model writes its final answer is answered as a turn of its own. One
146
+ OpenCode placed as the turn was stopped is the stopped turn's: the turn
147
+ holds it, and it is not answered again as a turn of its own.
148
+
149
+ The files of a `workspace` are not in the database: they last as long as the
150
+ disk does.
151
+
152
+ ## Permissions
153
+
154
+ With a workspace, OpenCode's permission rules allow its tools everything
155
+ but a few asks (by default, a read of a `*.env` file). OpenCode alone would
156
+ keep an ask in memory, waiting for a reply nothing gives, and its turn
157
+ would never end. Here each ask is settled through OpenCode's
158
+ `permission.evaluate` hook:
159
+
160
+ - **Without `approval`**, it is denied, as OpenCode denies an ask nobody is
161
+ present for: the model gets the denial as the tool's error. So is an ask
162
+ of no tool call, with `approval` too.
163
+ - **With `approval: true`**, the tool call waits for the signal `approval`
164
+ (`opencode.APPROVAL`) to the agent, as a `signal()` tool waits
165
+ ([Signals](../../README.md#signals)). `pending` shows the wait with the
166
+ call's tool and arguments, and the permission asked (`action`,
167
+ `resources`). `true`, `{"approved": true}`, or a text such as `approved`,
168
+ `yes` or `ok` allows the call; anything else denies it, and the model is
169
+ told why (`The user denied tool "shell": <the text, or the reason>`).
170
+
171
+ ```ts
172
+ opencode.agent({ name: 'coder', workspace: (ctx) => `/work/${ctx.key}`, approval: true });
173
+ ```
174
+
175
+ The wait outlasts a crash, or a suspension: the resumed turn gives the call
176
+ OpenCode's "interrupted" result, the model makes it again under a new id,
177
+ and the call, with the same tool and arguments, joins the wait. The person
178
+ is asked once, and the tool runs once, after the decision. A turn stopped
179
+ while the call waits ends cancelled, and the tool never runs.
180
+
181
+ The wait is the tool call's: a call that asks more than once (a directory,
182
+ then the file) has each ask answered by the first's answer. OpenCode's hook
183
+ does not tell an ask from a probe (an edit's hint on a miss), so a probe
184
+ that would ask waits too.
185
+
186
+ ## Not yet
187
+
188
+ - **A change of `model`** for a key that has a session already: the session
189
+ keeps the model it was created with.
190
+
191
+ ## Notes
192
+
193
+ - **Embedded.** OpenCode runs in the handler's own process, on OpenCode's
194
+ workerd profile (the one it boots in a Cloudflare Durable Object), with
195
+ the object's database for its own. Without a `workspace` it has no
196
+ filesystem, shell or terminal; with one, its own tools run on the local
197
+ machine. The only other traffic out is the model's, to its provider's API.
198
+ - **Boots lazily**: OpenCode boots as a turn runs, once per attempt.
199
+ Booting takes about 100 ms, after a one-time import of about 2 s per
200
+ process; a prompt makes some hundreds of SQL statements.
201
+ - **A turn that neither runs nor ends** for 5 s fails the attempt: the
202
+ retry boots OpenCode again, which resumes it.
203
+
204
+ ## Run
205
+
206
+ ```sh
207
+ cd packages/examples && OPENAI_API_KEY=… node basic/opencode.ts
208
+ ```
209
+
210
+ With a Restate server, and the agent registered with it: see
211
+ [Run an example](../../../examples/README.md#run-an-example).
212
+ [`examples/advanced/foreman`](../../../examples/advanced/foreman/README.md) has
213
+ OpenCode agents, a worker and a senior with a workspace and a reviewer
214
+ without one, under a pi boss.
215
+
216
+ ## Tests
217
+
218
+ The tests run on a scripted model, [`test/fakes/opencode.ts`](../../test/fakes/opencode.ts),
219
+ an AI SDK language model that OpenCode calls through a plugin's `language`
220
+ hook, and makes a fresh tool call id for every call
221
+ (`pnpm --filter @restatedev/agents test opencode`, from the repository root,
222
+ on Node 24: on older Node the suites are skipped):
223
+
224
+ - [`test/opencode.test.ts`](../../test/opencode.test.ts):
225
+ each point above, with crashes that stop an attempt in a tool call, or
226
+ at any of its state requests, and kills, at a turn's end too; a stop, a
227
+ refusal, an outage, asking again for `output`, the system prompt,
228
+ `messages`, `clear`, steering, and permission asks, denied or approved.
229
+ - [`test/opencode-spike.test.ts`](../../test/opencode-spike.test.ts): `db.ts`
230
+ alone, a killed turn closed at boot without the model (by OpenCode's
231
+ budget, or by a closer of our own), and a crashed one resumed.
232
+ - [`test/opencode.ts`](../../test/opencode.ts): the bank agent, through
233
+ crashes and kills in [the crash test](../../../e2e/crash.ts)
234
+ (`pnpm --filter e2e crash`).