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