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