@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
@@ -0,0 +1,1243 @@
1
+ // OpenCode 2.2 agents in Restate virtual objects: OpenCode for each
2
+ // invocation, with its database beside the object's.
3
+ //
4
+ // const coder = opencode.agent({ name: 'coder', workspace: (ctx) => `/work/${ctx.key}` });
5
+ //
6
+ // or a handler of an object of your own: `handlers: { chat: opencode.chat() }`,
7
+ // with options for each invocation: `opencode.chat(async (ctx) => ({ workspace }))`
8
+ //
9
+ // or, for more than a prompt:
10
+ //
11
+ // review: (ctx, task) => withOpenCode(ctx, { tools }, async ({ prompt }) => [await prompt(task), await prompt('Review it')]),
12
+ //
13
+ // The model is `model`, MODEL, or else openai/gpt-6-sol, which OpenCode's
14
+ // own providers serve, with the provider's API key (such as OPENAI_API_KEY).
15
+ //
16
+ // OpenCode keeps the model's history in a database of the key's own, beside
17
+ // `ctx.db` (db.ts): OpenCode boots only on a database that is empty or its
18
+ // own. Each prompt is a turn of the object's conversation (../conversation.ts):
19
+ // what clients read, and how turns end. What OpenCode stores of a turn (the
20
+ // model's replies, the tools' results) is copied into the turn after each of
21
+ // OpenCode's commits, in a `ctx.db` transaction of its own, idempotently (by
22
+ // OpenCode's message and part ids), and caught up before a tool call runs, the
23
+ // answer, and any close of the turn. A copy of steps (a reply with tool calls,
24
+ // tools' results) is published once it commits, and nothing else is: followers
25
+ // read the conversation then. OpenCode boots lazily, as a turn runs:
26
+ // an answered prompt's retry boots nothing.
27
+ //
28
+ // OpenCode records an execution claim as a turn starts, and every boot sweeps
29
+ // the claims left behind. Whose claim it is comes from `ctx.db`: the last
30
+ // prompt submitted to OpenCode is recorded there before its submit
31
+ // (`restate_agents_opencode`). A boot for that prompt (a retried attempt)
32
+ // resumes its turn, as OpenCode does; a boot for any other closes it without
33
+ // asking the model (OpenCode's resume budget, `maxAttempts: 0`), and the sweep
34
+ // is awaited before anything is submitted. A retried attempt whose turn holds
35
+ // its final reply (copied, or caught up from OpenCode before the boot that
36
+ // would resume) answers with it: OpenCode's turn is closed, not resumed, which
37
+ // would ask the model again. A turn another invocation left
38
+ // (killed) is closed in OpenCode first, then the copy catches up, then the
39
+ // conversation closes it (`settleOwn` of the items). The next prompt tells the
40
+ // model how the turn before it ended, and which of its calls did happen.
41
+ //
42
+ // A tool's error fails the attempt rather than hand the error to the model:
43
+ // from then on the attempt stores nothing (its fence closes), and the next
44
+ // attempt resumes the turn, in which OpenCode gives the cut-off call an
45
+ // "interrupted" result and the model makes it again under a new id.
46
+ //
47
+ // A provider's outage never ends the turn: OpenCode asks the model again,
48
+ // as its `session.retry` hook decides (`retryPlugin`: pi's backoff, not
49
+ // before the provider's `retry-after`), and an outage it would retry for the
50
+ // last time, or stops retrying (timeouts), fails the attempt instead, as a
51
+ // tool's error does: the next attempt resumes the turn. A refusal is never
52
+ // asked again, and ends the turn (424).
53
+ //
54
+ // A message steered to the turn (the agent's `steer` view, ../steering.ts)
55
+ // is submitted to OpenCode as a tool call of a round returns, before the
56
+ // round's next step: with `delivery: 'steer'`, which joins the turn at that
57
+ // step, after the round's results. Once, by its steer id (`msg_steer_<id>`,
58
+ // which OpenCode takes once, also from a retried attempt). In such a turn,
59
+ // the tool's `execute.after` hook, which OpenCode awaits before it stores the
60
+ // result, copies the result as the tool returned it and publishes the copy,
61
+ // whose answer lists the messages, then submits them: so OpenCode places
62
+ // them at the step that follows, never past the turn's end. The copy stores
63
+ // each as a steered message of the turn, in its place, and tells the
64
+ // companion it is taken.
65
+ //
66
+ // v1 leaves out OpenCode's background work: its subagent and question tools,
67
+ // and background shell jobs.
68
+ //
69
+ // With a workspace, an ask of OpenCode's permission rules (a read of `.env`,
70
+ // by default) is denied, as OpenCode denies one nobody is present for; with
71
+ // `approval`, its tool call waits for a person's approval, through Restate
72
+ // (`permissionPlugin`).
73
+ //
74
+ // TODO: a change of `model` on an existing session.
75
+ import * as restate from '@restatedev/sessions';
76
+ import { database, reset } from '@restatedev/sessions/internal';
77
+ import { mkdir } from 'node:fs/promises';
78
+ import type { Plugin } from '@opencode/plugin';
79
+ import { toSessionError } from '@opencode/core/session/to-session-error';
80
+ import type { StandardSchemaV1 } from '@standard-schema/spec';
81
+ import type { z } from 'zod';
82
+ import {
83
+ AttemptEnded,
84
+ chatHandler,
85
+ CHECK_MODEL,
86
+ type Check,
87
+ checkModelName,
88
+ type Configure,
89
+ configured,
90
+ fromTool,
91
+ inboxOf,
92
+ modelOf,
93
+ providerOf,
94
+ refusal,
95
+ REFUSED,
96
+ RETURNED_UNRECORDED,
97
+ stopSignalOf,
98
+ toolCallStarted,
99
+ } from '../common.ts';
100
+ import { answerOnce, invocationOf, type Call, type Items, type Parsed, STEPS, type Turn } from '../conversation.ts';
101
+ import { conversationView } from '../messages.ts';
102
+ import { tookSteers } from '../steering.ts';
103
+ import { type Definition, sessionObject } from '../object.ts';
104
+ import { type Answer, withChecked } from '../output.ts';
105
+ import { isTool, type Tool as AnyTool, waitFor } from '../tools.ts';
106
+ import { type Fence, type Host, openOpenCode, type Restart } from './db.ts';
107
+
108
+ /** An OpenCode model reference. */
109
+ export interface ModelRef {
110
+ providerID: string;
111
+ id: string;
112
+ }
113
+
114
+ /** `provider/model-id` as OpenCode names it. */
115
+ const modelRef = (name: string): ModelRef => {
116
+ const [providerID, id] = providerOf(name);
117
+ return { providerID, id };
118
+ };
119
+
120
+ /** An OpenCode tool of your own: `execute` gets the input and the tool call's id. */
121
+ export interface OpenCodeTool<Input = unknown> {
122
+ name: string;
123
+ description: string;
124
+ input: StandardSchemaV1<unknown, Input>;
125
+ execute(input: Input, callId: string): Promise<string>;
126
+ }
127
+
128
+ /**
129
+ * `t` as an OpenCode tool. OpenCode checks the arguments against `t.input`,
130
+ * and answers the model with what is wrong; those that fit reach `t.run` as
131
+ * the model gave them, which parses them itself.
132
+ */
133
+ const native = (t: AnyTool, ctx: restate.SessionContext): OpenCodeTool => {
134
+ const standard = t.input['~standard'];
135
+ const input: StandardSchemaV1 = {
136
+ '~standard': {
137
+ ...standard,
138
+ validate: (args) => {
139
+ const result = standard.validate(args) as StandardSchemaV1.Result<unknown>;
140
+ return result.issues ? result : { value: args };
141
+ },
142
+ },
143
+ };
144
+ return { name: t.name, description: t.description, input, execute: (args, callId) => t.run(args, { ctx, callId }) };
145
+ };
146
+
147
+ /** The session every prompt goes to. */
148
+ const SESSION = 'ses_root' as never;
149
+
150
+ /** The key's database where OpenCode's tables are, apart from `ctx.db`. */
151
+ const DATABASE = 'restate-agents.opencode';
152
+
153
+ /** The table of `ctx.db` where the last prompt submitted to OpenCode is recorded: one row. */
154
+ const SUBMITTED = 'restate_agents_opencode';
155
+
156
+ /** OpenCode's message id of prompt `id`: letters, digits, `_` and `-`. */
157
+ export const messageIdOf = (id: string) => `msg_${id.replace(/[^\w-]/g, '_')}`;
158
+
159
+ /** OpenCode's message id of the message that asks again within the turn of prompt `id`. */
160
+ const againIdOf = (id: string) => `${messageIdOf(id)}_again`;
161
+
162
+ /** OpenCode's message id of the message `steerId` steered to a turn. */
163
+ const steerIdOf = (steerId: string) => messageIdOf(`steer_${steerId}`);
164
+
165
+ // The items: OpenCode's messages as the conversation keeps them.
166
+
167
+ /** A tool call's result, as an item holds it. */
168
+ interface ItemResult {
169
+ id: string;
170
+ name: string;
171
+ output: string;
172
+ error?: boolean;
173
+ }
174
+
175
+ /**
176
+ * An item of the conversation: a user's message, an assistant's message (a
177
+ * step of OpenCode's: its text and tool calls), or tool calls' results. One
178
+ * copied from OpenCode (a message steered to the turn, say) has `from`: the
179
+ * id of its OpenCode message, and for a result the id of its part too
180
+ * (`<message>/<part>`), by which it is copied once.
181
+ */
182
+ export type Item =
183
+ | { type: 'user'; text: string; from?: string }
184
+ | { type: 'assistant'; text: string; calls?: Call[]; from?: string }
185
+ | { type: 'results'; results: ItemResult[]; from?: string };
186
+
187
+ const KINDS = new Set(['user', 'assistant', 'results']);
188
+
189
+ /** The current attempt's live work on a turn, by turn: what `settleOwn` does while the turn runs here. */
190
+ const live = new WeakMap<object, (status: string) => Promise<void>>();
191
+
192
+ /**
193
+ * OpenCode's items. A user's message is said by the user; an assistant's
194
+ * says its text, with its tool calls; results are results. OpenCode's
195
+ * synthetic messages, idle markers and compactions are never copied.
196
+ */
197
+ export const items: Items<Item> = {
198
+ dump: (item) => JSON.stringify(item),
199
+ load: (stored) => {
200
+ const item = JSON.parse(stored) as Item;
201
+ if (typeof item !== 'object' || item === null || !KINDS.has(item.type)) {
202
+ throw new Error('not an OpenCode item (a user, assistant or results item)');
203
+ }
204
+ return item;
205
+ },
206
+ prompt: (text) => ({ type: 'user', text }),
207
+ reply: (text) => ({ type: 'assistant', text }),
208
+ results: (results) =>
209
+ [
210
+ {
211
+ type: 'results',
212
+ results: results.map(([call, output]) => ({
213
+ id: call.id,
214
+ name: call.name,
215
+ output,
216
+ ...(output === RETURNED_UNRECORDED ? {} : { error: true }),
217
+ })),
218
+ },
219
+ ] satisfies Item[],
220
+ read: (item): Parsed => {
221
+ if (item.type === 'user') return { said: ['user', item.text] };
222
+ if (item.type === 'assistant') return { said: ['assistant', item.text], calls: item.calls ?? [] };
223
+ return { results: item.results.map(({ id, output, error }) => ({ id, output, error })) };
224
+ },
225
+ // A turn another invocation left: OpenCode closes it first (its resume
226
+ // budget, no model), then what OpenCode has of it is copied.
227
+ settleOwn: async (ctx, turn, status) => {
228
+ const own = live.get(turn);
229
+ if (own) return own(status);
230
+ if (status !== 'ended') return;
231
+ const fence: Fence = { closed: false };
232
+ const host = await openOpenCode(database(ctx.db, DATABASE), fence, { restart: 'close' });
233
+ try {
234
+ await host.swept;
235
+ await dropInbox(host);
236
+ await copyInto(ctx, host, turn);
237
+ } finally {
238
+ await host.close();
239
+ }
240
+ },
241
+ erase: (ctx) => database(ctx.db, DATABASE).transaction((tx) => reset(tx)),
242
+ };
243
+
244
+ // OpenCode's messages, as the client gives them.
245
+
246
+ /** A part of an assistant message: text, or a tool call (`id`, `name`, and its `state`). */
247
+ interface Content {
248
+ type: string;
249
+ text?: string;
250
+ id?: string;
251
+ name?: string;
252
+ state?: {
253
+ status?: string;
254
+ input?: unknown;
255
+ content?: string | Content[];
256
+ output?: unknown;
257
+ error?: { message?: string };
258
+ };
259
+ }
260
+
261
+ /** A message of OpenCode's session, as far as the copy and a prompt's outcome go. */
262
+ interface Message {
263
+ id: string;
264
+ type: string;
265
+ outcome?: string;
266
+ text?: string;
267
+ content?: Content[];
268
+ error?: { message?: string; type?: string; status?: number };
269
+ time?: { completed?: unknown; streamed?: unknown };
270
+ /** How the step ended (`stop`, `tool-calls`, `error`...), once OpenCode stored it. */
271
+ finish?: string;
272
+ metadata?: Record<string, unknown>;
273
+ }
274
+
275
+ /** The id of the message steered to a turn that `m` is, if it is one: the steer id it was submitted with. */
276
+ const steerOf = (m: Message): string | undefined => {
277
+ const steer = m.metadata?.steer;
278
+ return m.type === 'user' && typeof steer === 'string' && m.id === steerIdOf(steer) ? steer : undefined;
279
+ };
280
+
281
+ /** The text of `content`. */
282
+ const textOf = (content: string | Content[] = []) =>
283
+ typeof content === 'string'
284
+ ? content
285
+ : content.flatMap((c) => (c.type === 'text' && c.text ? [c.text] : [])).join('');
286
+
287
+ /** The output of a tool part that ended: its content, or its error. */
288
+ const outputOf = (part: Content) => {
289
+ const state = part.state ?? {};
290
+ if (state.status === 'error') return state.error?.message ?? 'Error';
291
+ if (state.content !== undefined) return textOf(state.content);
292
+ return typeof state.output === 'string' ? state.output : JSON.stringify(state.output ?? '');
293
+ };
294
+
295
+ /** The prompts waiting in the session's inbox, until their turn starts, oldest first. */
296
+ const inbox = (host: Host): Promise<{ id: string; payload: { text: string } }[]> =>
297
+ host.call(host.client.session.inbox.list({ sessionID: SESSION }));
298
+
299
+ /**
300
+ * Cancel what waits in the session's inbox. A prompt killed after OpenCode
301
+ * queued it and before its turn's claim leaves no claim for the sweep to
302
+ * close, only its input: the next prompt's drain would run it, under the
303
+ * next invocation.
304
+ */
305
+ async function dropInbox(host: Host) {
306
+ // No session yet (the key's first prompt): nothing waits.
307
+ if (!(await sessionExists(host))) return;
308
+ for (const item of await inbox(host)) {
309
+ await host.call(host.client.session.inbox.cancel({ sessionID: SESSION, inboxID: item.id as never }));
310
+ }
311
+ }
312
+
313
+ /** The session's messages, a page at a time, newest first. */
314
+ async function* newestFirst(host: Host): AsyncGenerator<Message[]> {
315
+ for (let cursor: string | undefined; ;) {
316
+ const page: { data: unknown[]; cursor: { next?: string } } = await host.call(
317
+ host.client.message.list(
318
+ cursor === undefined ? { sessionID: SESSION, order: 'desc', limit: 50 } : { sessionID: SESSION, cursor },
319
+ ),
320
+ );
321
+ yield page.data as Message[];
322
+ cursor = page.cursor.next;
323
+ if (cursor === undefined) return;
324
+ }
325
+ }
326
+
327
+ /** The messages after message `messageId`, oldest first; undefined if the session does not have it. */
328
+ async function messagesAfter(host: Host, messageId: string): Promise<Message[] | undefined> {
329
+ // One lookup says a message is not there (every new prompt's): no paging through the session for it.
330
+ const there = await host
331
+ .call(host.client.session.message.get({ sessionID: SESSION, messageID: messageId as never }))
332
+ .then(
333
+ () => true,
334
+ () => false,
335
+ );
336
+ if (!there) return undefined;
337
+ const after: Message[] = [];
338
+ for await (const page of newestFirst(host)) {
339
+ const at = page.findIndex((m) => m.id === messageId);
340
+ after.unshift(...(at < 0 ? page : page.slice(0, at)).toReversed());
341
+ if (at >= 0) return after;
342
+ }
343
+ return undefined;
344
+ }
345
+
346
+ /** Whether OpenCode's session exists. */
347
+ const sessionExists = (host: Host) =>
348
+ host.call(host.client.session.get({ sessionID: SESSION })).then(
349
+ () => true,
350
+ () => false,
351
+ );
352
+
353
+ /** A tool call's result as its tool returned it, `from` its OpenCode message and part (`<message>/<part>`). */
354
+ interface Returned {
355
+ result: ItemResult;
356
+ from: string;
357
+ }
358
+
359
+ /**
360
+ * Copy into `turn` what OpenCode has of it that the turn lacks: each step's
361
+ * assistant message once its stream ended (its text, its tool calls, before
362
+ * they run; one without calls once its step ended, and not if it failed
363
+ * or the output limit cut it off),
364
+ * each tool call's result once it ended, and each message
365
+ * steered to the turn that OpenCode placed at a step (stored as steered, the
366
+ * companion told it is taken in the transaction). Each once: by OpenCode's
367
+ * ids, a steered message by its steer id too. Not the prompt, nor what asks
368
+ * again (the turn has them), nor OpenCode's synthetic messages, idle markers
369
+ * and compactions. In a `ctx.db` transaction of its own. Whether it copied a
370
+ * step that a follower waits for: a reply with tool calls, or a tool's result.
371
+ *
372
+ * With `own`, a call's result as its tool returned it, before OpenCode
373
+ * stores it: copied too (after its reply), under the id OpenCode's part has.
374
+ */
375
+ async function copyInto(
376
+ ctx: restate.SessionContext,
377
+ host: Host,
378
+ turn: Turn<Item>,
379
+ own?: Returned,
380
+ steersOnly = false,
381
+ ): Promise<boolean> {
382
+ if (!turn.writable) return false;
383
+ const after = await messagesAfter(host, messageIdOf(turn.id));
384
+ if (!after) return false;
385
+ const have = new Set(turn.items.flatMap((e) => (e.item.from ? [e.item.from] : [])));
386
+ const held = new Set(turn.steered().map((e) => e.steer));
387
+ const copied: { item: Item; reply?: boolean; steer?: string }[] = [];
388
+ for (const m of after) {
389
+ const steer = steerOf(m);
390
+ if (steer !== undefined) {
391
+ if (!have.has(m.id) && !held.has(steer)) {
392
+ copied.push({ item: { type: 'user', text: m.text ?? '', from: m.id }, steer });
393
+ have.add(m.id);
394
+ held.add(steer);
395
+ }
396
+ continue;
397
+ }
398
+ if (m.type !== 'assistant' || steersOnly) continue;
399
+ const tools = (m.content ?? []).filter((c) => c.type === 'tool' && c.id !== undefined);
400
+ // A step's message is updated in place as it streams. With tool calls, it is copied once its stream
401
+ // ended, before they run, their input whole. Without, once OpenCode stored how the step ended (its
402
+ // `finish`, after its stream's end): a step that failed (its provider refused, or failed mid-stream)
403
+ // is no reply, as OpenCode asks again in a step of its own, or its error ends the turn. A step left
404
+ // without its end (a crash between the two, then a resume) is never one either: OpenCode marks it
405
+ // completed, without a `finish`, as the resumed turn's next step starts.
406
+ if (tools.length === 0 && m.finish === undefined) {
407
+ if (after.slice(after.indexOf(m) + 1).some((n) => n.type === 'assistant')) continue;
408
+ break;
409
+ }
410
+ // A step with tool calls whose stream never ended (a crash once a call ran, as OpenCode runs a call as it
411
+ // streams) is completed, without a `finish`, as the resumed turn's next step starts: copied, its calls kept.
412
+ const ready =
413
+ m.time?.completed !== undefined ||
414
+ (m.time?.streamed !== undefined && tools.every((t) => t.state?.status !== 'streaming'));
415
+ if (!ready) break;
416
+ if (!have.has(m.id)) {
417
+ const text = textOf(m.content);
418
+ const calls = tools.map((t) => ({ id: t.id!, name: t.name ?? '', input: t.state?.input ?? {} }));
419
+ // A failed step's tool calls are kept, for their results. Without calls, a step that failed (its
420
+ // `error`), or that the model's output limit cut off (`length`: OpenCode asks the model to go on in a
421
+ // step of its own), is no reply; one that ended otherwise (`stop`, or `error` as a provider names it)
422
+ // ends OpenCode's turn with its text.
423
+ if (calls.length === 0 && (m.error !== undefined || m.finish === 'length' || !text.trim())) continue;
424
+ copied.push({ item: { type: 'assistant', text, calls, from: m.id }, reply: true });
425
+ have.add(m.id);
426
+ }
427
+ for (const t of tools) {
428
+ const status = t.state?.status;
429
+ const from = `${m.id}/${t.id}`;
430
+ if ((status !== 'completed' && status !== 'error') || have.has(from)) continue;
431
+ const output = outputOf(t);
432
+ const result: ItemResult = {
433
+ id: t.id!,
434
+ name: t.name ?? '',
435
+ output,
436
+ ...(status === 'error' ? { error: true } : {}),
437
+ };
438
+ copied.push({ item: { type: 'results', results: [result], from } });
439
+ have.add(from);
440
+ }
441
+ }
442
+ if (own && !have.has(own.from) && have.has(own.from.split('/')[0]!)) {
443
+ copied.push({ item: { type: 'results', results: [own.result], from: own.from } });
444
+ }
445
+ if (copied.length === 0) return false;
446
+ const done = await ctx.db.transaction(async (tx) => {
447
+ if (!(await turn.copyIn(tx, copied))) return false;
448
+ tookSteers(
449
+ ctx,
450
+ tx,
451
+ copied.flatMap(({ steer }) => (steer === undefined ? [] : [steer])),
452
+ );
453
+ return true;
454
+ });
455
+ return (
456
+ done &&
457
+ copied.some(({ item }) => item.type === 'results' || (item.type === 'assistant' && (item.calls?.length ?? 0) > 0))
458
+ );
459
+ }
460
+
461
+ /** Where a prompt is: not in the session, its turn running, or ended with an answer or a failure. */
462
+ type Outcome =
463
+ | { state: 'absent' | 'running' }
464
+ | { state: 'answered'; text: string }
465
+ | { state: 'failed'; reason: string; type?: string; status?: number };
466
+
467
+ /** Where prompt `messageId` is (see {@link Outcome}). */
468
+ async function outcome(host: Host, messageId: string): Promise<Outcome> {
469
+ if ((await inbox(host)).some((item) => item.id === messageId)) return { state: 'running' };
470
+ const after = await messagesAfter(host, messageId);
471
+ return after ? turnOutcome(after) : { state: 'absent' };
472
+ }
473
+
474
+ /**
475
+ * How the turn of the messages `after` a prompt ended: at an idle marker, or
476
+ * where a next prompt starts (a message steered to the turn is not one).
477
+ */
478
+ function turnOutcome(after: Message[]): Outcome {
479
+ let last: Message | undefined;
480
+ for (const m of after) {
481
+ if (m.type === 'idle') return ended(last, m);
482
+ if (m.type === 'user' && last !== undefined && steerOf(m) === undefined)
483
+ return ended(last, { id: '', type: 'idle', outcome: 'succeeded' });
484
+ if (m.type === 'assistant') last = m;
485
+ }
486
+ return { state: 'running' };
487
+ }
488
+
489
+ /** The outcome of a turn that ended at `idle`, with `last`, its last assistant message: its text, or its error. */
490
+ function ended(last: Message | undefined, idle: Message): Outcome {
491
+ const error = last?.error ?? idle.error;
492
+ if (idle.outcome === 'succeeded' && last?.error === undefined)
493
+ return { state: 'answered', text: textOf(last?.content) };
494
+ return {
495
+ state: 'failed',
496
+ reason: error?.message ?? idle.outcome ?? 'failed',
497
+ type: error?.type,
498
+ status: error?.status,
499
+ };
500
+ }
501
+
502
+ /** Whether a turn of the session runs in this process. */
503
+ const active = async (host: Host) => {
504
+ const turns: Record<string, unknown> = await host.call(host.client.session.active());
505
+ return turns[SESSION as string] !== undefined;
506
+ };
507
+
508
+ /** How long a prompt's turn may be neither running nor ended: one resumed at boot starts well within it. */
509
+ const STALLED_MS = 5_000;
510
+
511
+ /**
512
+ * The outcome of prompt `messageId`, once its turn has ended. A prompt left
513
+ * in the inbox with nothing to run it (a crash between its queueing and its
514
+ * turn's claim) is started again, by its id. A turn that neither runs nor
515
+ * ends for {@link STALLED_MS} fails the attempt: the retry boots OpenCode
516
+ * again, which resumes the turn of this prompt.
517
+ */
518
+ async function settled(host: Host, messageId: string): Promise<Outcome> {
519
+ for (let idleSince = Date.now(); ;) {
520
+ const now = await outcome(host, messageId);
521
+ if (now.state !== 'running') return now;
522
+ if (!(await active(host))) {
523
+ const [first] = await inbox(host);
524
+ if (first !== undefined) {
525
+ await host.call(
526
+ host.client.session.prompt({
527
+ sessionID: SESSION,
528
+ id: first.id as never,
529
+ text: first.payload.text,
530
+ delivery: 'queue',
531
+ resume: true,
532
+ }),
533
+ );
534
+ }
535
+ }
536
+ await host.call(host.client.session.wait({ sessionID: SESSION }));
537
+ if (await active(host)) {
538
+ idleSince = Date.now();
539
+ continue;
540
+ }
541
+ if (Date.now() - idleSince > STALLED_MS) {
542
+ throw new Error(`prompt ${messageId}: its turn has neither run nor ended for ${STALLED_MS / 1000} s`);
543
+ }
544
+ await new Promise((resolve) => setTimeout(resolve, 20));
545
+ }
546
+ }
547
+
548
+ /** The prompt last submitted to OpenCode, as recorded before its submit. */
549
+ async function submittedOf(ctx: restate.SessionContext): Promise<string | undefined> {
550
+ await ctx.db.execute(
551
+ `CREATE TABLE IF NOT EXISTS ${SUBMITTED} (row INTEGER PRIMARY KEY CHECK (row = 0), prompt TEXT NOT NULL)`,
552
+ );
553
+ const row = await ctx.db.get<{ prompt: string }>(`SELECT prompt FROM ${SUBMITTED} WHERE row = 0`);
554
+ return row?.prompt;
555
+ }
556
+
557
+ /** Record prompt `promptId` as the last submitted to OpenCode: before it is. */
558
+ const record = (ctx: restate.SessionContext, promptId: string) =>
559
+ ctx.db.execute(`INSERT OR REPLACE INTO ${SUBMITTED} (row, prompt) VALUES (0, ?)`, [promptId]);
560
+
561
+ /**
562
+ * The note that tells the model how the turn before ended, if it was closed:
563
+ * its answer, and for a turn another invocation left, the calls that did
564
+ * happen (OpenCode's own history says only that they were interrupted).
565
+ */
566
+ async function noteOf(ctx: restate.SessionContext, before: { n: number; answer?: string; status?: string }) {
567
+ if (!before.answer || before.status === 'answered' || before.status === undefined) return '';
568
+ if (before.status !== 'ended') return `(${before.answer})\n\n`;
569
+ const rows = await ctx.db.values(`SELECT item FROM ${STEPS} WHERE turn = ? ORDER BY n`, [before.n]);
570
+ const happened = rows.flatMap(([stored]) => {
571
+ const item = items.load(String(stored));
572
+ return item.type === 'results' ? item.results.filter((r) => r.output === RETURNED_UNRECORDED) : [];
573
+ });
574
+ const calls = happened.map((r) => `${r.name} (${r.id})`).join(', ');
575
+ return `(${before.answer}${calls ? ` These calls did happen: ${calls}.` : ''})\n\n`;
576
+ }
577
+
578
+ /** OpenCode's error types of a request its provider refused for good. */
579
+ const REFUSALS = /^provider\.(no-route|auth|unauthorized|not-found)|auth/i;
580
+
581
+ /** Whether OpenCode's error (`reason`, its `type` and HTTP `status`) is its provider's refusal, for good. */
582
+ const refusedFor = (reason: string, type?: string, status?: number) =>
583
+ refusal(new Error(reason)) !== undefined ||
584
+ (type !== undefined && REFUSALS.test(type)) ||
585
+ status === 401 ||
586
+ status === 403;
587
+
588
+ /** The error of prompt `id`, which ended unanswered (`failed`): {@link REFUSED} if its provider refused it. */
589
+ function unanswered(id: string, failed: Extract<Outcome, { state: 'failed' }>, model: ModelRef) {
590
+ const message = `prompt ${id} unanswered: ${failed.reason}`;
591
+ if (!refusedFor(failed.reason, failed.type, failed.status)) return new restate.TerminalError(message);
592
+ const of = `the model ${model.providerID}/${model.id}: ${CHECK_MODEL}`;
593
+ return new restate.TerminalError(`${message} (${of})`, { errorCode: REFUSED });
594
+ }
595
+
596
+ /** What `work` gets: `prompt(text)`, and the OpenCode host for anything else. */
597
+ export interface OpenCodeSession {
598
+ /** OpenCode, booted on its first use. */
599
+ host: () => Promise<Host>;
600
+ /**
601
+ * Answer `text`, once, with the answer's text: a turn of the object's
602
+ * conversation (each prompt of an invocation has an id of its own, the
603
+ * same on every attempt). With `check`, a reply it returns a message for
604
+ * is asked again within the turn, once. With `reminder`, the model is told
605
+ * it after the prompt, which the conversation keeps as it was asked.
606
+ */
607
+ prompt: (text: string, check?: Check, reminder?: string) => Promise<string>;
608
+ }
609
+
610
+ /** An agent's options: `chat`, `prompt` and `withOpenCode` take them. */
611
+ export interface Options<O extends z.ZodObject | undefined = z.ZodObject | undefined> {
612
+ /** The model of the session, as `provider/model-id`: MODEL, or else openai/gpt-6-sol. */
613
+ model?: string | ModelRef;
614
+ /** The system prompt: who the agent is, and how it answers. */
615
+ system?: string;
616
+ /** The agent's tools, which replace OpenCode's own: `tool()`s, Restate's (`call`, `signal`...), or OpenCode tools of your own. */
617
+ tools?: (AnyTool | OpenCodeTool)[];
618
+ /**
619
+ * A directory of the local machine, made if missing: OpenCode keeps its own
620
+ * tools (read, write, edit, shell, glob, grep...) there, besides `tools`,
621
+ * and the session works in it. Or a function of the invocation's context
622
+ * that gives one: `(ctx) => \`/work/${ctx.key}\``.
623
+ */
624
+ workspace?: string | ((ctx: restate.SessionContext) => string | Promise<string>);
625
+ /** OpenCode plugins, such as the one of the model. */
626
+ plugins?: Plugin.Plugin[];
627
+ /**
628
+ * How OpenCode asks the model again after a request failed for a reason
629
+ * that passes (an overloaded or unreachable provider, a rate limit), as pi
630
+ * does: by default without limit, 2 s after the first failure, then twice
631
+ * as long each time, a minute apart at most (`baseDelayMs`,
632
+ * `maxAgentDelayMs`), but never before the provider said to try again
633
+ * (its `retry-after`, which the cap does not shorten: up to 15 minutes, as
634
+ * OpenCode takes it). A request refused for good (a wrong API key, an
635
+ * unknown model, a request a retry would make again) is never asked again,
636
+ * and ends the turn (424). Unlike pi, OpenCode asks again 10 times at most
637
+ * in a step of the turn, and after its 4th timeout in a step not at all:
638
+ * without `maxRetries`, an outage OpenCode stops asking again about fails
639
+ * the attempt instead, and Restate's retry of it resumes the turn, waits
640
+ * from 2 s again. With `maxRetries`, a failure after that many retries of
641
+ * a step ends the turn, as one OpenCode stops asking again about does.
642
+ * `enabled: false` asks no request again.
643
+ */
644
+ retry?: Partial<RetryPolicy>;
645
+ /**
646
+ * With a workspace, OpenCode's own tools ask before what its permission
647
+ * rules say to ask about (by default, a read of a `.env` file). Without
648
+ * `approval`, nobody answers such an ask: it is denied, as OpenCode denies
649
+ * one nobody is present for, and the model gets the denial as the tool's
650
+ * error. With `approval`, the tool call waits for the signal
651
+ * {@link APPROVAL} to the agent, which `pending` shows with the call's tool
652
+ * and arguments and the permission asked (`action`, `resources`); `true`,
653
+ * or a text such as "approved" or "yes", allows it, anything else denies
654
+ * it (a text, or `{ reason }`, is the denial's reason, for the model).
655
+ */
656
+ approval?: boolean;
657
+ /**
658
+ * The answer as data: a zod object, whose JSON the agent replies with
659
+ * (checked), and `chat` and `prompt` answer with (see output.ts).
660
+ */
661
+ output?: O;
662
+ }
663
+
664
+ /** An OpenCode plugin that adds `system` to the session's system prompt. */
665
+ const systemPlugin = (system: string): Plugin.Plugin => ({
666
+ id: 'restate-agents.system',
667
+ async setup(ctx) {
668
+ const hook = await ctx.session.hook('context', (request) => {
669
+ request.system.push({ type: 'text', text: system });
670
+ });
671
+ return () => hook.dispose();
672
+ },
673
+ });
674
+
675
+ /** How a failed model request is asked again ({@link Options.retry}): pi's policy, as OpenCode can take it. */
676
+ export interface RetryPolicy {
677
+ enabled: boolean;
678
+ maxRetries: number;
679
+ baseDelayMs: number;
680
+ maxAgentDelayMs?: number;
681
+ }
682
+
683
+ /** The retries OpenCode makes of a step at most, in one attempt (its `ModelRetry` schedule's `recurs(10)`). */
684
+ const OPENCODE_RETRIES = 10;
685
+
686
+ /** The longest wait a provider's `retry-after` asks for that OpenCode takes (its `ModelRetry`'s `RETRY_AFTER_MAX`). */
687
+ const RETRY_AFTER_MAX_MS = 15 * 60_000;
688
+
689
+ /**
690
+ * OpenCode's error types of an outage: the failures its `AIError.isRetryable`
691
+ * retries (a rate limit, the provider's internal error, the transport's, one
692
+ * it cannot classify), as `toSessionError` names them.
693
+ */
694
+ const OUTAGES = new Set(['provider.rate-limit', 'provider.internal', 'provider.transport', 'provider.unknown']);
695
+
696
+ /**
697
+ * An OpenCode plugin that decides, by its `session.retry` hook, how a failed
698
+ * model request is asked again: OpenCode calls it for each failure while its
699
+ * schedule lasts (`attempt` is 2 at the first), its decision proposed. A
700
+ * refusal is never retried, nor a failure OpenCode would not retry that is
701
+ * no outage; an outage after `baseDelayMs` doubled each time, at most
702
+ * `maxAgentDelayMs`, and not before the provider's `retry-after`. An outage
703
+ * OpenCode would retry for the last time, or stopped retrying (after its 4th
704
+ * timeout in a step), is `outage` instead (with no `maxRetries`), which
705
+ * fails the attempt: the next resumes the turn, which OpenCode retries
706
+ * afresh.
707
+ */
708
+ function retryPlugin(
709
+ { enabled = true, maxRetries = Infinity, baseDelayMs = 2_000, maxAgentDelayMs = 60_000 }: Partial<RetryPolicy>,
710
+ outage: (error: Error) => void,
711
+ ): Plugin.Plugin {
712
+ return {
713
+ id: 'restate-agents.retry',
714
+ async setup(ctx) {
715
+ const hook = await ctx.session.hook('retry', (event) => {
716
+ const { message, type, status, retryAfterMs = 0 } = event.error;
717
+ const retries = event.attempt - 1;
718
+ const stopped = !event.decision.retry;
719
+ if (
720
+ !enabled ||
721
+ refusedFor(message, type, status) ||
722
+ retries > maxRetries ||
723
+ (stopped && (maxRetries !== Infinity || !OUTAGES.has(type)))
724
+ ) {
725
+ event.decision = { retry: false };
726
+ } else if (stopped || (maxRetries === Infinity && retries >= OPENCODE_RETRIES)) {
727
+ outage(
728
+ new Error(
729
+ `the model's provider failed ${retries} times in a row (${message}): the next attempt resumes the turn`,
730
+ ),
731
+ );
732
+ // The attempt is over: OpenCode waits until it is closed.
733
+ event.decision = { retry: true, delay: 2 ** 31 - 1 };
734
+ } else {
735
+ const backoff = Math.min(baseDelayMs * 2 ** (retries - 1), maxAgentDelayMs);
736
+ event.decision = { retry: true, delay: Math.max(backoff, Math.min(retryAfterMs, RETRY_AFTER_MAX_MS)) };
737
+ }
738
+ });
739
+ return () => hook.dispose();
740
+ },
741
+ };
742
+ }
743
+
744
+ /** OpenCode's tools of background work, which v1 leaves out: their recovery is not mapped onto turns. */
745
+ const BACKGROUND = new Set(['subagent', 'question']);
746
+
747
+ /**
748
+ * An OpenCode plugin whose tools are `tools`, and, with `builtins` (a
749
+ * workspace), OpenCode's own but those of background work.
750
+ */
751
+ function toolsPlugin(
752
+ tools: OpenCodeTool[],
753
+ fail: (error: unknown) => Promise<never>,
754
+ builtins: boolean,
755
+ ): Plugin.Plugin {
756
+ return {
757
+ id: 'restate-agents.tools',
758
+ async setup(ctx) {
759
+ const transform = await ctx.tool.transform((editor) => {
760
+ for (const t of editor.list()) {
761
+ if (!builtins || BACKGROUND.has(t.name)) editor.remove(t.id);
762
+ else if (t.name === 'shell') {
763
+ // A shell command runs in the tool call, never as a background job.
764
+ editor.update(t.id, (shell) => {
765
+ const run = shell.execute;
766
+ shell.execute = (input, context) =>
767
+ (input as { background?: unknown } | undefined)?.background === true
768
+ ? Promise.resolve({
769
+ content: 'Error: background jobs are not available: run the command in the foreground.',
770
+ })
771
+ : run(input, context);
772
+ });
773
+ }
774
+ }
775
+ for (const t of tools) {
776
+ editor.add({
777
+ name: t.name,
778
+ description: t.description,
779
+ input: t.input,
780
+ // Offered to the model as a tool, not in a code-mode script.
781
+ options: { codemode: false },
782
+ execute: async (input, context) => {
783
+ try {
784
+ return { content: await t.execute(input, context.id) };
785
+ } catch (error) {
786
+ return fail(error);
787
+ }
788
+ },
789
+ });
790
+ }
791
+ });
792
+ return () => transform.dispose();
793
+ },
794
+ };
795
+ }
796
+
797
+ /** The signal that an OpenCode tool call waits for, to the agent, when OpenCode asks for a permission (`approval`). */
798
+ export const APPROVAL = 'approval';
799
+
800
+ /** The texts that approve an ask, whatever their case. */
801
+ const APPROVED: ReadonlySet<string> = new Set(['approved', 'approve', 'yes', 'ok', 'allow', 'allowed']);
802
+
803
+ /**
804
+ * What the value of an {@link APPROVAL} signal decides: `true`,
805
+ * `{ "approved": true }`, or a text such as "approved" or "yes" allows;
806
+ * anything else denies, with the reason it gives, if any (a text, or
807
+ * `{ "reason": "..." }`).
808
+ */
809
+ function decided(value: unknown): { allowed: true } | { allowed: false; reason?: string } {
810
+ if (value === true) return { allowed: true };
811
+ if (typeof value === 'string') {
812
+ const text = value.trim();
813
+ return APPROVED.has(text.toLowerCase()) ? { allowed: true } : { allowed: false, ...(text ? { reason: text } : {}) };
814
+ }
815
+ if (typeof value === 'object' && value !== null) {
816
+ const { approved, reason } = value as { approved?: unknown; reason?: unknown };
817
+ if (approved === true) return { allowed: true };
818
+ return { allowed: false, ...(typeof reason === 'string' && reason.trim() ? { reason: reason.trim() } : {}) };
819
+ }
820
+ return { allowed: false };
821
+ }
822
+
823
+ /**
824
+ * An OpenCode plugin that settles each permission OpenCode would ask for
825
+ * (its `permission.evaluate` hook, which OpenCode awaits before it asks):
826
+ * what OpenCode's rules allow or deny stays so. An ask would wait in
827
+ * OpenCode's memory for a reply nothing gives, and its turn would never end.
828
+ *
829
+ * Without `approval`, it is denied, as OpenCode denies an ask nobody is
830
+ * present for (its `Unattended` rules): the model gets the denial as the
831
+ * tool's error. With `approval`, an ask of a tool call waits for the signal
832
+ * {@link APPROVAL} (`waitFor`), which `pending` shows with the call's tool
833
+ * and arguments, and the permission asked: its answer allows or denies.
834
+ *
835
+ * OpenCode stores the call (running) before it runs the tool, which asks;
836
+ * but a crash, or a suspension, while it waits has the resumed turn give the
837
+ * call OpenCode's "interrupted" result, and the model makes it again under a
838
+ * new id: made with the same tool and arguments, it joins the wait
839
+ * (`rejoin`), so the person is asked once. The wait is an approval
840
+ * (`approval`): a stopped turn does not report its call as done because it
841
+ * was approved. An error of the wait fails the attempt (`fail`), and the ask
842
+ * never settles.
843
+ *
844
+ * The wait is the tool call's: a call that asks more than once (another
845
+ * directory, then the file) has each ask answered by the first's answer.
846
+ * OpenCode's hook does not tell an ask from a probe (`permission.allows`,
847
+ * which an edit's miss hint makes), so a probe that would ask waits too.
848
+ */
849
+ function permissionPlugin(
850
+ ctx: restate.SessionContext,
851
+ approval: boolean,
852
+ fail: (error: unknown) => Promise<never>,
853
+ ): Plugin.Plugin {
854
+ return {
855
+ id: 'restate-agents.permission',
856
+ async setup(plugin) {
857
+ // Each tool call's tool and arguments, by call id: what `pending` shows of an ask.
858
+ const calls = new Map<string, { tool: string; args: unknown }>();
859
+ const before = await plugin.tool.hook('execute.before', (event) => {
860
+ calls.set(event.id, { tool: event.tool, args: event.input });
861
+ });
862
+ const evaluate = await plugin.permission.hook('evaluate', async (event) => {
863
+ if (event.effect !== 'ask') return;
864
+ const callId = event.source?.type === 'tool' ? event.source.id : undefined;
865
+ if (!approval || callId === undefined) {
866
+ event.effect = 'deny';
867
+ event.message = `Permission ${event.action} needs approval, and nobody is present to give it`;
868
+ return;
869
+ }
870
+ const call = calls.get(callId);
871
+ const asked = { ...call, action: event.action, resources: [...event.resources] };
872
+ // An error of the wait fails the attempt: the ask never settles.
873
+ const value = await waitFor(ctx, callId, APPROVAL, asked, { approval: true, rejoin: true }).catch(fail);
874
+ const decision = decided(value);
875
+ if (decision.allowed) {
876
+ event.effect = 'allow';
877
+ return;
878
+ }
879
+ event.effect = 'deny';
880
+ const which = call ? `tool "${call.tool}"` : `permission ${event.action}`;
881
+ event.message = `The user denied ${which}${decision.reason ? `: ${decision.reason}` : ''}`;
882
+ });
883
+ return async () => {
884
+ await before.dispose();
885
+ await evaluate.dispose();
886
+ };
887
+ },
888
+ };
889
+ }
890
+
891
+ /**
892
+ * Run `work(opencode)` with OpenCode over the object's database: `model` is
893
+ * the session's model, `plugins` OpenCode plugins (such as the model's), and
894
+ * `tools` the agent's tools. `opencode` has `prompt(text)`, and the
895
+ * OpenCode host for anything else.
896
+ */
897
+ export const withOpenCode = async <T>(
898
+ ctx: restate.SessionContext,
899
+ { plugins = [], model: named, system, tools = [], workspace: where, retry, approval = false }: Options,
900
+ work: (opencode: OpenCodeSession) => Promise<T>,
901
+ ): Promise<T> => {
902
+ const model = typeof named === 'object' ? named : modelRef(modelOf(named));
903
+ const workspace = typeof where === 'function' ? await where(ctx) : where;
904
+ if (workspace) await mkdir(workspace, { recursive: true });
905
+ const fence: Fence = { closed: false };
906
+ const { promise: failure, reject: failed } = Promise.withResolvers<never>();
907
+ failure.catch(() => {});
908
+ // A tool's error ends the attempt: nothing more is stored, and the tool
909
+ // call never returns. A cancellation (a tool's, or the turn's stop)
910
+ // interrupts OpenCode's turn instead, which then ends.
911
+ let cancelled: restate.CancelledError | undefined;
912
+ const fail = (error: unknown) => {
913
+ if (error instanceof restate.CancelledError) cancelled = error;
914
+ else {
915
+ fromTool(ctx, error);
916
+ fence.closed = true;
917
+ }
918
+ failed(error);
919
+ return new Promise<never>(() => {});
920
+ };
921
+ const stop = stopSignalOf(ctx);
922
+ const onStop = () => {
923
+ const reason: unknown = stop!.reason;
924
+ // An attempt that ends stores nothing more: the next goes on with the turn.
925
+ if (reason instanceof AttemptEnded) fence.closed = true;
926
+ else cancelled = reason as restate.CancelledError;
927
+ failed(reason);
928
+ };
929
+ stop?.addEventListener('abort', onStop, { once: true });
930
+
931
+ // The turn being answered, which the copy writes.
932
+ let turn: Turn<Item> | undefined;
933
+ // Once the turn is stopped, nothing more is copied: its close says how it ended.
934
+ let stopping = false;
935
+ // The copies, one after another.
936
+ let copying: Promise<unknown> = Promise.resolve();
937
+ /**
938
+ * Copy what OpenCode has of the turn, and `own`, a call's result as its tool returned it (see {@link copyInto}):
939
+ * once the turn is stopped, only with `steersOnly`, its messages steered to the turn. A copy of steps (a reply
940
+ * with tool calls, tools' results) is published once it is committed, for followers to read them there.
941
+ */
942
+ const copy = (own?: Returned, steersOnly = false) => {
943
+ const next = copying.then(async () => {
944
+ if (!turn || (stopping && !steersOnly) || fence.closed) return undefined;
945
+ if (await copyInto(ctx, await host(), turn, own, steersOnly)) await turn.stepsCommitted();
946
+ return undefined;
947
+ });
948
+ copying = next.catch(() => {});
949
+ return next;
950
+ };
951
+ const copied = () => {
952
+ copy().catch((error: unknown) => void fail(error));
953
+ };
954
+
955
+ // The messages steered to the turn that this attempt submitted to OpenCode, by steer id.
956
+ const given = new Set<string>();
957
+ /**
958
+ * Submit to OpenCode each message steered to the turn that the inbox lists
959
+ * and the turn has not taken, once (keyed by its id: OpenCode takes an id
960
+ * once, also from a retried attempt), with `delivery: 'steer'`: OpenCode
961
+ * places it at the turn's next step, after the round's results. Only as a
962
+ * tool call of a round returns, so a step follows; none once the turn is
963
+ * stopped, or closed.
964
+ */
965
+ const steer = async () => {
966
+ const waiting = inboxOf(ctx);
967
+ if (!waiting || !turn) return;
968
+ if (stopping || cancelled !== undefined || fence.closed || stopSignalOf(ctx)?.aborted || !turn.writable) return;
969
+ const held = new Set(turn.steered().map((e) => e.steer));
970
+ const fresh = waiting.messages.filter((m) => !given.has(m.id) && !held.has(m.id));
971
+ if (fresh.length === 0) return;
972
+ const opened = await host();
973
+ for (const { id: steerId, text } of fresh) {
974
+ given.add(steerId);
975
+ await opened.call(
976
+ opened.client.session.prompt({
977
+ sessionID: SESSION,
978
+ id: steerIdOf(steerId) as never,
979
+ text,
980
+ metadata: { steer: steerId },
981
+ delivery: 'steer',
982
+ }),
983
+ );
984
+ }
985
+ };
986
+
987
+ /**
988
+ * Copy the reply that makes a tool call before the call runs (its copy is
989
+ * published), then forget the calls whose results are stored. In a turn
990
+ * that takes steered messages, the result is copied as the tool returns it
991
+ * (OpenCode stores it after this hook, and goes on to the round's next step
992
+ * without waiting for a copy): the copy's publish lists the messages
993
+ * steered to the turn, which are submitted before OpenCode stores the
994
+ * result ({@link steer}).
995
+ */
996
+ const followPlugin: Plugin.Plugin = {
997
+ id: 'restate-agents.follow',
998
+ async setup(plugin) {
999
+ const before = await plugin.tool.hook('execute.before', async () => {
1000
+ await copy()
1001
+ .then(() => toolCallStarted(ctx))
1002
+ .catch(fail);
1003
+ });
1004
+ const after = await plugin.tool.hook('execute.after', async (event) => {
1005
+ if (!inboxOf(ctx)) return;
1006
+ const output =
1007
+ event.status === 'error'
1008
+ ? // As OpenCode stores it: a denied permission's reason, say, not the tool's "Unable to read".
1009
+ toSessionError(event.error).message
1010
+ : outputOf({ type: 'tool', state: { status: 'completed', ...event.result } as Content['state'] });
1011
+ const result: ItemResult = {
1012
+ id: event.id,
1013
+ name: event.tool,
1014
+ output,
1015
+ ...(event.status === 'error' ? { error: true } : {}),
1016
+ };
1017
+ await copy({ result, from: `${event.messageID}/${event.id}` })
1018
+ .then(steer)
1019
+ .catch(fail);
1020
+ });
1021
+ return async () => {
1022
+ await before.dispose();
1023
+ await after.dispose();
1024
+ };
1025
+ },
1026
+ };
1027
+
1028
+ // This attempt found a turn's final reply stored: a claim left is of a turn the model finished.
1029
+ let finished = false;
1030
+ let booted: Promise<Host> | undefined;
1031
+ /** Boot OpenCode, once: for the prompt `promptId` of turn `current` if a prompt boots it. */
1032
+ const boot = (promptId?: string, current?: Turn<Item>) =>
1033
+ (booted ??= (async () => {
1034
+ const submitted = await submittedOf(ctx);
1035
+ // A claim, if any, is the recorded prompt's: this one's goes on, another's is closed.
1036
+ const mine =
1037
+ submitted !== undefined &&
1038
+ (promptId === undefined ? invocationOf(submitted) === ctx.request.id : submitted === promptId);
1039
+ if (mine && !finished && current) {
1040
+ // What OpenCode stored of the turn is copied first: a final reply it stored (and the attempt died
1041
+ // before its copy, or before OpenCode's turn ended) is the answer, and its turn is not resumed,
1042
+ // which would ask the model again.
1043
+ const reader = await openOpenCode(database(ctx.db, DATABASE), fence, { restart: 'none' });
1044
+ try {
1045
+ await reader.swept;
1046
+ await copyInto(ctx, reader, current);
1047
+ } finally {
1048
+ await reader.close();
1049
+ }
1050
+ finished = current.finalReply() !== undefined;
1051
+ }
1052
+ const restart: Restart = mine && !finished ? 'resume' : 'close';
1053
+ const opened = await openOpenCode(database(ctx.db, DATABASE), fence, {
1054
+ plugins: [
1055
+ ...plugins,
1056
+ followPlugin,
1057
+ toolsPlugin(
1058
+ tools.map((t) => (isTool(t) ? native(t, ctx) : t)),
1059
+ fail,
1060
+ workspace !== undefined,
1061
+ ),
1062
+ permissionPlugin(ctx, approval, fail),
1063
+ ...(system ? [systemPlugin(system)] : []),
1064
+ // An outage OpenCode would stop retrying fails the attempt, as a tool's error does (never a refusal).
1065
+ retryPlugin(retry ?? {}, (error) => void fail(error)),
1066
+ ],
1067
+ config: { default_agent: 'build' },
1068
+ local: workspace !== undefined,
1069
+ restart,
1070
+ committed: copied,
1071
+ });
1072
+ await opened.swept;
1073
+ // Another prompt's input still waiting is a dead invocation's too: it never runs.
1074
+ if (!mine) await dropInbox(opened);
1075
+ return opened;
1076
+ })());
1077
+ const host = () => boot();
1078
+
1079
+ let interrupting: Promise<unknown> | undefined;
1080
+ /**
1081
+ * Stop OpenCode's turn, once: what it has of the turn is copied, then
1082
+ * nothing more is (the turn's close says how it ended), and its turn is
1083
+ * interrupted: it ends, and releases its claim. The copies' errors are
1084
+ * the turn's close's no more than its interrupt's in an attempt that is
1085
+ * over (its fence closed: OpenCode refuses it, and its close ends the turn):
1086
+ * the turn closes cancelled.
1087
+ */
1088
+ const stopTurn = () =>
1089
+ (interrupting ??= (async () => {
1090
+ if (!booted) return;
1091
+ await copy().catch(() => {});
1092
+ stopping = true;
1093
+ const opened = await booted;
1094
+ await opened.call(opened.client.session.interrupt({ sessionID: SESSION })).catch((error: unknown) => {
1095
+ if (!fence.closed) throw error;
1096
+ });
1097
+ // A message steered to the turn that OpenCode placed as it was stopped is the turn's: OpenCode's
1098
+ // history has it, so the turn takes it, and it is not answered again as a turn of its own (unless
1099
+ // the copy fails: then its own turn answers it).
1100
+ await copy(undefined, true).catch(() => {});
1101
+ })());
1102
+
1103
+ const prompt = (text: string, check?: Check, reminder?: string) =>
1104
+ answerOnce(
1105
+ ctx,
1106
+ text,
1107
+ items,
1108
+ async (store) => {
1109
+ const current = store.turn;
1110
+ const id = current.id;
1111
+ const again = current.latestAsk() !== current.prompt;
1112
+ const messageId = again ? againIdOf(id) : messageIdOf(id);
1113
+ // A stored final reply is the answer: the model is not asked for it again (nor OpenCode's turn resumed).
1114
+ const stored = current.finalReply();
1115
+ if (stored !== undefined) {
1116
+ finished = true;
1117
+ return stored;
1118
+ }
1119
+ const opened = await boot(id, current);
1120
+ const caught = current.finalReply();
1121
+ if (caught !== undefined) return caught;
1122
+ // Before the turn closes here (stopped, refused, failed): OpenCode's turn first, then the copy.
1123
+ live.set(current, async (status) => {
1124
+ if (status === 'cancelled') await stopTurn();
1125
+ else await copy();
1126
+ });
1127
+ if (!(await sessionExists(opened))) {
1128
+ const location = workspace ? { location: { directory: workspace as never } } : {};
1129
+ await opened.call(
1130
+ opened.client.session.create({ id: SESSION, model: model as never, agent: 'build' as never, ...location }),
1131
+ );
1132
+ }
1133
+ // From now on, each of OpenCode's commits is copied into the turn.
1134
+ turn = current;
1135
+ if ((await outcome(opened, messageId)).state === 'absent') {
1136
+ // The model is told how the turn before this one ended, if its run did not answer it.
1137
+ const before = store.transcript.at(-2);
1138
+ const note = !again && before ? await noteOf(ctx, before) : '';
1139
+ const said = items.read(current.latestAsk().item).said?.[1] ?? '';
1140
+ const asked = said + (again ? '' : (current.reminder ?? ''));
1141
+ await record(ctx, id);
1142
+ await opened.call(
1143
+ opened.client.session.prompt({
1144
+ sessionID: SESSION,
1145
+ id: messageId as never,
1146
+ text: note + asked,
1147
+ delivery: 'queue',
1148
+ resume: true,
1149
+ }),
1150
+ );
1151
+ }
1152
+ const now = await settled(opened, messageId);
1153
+ // A prompt the cancellation's interrupt ended fails with the cancellation.
1154
+ if (cancelled) throw cancelled;
1155
+ await copy();
1156
+ if (now.state === 'answered') return now.text;
1157
+ if (now.state !== 'failed') throw new Error(`prompt ${id} is not in the session`);
1158
+ throw unanswered(id, now, model);
1159
+ },
1160
+ // OpenCode keeps the model's history: the conversation reads only its latest turns.
1161
+ { check, reminder, ownHistory: true },
1162
+ );
1163
+
1164
+ // `failure`, once it comes. A cancellation interrupts OpenCode's turn
1165
+ // instead: the work ends with it (a prompt closes its turn, cancelled).
1166
+ const interruptOn = async (): Promise<never> => {
1167
+ try {
1168
+ return await failure;
1169
+ } catch (error) {
1170
+ if (!(error instanceof restate.CancelledError)) throw error;
1171
+ await stopTurn();
1172
+ return new Promise<never>(() => {});
1173
+ }
1174
+ };
1175
+
1176
+ try {
1177
+ const done = await Promise.race([interruptOn(), work({ host, prompt })]);
1178
+ if (cancelled) throw cancelled;
1179
+ return done;
1180
+ } finally {
1181
+ stop?.removeEventListener('abort', onStop);
1182
+ if (turn) live.delete(turn);
1183
+ if (booted) {
1184
+ const opened = await booted.catch(() => undefined);
1185
+ await interrupting?.catch(() => {});
1186
+ await opened?.close();
1187
+ }
1188
+ }
1189
+ };
1190
+
1191
+ /**
1192
+ * Answer `text`, once: a retried attempt resumes the same prompt. Each prompt
1193
+ * of an invocation is a prompt of its own. With `output`, it answers with the
1194
+ * value the agent replies with (see output.ts), not its text.
1195
+ */
1196
+ export const prompt = <O extends z.ZodObject | undefined = undefined>(
1197
+ ctx: restate.SessionContext,
1198
+ text: string,
1199
+ options: Options<O> = {},
1200
+ ): Promise<Answer<O>> =>
1201
+ withChecked(text, options, (t, o, check, reminder) =>
1202
+ withOpenCode(ctx, o, (session) => session.prompt(t, check, reminder)),
1203
+ ) as Promise<Answer<O>>;
1204
+
1205
+ /**
1206
+ * A chat handler: each message an invocation, the session in the object's
1207
+ * database, with `options`, or the options a function of the invocation's
1208
+ * context gives (each user's workspace, say). It takes the message as plain
1209
+ * text (`curl -d 'Hi'`) or as a JSON string (`curl --json '"Hi"'`).
1210
+ */
1211
+ export const chat = <O extends z.ZodObject | undefined = undefined>(options: Configure<Options<O>> = {}) => {
1212
+ if (typeof options === 'object' && typeof options.model !== 'object') checkModelName('opencode', options.model);
1213
+ return chatHandler(async (ctx, message) => prompt(ctx, message, await configured(options, ctx)), { steers: true });
1214
+ };
1215
+
1216
+ /**
1217
+ * A view of the conversation as clients read it: a page at a time, or what
1218
+ * is new or changed since a cursor; `view: 'summary'` for each turn's
1219
+ * message and answer. It answers while a message is answered. `clear` also
1220
+ * empties OpenCode's database.
1221
+ */
1222
+ export const messages = () => conversationView(items);
1223
+
1224
+ /** An agent: a virtual object `name`, one per key, whose `chat` handler is {@link chat}, and `messages` {@link messages}. */
1225
+ export const agent = <P extends string, O extends z.ZodObject | undefined = undefined>({
1226
+ name,
1227
+ description,
1228
+ schema,
1229
+ background,
1230
+ window,
1231
+ budget,
1232
+ ...options
1233
+ }: Options<O> & Definition<P>) =>
1234
+ sessionObject({
1235
+ name,
1236
+ description,
1237
+ schema,
1238
+ background,
1239
+ window,
1240
+ budget,
1241
+ handlers: { chat: chat(options) },
1242
+ views: { messages: messages() },
1243
+ });