@restatedev/agents 0.4.0 → 0.5.0

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