@restatedev/agents 0.11.1 → 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 -235
  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 -330
  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,249 +0,0 @@
1
- # OpenCode
2
-
3
- [OpenCode](https://opencode.ai) 2.2 can run embedded: `@opencode/sdk` hosts
4
- the whole OpenCode server in your process, with no HTTP listener. Here it
5
- runs in the agent's virtual object, and OpenCode's database (its session,
6
- messages, inbox and events) is an SQL database of the key's own, in the
7
- object's state beside `ctx.db` (`database` of @restatedev/sessions): OpenCode
8
- boots only on a database that is empty or its own, so its tables are alone
9
- there, and `ctx.db` keeps the conversation of turns and the tables of yours
10
- ([SQL in Restate virtual objects](../../../sessions/README.md)). The
11
- integration pins OpenCode 2.2.6 exactly (`@opencode/core`, `sdk`, `server`
12
- and `plugin`), with the Effect release it is built on (4.1.0); OpenCode
13
- needs Node 24.
14
-
15
- ## Use
16
-
17
- ```ts
18
- import { serve } from '@restatedev/agents';
19
- import * as opencode from '@restatedev/agents/opencode';
20
-
21
- const coder = opencode.agent({ name: 'coder', workspace: (ctx) => `/work/${ctx.key}` });
22
- await serve(coder);
23
- ```
24
-
25
- | Option | What |
26
- | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
27
- | `model` | `provider/model-id`, of any provider OpenCode serves; or else `MODEL`, or else `openai/gpt-6-sol` (`OPENAI_API_KEY`). A key's session keeps the model it was created with (see [Not yet](#not-yet)) |
28
- | `system` | Added to OpenCode's own system prompt, on each model request |
29
- | `tools` | `tool()`s and Restate's tools of `@restatedev/agents`, or OpenCode tools of your own (`OpenCodeTool`: `execute(input, callId)`) |
30
- | `output` | A zod object: the answer as data, which the agent replies with as JSON, and `chat` answers with (see [Structured answers](../../README.md#structured-answers)) |
31
- | `workspace` | A directory of the local machine, made if missing, for OpenCode's own tools (read, write, edit, shell, glob, grep...), or a function of the context that gives one (`(ctx) => \`/work/${ctx.key}\``); use a sandbox. Without one, the agent has only `tools` |
32
- | `plugins` | OpenCode plugins of your own (`@opencode/plugin`) |
33
- | `retry` | How OpenCode asks the model again after a request failed for a reason that passes (an outage, a rate limit), as pi's `retry`: by default without limit, 2 s to a minute apart (`baseDelayMs`, `maxAgentDelayMs`, `maxRetries`, `enabled`; see [Through crashes](#through-crashes)) |
34
- | `approval` | With a workspace, `true` has what OpenCode's permission rules ask about wait for a person's approval, the signal `approval`; without it, such an ask is denied ([Permissions](#permissions)) |
35
-
36
- With a workspace, OpenCode's tools of background work are left out: its
37
- subagent and question tools are removed, and its shell runs a command in
38
- the tool call, never as a background job (one asked for is refused, and the
39
- model told to run it in the foreground). Restate's `subagent` tool is the
40
- way to delegate: its calls are made once.
41
-
42
- For a session object of your own, `opencode.chat(options)` is the handler and
43
- `opencode.messages()` the view (with it, the agent's `clear` empties
44
- OpenCode's database too); `options` may be a function of the invocation's
45
- context, such as a directory for each key:
46
-
47
- ```ts
48
- chat: opencode.chat((ctx) => ({ workspace: `/work/${ctx.key}` })),
49
- ```
50
-
51
- `opencode.prompt(ctx, text, options)` answers a prompt in a handler of your
52
- own. For more than a prompt, `withOpenCode(ctx, options, work)` runs `work`
53
- with OpenCode: `prompt(text)` answers a prompt once, and `host()` boots
54
- OpenCode (once) and gives its client.
55
-
56
- ## Through crashes
57
-
58
- [`db.ts`](db.ts) (`@restatedev/agents/opencode/db`) boots OpenCode's embedded
59
- host on its database: an Effect `SqlClient` through
60
- `Database.configuredClient`, OpenCode's seam for an injected client, each
61
- OpenCode transaction an SQL transaction. The handler is not replayed: a
62
- retried attempt boots OpenCode again, on the stored database. OpenCode
63
- records an execution claim when a turn starts, and every boot sweeps the
64
- claims left behind. Whose claim it is comes from `ctx.db`: the prompt last
65
- submitted to OpenCode is recorded there before it is submitted
66
- (`restate_agents_opencode`). So:
67
-
68
- - **A message is answered once per invocation** (`answerOnce`): the prompt's
69
- id is its OpenCode message id (`msg_<id>`), and a retried attempt of an
70
- answered prompt returns its answer without booting OpenCode. So does one
71
- whose turn holds its final reply, copied before the attempt died. A
72
- retried attempt of the recorded prompt boots OpenCode twice: first
73
- without its sweep, to copy what OpenCode stored of the turn; a final
74
- reply stored before the attempt died (before its copy, or before
75
- OpenCode's turn ended) is then the answer, and the second boot closes
76
- OpenCode's claim without the model, rather than resume the turn, which
77
- would ask it again; without one, the second boot resumes the turn.
78
- - **A tool runs only once its call is stored.** OpenCode stores the model's
79
- reply, with its tool calls, before the tools run.
80
- - **A crashed attempt's turn goes on.** A boot for the recorded prompt
81
- resumes its turn, as OpenCode does: a tool call that was running gets an
82
- "interrupted" result, and the model makes it again under a new id. OpenCode
83
- gives up on a turn after ten resumes; here the object's retry policy
84
- decides. A tool that must not run twice needs a way for a retry to name
85
- the call it retries (the bank agent's `transfer` takes `retryOf`).
86
- Restate's own tools (`call`, `send`, `workflow`, `subagent`, `signal`)
87
- need none: made again with the same input, the call is the one the
88
- cut-off call made.
89
- - **A tool's error fails the attempt**, and Restate retries it; a
90
- `restate.TerminalError` of a `@restatedev/agents` tool is its answer to the
91
- model. The failed attempt stores nothing more, so its retry finds the call
92
- interrupted, as above.
93
- - **A killed invocation's turn is closed, never finished.** A boot for any
94
- other prompt (the next message, or the companion's `settle`) closes the
95
- claim without asking the model, through OpenCode's own resume budget
96
- (`maxAttempts: 0`), and waits for that before anything is submitted; then
97
- the turn's copy catches up, and the conversation closes the turn
98
- (`ended`). The next prompt tells the model how the turn before it ended,
99
- and which of its calls did happen (OpenCode's history says only that they
100
- were interrupted). A final reply OpenCode stored before the kill is kept
101
- in the turn, then its `Ended` note. A prompt killed once OpenCode queued
102
- it, before its turn began, never runs: what waits in OpenCode's inbox is
103
- cancelled.
104
- - **A stopped turn** (`stop`) is interrupted in OpenCode, and closed
105
- cancelled, also when a tool's error ended the attempt as it stopped;
106
- the next prompt tells the model.
107
- - **A provider's outage never ends the turn.** OpenCode asks the model
108
- again as its `session.retry` hook decides, with pi's backoff (`retry`):
109
- 2 s after the first failure, twice as long each time, a minute apart at
110
- most, but never before the provider's `retry-after` (up to 15 minutes, as
111
- OpenCode takes it, which `maxAgentDelayMs` does not shorten). Unlike pi,
112
- OpenCode retries a step 10 times at most, and not after its 4th timeout:
113
- an outage it would retry for the last time, or no longer retries, fails
114
- the attempt instead (not terminal), as a tool's error does, and the next
115
- attempt resumes the turn, its retries afresh. With a finite `maxRetries`,
116
- a failure past that many retries of a step ends the turn instead, as
117
- does one OpenCode no longer retries; `enabled: false` retries nothing.
118
- - **A refused prompt** (a wrong API key, an unknown model) is never asked
119
- again: it fails at once with a terminal error, 424, and closes its turn;
120
- any other turn OpenCode ends unanswered fails with a terminal error.
121
-
122
- OpenCode keeps its own history, and compacts it itself: `window`, `budget`
123
- and summaries do not apply. What OpenCode stores of a turn (the model's
124
- replies, the tools' results) is copied into the turn after each of
125
- OpenCode's commits, in a `ctx.db` transaction of its own, by OpenCode's
126
- message and part ids, so a copy a crash missed is caught up, before a tool
127
- call runs, the answer, and any close of the turn. A copy of a reply with
128
- tool calls, or of tools' results, is published once it is committed, in a
129
- `chat` turn (a `prompt()` in a handler of your own publishes nothing), and
130
- nothing else is: a tool call's start publishes nothing. That is what `messages`
131
- shows ([docs/conversation.md](../../docs/conversation.md)); OpenCode's own
132
- "Continue" after a restart, its idle markers and its compactions are not
133
- copied. A reply with tool calls is copied as its stream ends, before the
134
- calls run; one without, once OpenCode stored how its step ended, and never
135
- if the step failed or the model's output limit cut it off (OpenCode asks
136
- the model again, or to go on). A step a crash left without its end is
137
- never a reply either: a retry of such a turn resumes it, and the model is
138
- asked again. The two databases share no transaction: a follower may see a
139
- step late after a crash, never the model.
140
-
141
- **A message steered to the turn** (`steer`) is submitted to OpenCode as a
142
- tool call of a round returns, as a steered prompt (`delivery: 'steer'`,
143
- once, by its id), which OpenCode places at the round's next step, after its
144
- results; the copy stores it in the turn, in its place. One sent while the
145
- model writes its final answer is answered as a turn of its own. One
146
- OpenCode placed as the turn was stopped is the stopped turn's: the turn
147
- holds it, and it is not answered again as a turn of its own.
148
-
149
- The files of a `workspace` are not in the database: they last as long as the
150
- disk does.
151
-
152
- ## Permissions
153
-
154
- With a workspace, OpenCode's permission rules allow its tools everything
155
- but a few asks (by default, a read of a `*.env` file). OpenCode alone would
156
- keep an ask in memory, waiting for a reply nothing gives, and its turn
157
- would never end. Here each ask is settled through OpenCode's
158
- `permission.evaluate` hook:
159
-
160
- - **Without `approval`**, it is denied, as OpenCode denies an ask nobody is
161
- present for: the model gets the denial as the tool's error. So is an ask
162
- of no tool call, with `approval` too.
163
- - **With `approval: true`**, the tool call waits for the signal `approval`
164
- (`opencode.APPROVAL`) to the agent, as a `signal()` tool waits
165
- ([Signals](../../README.md#signals)). `pending` shows the wait with the
166
- call's tool and arguments, and the permission asked (`action`,
167
- `resources`). `true`, `{"approved": true}`, or a text such as `approved`,
168
- `yes` or `ok` allows the call; anything else denies it, and the model is
169
- told why (`The user denied tool "shell": <the text, or the reason>`).
170
-
171
- ```ts
172
- opencode.agent({ name: 'coder', workspace: (ctx) => `/work/${ctx.key}`, approval: true });
173
- ```
174
-
175
- The wait outlasts a crash, or a suspension: the resumed turn gives the call
176
- OpenCode's "interrupted" result, the model makes it again under a new id,
177
- and the call, with the same tool and arguments, joins the wait. The person
178
- is asked once, and the tool runs once, after the decision. A turn stopped
179
- while the call waits ends cancelled, and the tool never runs.
180
-
181
- The wait is the tool call's: a call that asks more than once (a directory,
182
- then the file) has each ask answered by the first's answer. OpenCode's hook
183
- does not tell an ask from a probe (an edit's hint on a miss), so a probe
184
- that would ask waits too.
185
-
186
- ## Keeping alive
187
-
188
- Restate shuts an attempt down after its inactivity timeout (a minute) and starts it again, unless
189
- something keeps it alive. The adapter keeps it alive (`ctx.working`) while OpenCode's turn runs:
190
- while the model streams its requests, and while OpenCode's own tools (shell, read, write, edit,
191
- glob, grep) work on the machine, a command that runs for minutes included. But not:
192
-
193
- - while a tool of your own runs, unless it says so itself (`tool({ keepalive: true })`): it may
194
- wait on Restate (a call, a signal), and such a wait suspends.
195
- - while it waits for an approval, even of the shell: a wait on Restate suspends.
196
-
197
- OpenCode has no hook at the end of a model's request, so this is the turn's scope with a gap for
198
- each tool that runs (tools may overlap: the scope reopens once none runs). A request OpenCode
199
- makes outside a turn (a session's title, say) is not kept alive.
200
-
201
- ## Not yet
202
-
203
- - **A change of `model`** for a key that has a session already: the session
204
- keeps the model it was created with.
205
-
206
- ## Notes
207
-
208
- - **Embedded.** OpenCode runs in the handler's own process, on OpenCode's
209
- workerd profile (the one it boots in a Cloudflare Durable Object), with
210
- the object's database for its own. Without a `workspace` it has no
211
- filesystem, shell or terminal; with one, its own tools run on the local
212
- machine. The only other traffic out is the model's, to its provider's API.
213
- - **Boots lazily**: OpenCode boots as a turn runs, once per attempt.
214
- Booting takes about 100 ms, after a one-time import of about 2 s per
215
- process; a prompt makes some hundreds of SQL statements.
216
- - **A turn that neither runs nor ends** for 5 s fails the attempt: the
217
- retry boots OpenCode again, which resumes it.
218
-
219
- ## Run
220
-
221
- ```sh
222
- cd packages/examples && OPENAI_API_KEY=… node basic/opencode.ts
223
- ```
224
-
225
- With a Restate server, and the agent registered with it: see
226
- [Run an example](../../../examples/README.md#run-an-example).
227
- [`examples/advanced/foreman`](../../../examples/advanced/foreman/README.md) has
228
- OpenCode agents, a worker and a senior with a workspace and a reviewer
229
- without one, under a pi boss.
230
-
231
- ## Tests
232
-
233
- The tests run on a scripted model, [`test/fakes/opencode.ts`](../../test/fakes/opencode.ts),
234
- an AI SDK language model that OpenCode calls through a plugin's `language`
235
- hook, and makes a fresh tool call id for every call
236
- (`pnpm --filter @restatedev/agents test opencode`, from the repository root,
237
- on Node 24: on older Node the suites are skipped):
238
-
239
- - [`test/opencode.test.ts`](../../test/opencode.test.ts):
240
- each point above, with crashes that stop an attempt in a tool call, or
241
- at any of its state requests, and kills, at a turn's end too; a stop, a
242
- refusal, an outage, asking again for `output`, the system prompt,
243
- `messages`, `clear`, steering, and permission asks, denied or approved.
244
- - [`test/opencode-spike.test.ts`](../../test/opencode-spike.test.ts): `db.ts`
245
- alone, a killed turn closed at boot without the model (by OpenCode's
246
- budget, or by a closer of our own), and a crashed one resumed.
247
- - [`test/opencode.ts`](../../test/opencode.ts): the bank agent, through
248
- crashes and kills in [the crash test](../../../e2e/crash.ts)
249
- (`pnpm --filter e2e crash`).
@@ -1,387 +0,0 @@
1
- // OpenCode on the object's database: `openOpenCode(db, fence, options)` boots
2
- // OpenCode 2.2's embedded host (@opencode/sdk) with its database in a SQL
3
- // session, `ctx.db`.
4
- //
5
- // The host is OpenCode's workerd profile, the one it boots in a Cloudflare
6
- // Durable Object: no local filesystem, shell, terminal, npm or version
7
- // control, config given inline, plugins given in code. Only its database
8
- // differs. The workerd profile reads a Durable Object's SQLite, whose `exec`
9
- // is synchronous; here OpenCode gets an Effect SqlClient instead, which is
10
- // asynchronous, through `Database.configuredClient` (OpenCode's), the seam
11
- // OpenCode keeps for an injected client. Each transaction is an SQL
12
- // transaction, and the session runs statements one at a time, as OpenCode's
13
- // own clients do.
14
- //
15
- // `fence.closed` refuses every statement from then on: an attempt that is
16
- // giving up stores nothing more, as Restate fences an attempt that a newer
17
- // one replaced.
18
- //
19
- // At boot, OpenCode sweeps the turns a previous process left claimed
20
- // (`SessionRestart`): `restart` says what this boot does with them (see
21
- // {@link Restart}), and `Host.swept` settles once the sweep is done.
22
- //
23
- // Step 0 of docs/opencode.md (the spike) found its seams; `./opencode/db` exports it.
24
- import { Context, Deferred, Effect, Exit, Layer, Option, Scope } from 'effect';
25
- import { Reactivity } from 'effect/reactivity';
26
- import { SqlClient, Statement } from 'effect/sql';
27
- import { SqlError, UnknownError } from 'effect/sql/SqlError';
28
- import type { Connection } from 'effect/sql/SqlConnection';
29
- import { Bus } from '@opencode/core/bus';
30
- import { Database as OpenCodeDatabase } from '@opencode/core/database/database';
31
- import { fromPromise } from '@opencode/core/plugin/promise';
32
- import { SessionEvent } from '@opencode/core/session/event';
33
- import { SessionExecution } from '@opencode/core/session/execution';
34
- import { SessionRestart } from '@opencode/core/session/execution/restart';
35
- import { SessionStore } from '@opencode/core/session/store';
36
- import { ConfigPluginSource } from '@opencode/core/config/plugin/source';
37
- import { Pty } from '@opencode/core/pty';
38
- import { Snapshot } from '@opencode/core/snapshot';
39
- import { ServerWorkerd } from '@opencode/server/workerd';
40
- import { OpenCode } from '@opencode/sdk/effect';
41
- import type { Plugin } from '@opencode/plugin';
42
- import type { DatabaseWriter, Database, SqlValue } from '@restatedev/sessions';
43
-
44
- /** Closed: every later statement fails. */
45
- export interface Fence {
46
- closed: boolean;
47
- }
48
-
49
- const error = (operation: string, cause: unknown) =>
50
- new SqlError({
51
- reason: new UnknownError({
52
- cause,
53
- message: cause instanceof Error ? cause.message : String(cause),
54
- operation,
55
- }),
56
- });
57
-
58
- /** The connection inside a transaction, for statements of that transaction. */
59
- const InTransaction = Context.Service<SqlClient.TransactionConnection, SqlClient.TransactionConnection.Service>(
60
- '@restatedev/agents/OpenCodeTransaction',
61
- );
62
-
63
- /** A statement that writes. */
64
- const WRITE = /^\s*(INSERT|UPDATE|DELETE|REPLACE)\b/i;
65
-
66
- /**
67
- * A connection whose statements go to `target`: the session, which runs one
68
- * call at a time and holds them while a transaction runs, or that
69
- * transaction's database. Each is refused once `fence` closes; `wrote` is
70
- * told of each statement that writes.
71
- */
72
- function connection(target: DatabaseWriter, fence: Fence, wrote: () => void = () => {}): Connection {
73
- // Effect binds what the compiler made of OpenCode's values: SQL values.
74
- const exec = <T>(read: (sql: string, params: SqlValue[]) => Promise<T>, sql: string, params: readonly unknown[]) =>
75
- Effect.tryPromise({
76
- try: async () => {
77
- if (fence.closed) throw new Error('the attempt is over');
78
- const result = await read(sql, params as SqlValue[]);
79
- if (WRITE.test(sql)) wrote();
80
- return result;
81
- },
82
- catch: (cause) => error('execute', cause),
83
- });
84
- const run = (sql: string, params: readonly unknown[] = []) => exec((s, p) => target.query(s, p), sql, params);
85
- const runValues = (sql: string, params: readonly unknown[] = []) => exec((s, p) => target.values(s, p), sql, params);
86
- const transformed: Connection['execute'] = (sql, params, transformRows) =>
87
- transformRows ? Effect.map(run(sql, params), transformRows) : run(sql, params);
88
- return {
89
- execute: transformed,
90
- executeRaw: (sql, params) => run(sql, params),
91
- executeValues: (sql, params) => runValues(sql, params),
92
- executeValuesUnprepared: (sql, params) => runValues(sql, params),
93
- executeUnprepared: transformed,
94
- executeStream: () => {
95
- throw new Error('executeStream is not supported');
96
- },
97
- };
98
- }
99
-
100
- /**
101
- * An Effect SqlClient over `db`, with its statements refused once `fence`
102
- * closes. `committed` runs after each write is committed: a transaction that
103
- * wrote, or a statement that writes outside one.
104
- */
105
- export function sqlClient(
106
- db: Database,
107
- fence: Fence,
108
- committed: () => void = () => {},
109
- ): Layer.Layer<SqlClient.SqlClient> {
110
- // `effect` as one SQL transaction: it commits when `effect` succeeds
111
- // and rolls back when it fails. Its statements go to the transaction's
112
- // database.
113
- const withTransaction = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
114
- Effect.withFiber<A, E | SqlError, R>((fiber) => {
115
- if (Option.isSome(Context.getOption(fiber.context, InTransaction))) {
116
- return Effect.fail(error('transaction', new Error('nested transactions are not supported')));
117
- }
118
- return Effect.callback<A, E | SqlError, R>((resume) => {
119
- const rollback = new Error('rollback');
120
- let interrupted = false;
121
- let resumed = false;
122
- let wrote = false;
123
- // Settles when the transaction has committed, or rejects: with
124
- // `rollback` once `effect` failed, or with the error of BEGIN or COMMIT.
125
- const ended: Promise<void> = db.transaction(
126
- (tx) =>
127
- new Promise<void>((resolve, reject) => {
128
- if (interrupted) return reject(rollback);
129
- const inner = Effect.provideContext(
130
- effect,
131
- Context.add(fiber.context, InTransaction, [connection(tx, fence, () => (wrote = true)), 0]),
132
- );
133
- resumed = true;
134
- resume(
135
- // A finalizer, so that the body settles however `effect`
136
- // ends, an interruption included: otherwise the transaction
137
- // would hold the session for good.
138
- Effect.onExit(inner, (exit) => {
139
- if (Exit.isSuccess(exit)) {
140
- resolve();
141
- return Effect.void;
142
- }
143
- reject(rollback);
144
- return Effect.promise(() => settled);
145
- }).pipe(
146
- // The commit is part of the transaction: if it fails, so
147
- // does the transaction.
148
- Effect.flatMap((value) =>
149
- Effect.as(Effect.tryPromise({ try: () => ended, catch: (e) => error('commit', e) }), value),
150
- ),
151
- ),
152
- );
153
- }),
154
- );
155
- ended.then(
156
- () => (wrote ? committed() : undefined),
157
- () => undefined,
158
- );
159
- const settled = ended.catch((cause: unknown) => {
160
- // BEGIN failed: `effect` never ran.
161
- if (!resumed && cause !== rollback) resume(Effect.fail(error('transaction', cause)));
162
- });
163
- return Effect.suspend(() => {
164
- interrupted = true;
165
- return Effect.promise(() => settled);
166
- });
167
- });
168
- });
169
-
170
- const make = Effect.gen(function* () {
171
- const client = yield* SqlClient.make({
172
- // Outside a transaction, a statement commits as it runs.
173
- acquirer: Effect.succeed(connection(db, fence, committed)),
174
- compiler: Statement.makeCompilerSqlite(),
175
- driver: 'sqlite-restate',
176
- spanAttributes: [['db.system.name', 'sqlite']],
177
- transactionService: InTransaction,
178
- });
179
- return Object.assign(client, { withTransaction, transactionStatements: false });
180
- });
181
- return Layer.effect(SqlClient.SqlClient, make).pipe(Layer.provide(Reactivity.layer));
182
- }
183
-
184
- /**
185
- * What a boot does with the turns a previous process left claimed (OpenCode's
186
- * execution claims), before any prompt of its own:
187
- *
188
- * - `resume`: OpenCode's own restart, however often the turn was resumed
189
- * before (Restate's retry policy decides): a synthetic "Continue" message,
190
- * its running tool calls failed, and a new step. A crashed attempt's turn
191
- * goes on.
192
- * - `close`: each is closed without asking the model: an idle marker
193
- * (`Execution.Failed`) and the claim released. A killed invocation's turn
194
- * is over. How, `closer` says.
195
- * - `none`: nothing; the claims stay. A reader beside a running turn.
196
- */
197
- export type Restart = 'resume' | 'close' | 'none';
198
-
199
- /**
200
- * How `restart: 'close'` closes a claimed turn:
201
- *
202
- * - `own`: a `SessionRestart` of ours. Each streaming or running tool call
203
- * fails with `cutOff(toolCallId, name)` as its result, then the turn with
204
- * `ended`, the claim released in the same transaction.
205
- * - `budget`: OpenCode's own restart with no resumes left
206
- * (`maxAttempts: 0`): the idle marker with OpenCode's text, the claim
207
- * released; the running tool calls stay running until the next drain fails
208
- * them ("Tool execution interrupted").
209
- */
210
- export type Closer = 'own' | 'budget';
211
-
212
- export interface OpenOptions {
213
- /** OpenCode plugins: models, tools, agents. */
214
- plugins?: Plugin.Plugin[];
215
- /** OpenCode's config (opencode.json), inline. */
216
- config?: Record<string, unknown>;
217
- /**
218
- * OpenCode's own filesystem, search and shell, on the local machine, for
219
- * its built-in tools (read, write, edit, bash, glob, grep...) in a
220
- * session's directory. Without it, the workerd profile has none.
221
- */
222
- local?: boolean;
223
- /** What this boot does with the turns left claimed (default `resume`). */
224
- restart?: Restart;
225
- /** How `close` closes them (default `budget`: the spike found ours buys little over it). */
226
- closer?: Closer;
227
- /** The result of a tool call that a closed turn left running (`own` only). */
228
- cutOff?: (toolCallId: string, name: string) => string;
229
- /** The error a closed turn ends with (`own` only). */
230
- ended?: string;
231
- /** Runs after each of OpenCode's writes is committed: for a copy of what it wrote. */
232
- committed?: () => void;
233
- }
234
-
235
- /** A booted OpenCode: `call` runs one of `client`'s calls (which return Effects); `close` shuts it down. */
236
- export interface Host {
237
- client: OpenCode.Interface;
238
- call<A, E, R>(effect: Effect.Effect<A, E, R>): Promise<A>;
239
- /**
240
- * Settles once the boot's sweep of claimed turns is done: closed, for
241
- * `close`; their resumes started, for `resume`. The host forks the sweep, so
242
- * a prompt submitted before it settles may join a claimed turn.
243
- */
244
- swept: Promise<void>;
245
- close(): Promise<void>;
246
- }
247
-
248
- /** The result `own` gives a running tool call of a closed turn, by default. */
249
- const CUT_OFF = 'The turn ended before this call returned: it may or may not have happened.';
250
- /** The error `own` closes a turn with, by default. */
251
- const ENDED = 'Ended: the turn was killed before it finished.';
252
-
253
- /**
254
- * A `SessionRestart` that closes each claimed top-level session this process
255
- * does not run: OpenCode's budget's events (`Execution.Failed`, the release
256
- * as its commit), and before them a `Tool.Failed` of our result for each
257
- * streaming or running tool part. No synthetic message, no drain, no model.
258
- */
259
- const closing = (cutOff: (toolCallId: string, name: string) => string, ended: string) =>
260
- Layer.effect(
261
- SessionRestart.Service,
262
- Effect.gen(function* () {
263
- const store = yield* SessionStore.Service;
264
- const execution = yield* SessionExecution.Service;
265
- const bus = yield* Bus.Service;
266
- const close = Effect.fnUntraced(function* (sessionID: Parameters<typeof store.release>[0]) {
267
- for (const message of yield* Effect.orDie(store.context(sessionID))) {
268
- if (message.type !== 'assistant') continue;
269
- for (const part of message.content) {
270
- if (part.type !== 'tool') continue;
271
- if (part.state.status !== 'streaming' && part.state.status !== 'running') continue;
272
- yield* bus.publish(SessionEvent.Tool.Failed, {
273
- sessionID,
274
- assistantMessageID: message.id,
275
- id: part.id,
276
- error: { type: 'aborted', message: cutOff(part.id, part.name) },
277
- executed: part.executed === true,
278
- });
279
- }
280
- }
281
- yield* bus.publish(
282
- SessionEvent.Execution.Failed,
283
- { sessionID, error: { type: 'aborted', message: ended } },
284
- { commit: () => store.release(sessionID) },
285
- );
286
- });
287
- return SessionRestart.Service.of({
288
- resumeSuspendedSessions: Effect.gen(function* () {
289
- const active = yield* execution.active;
290
- // Child sessions' claims: v1 has no background subagents to recover.
291
- yield* store.releaseChildClaims([]);
292
- const claimed = (yield* store.listSuspended()).filter((id) => !active.has(id));
293
- yield* Effect.forEach(claimed, close, { discard: true });
294
- }),
295
- });
296
- }),
297
- );
298
-
299
- /** The sweep's service for `restart` and `closer`. */
300
- const restarts = (
301
- restart: Restart,
302
- closer: Closer,
303
- cutOff: (toolCallId: string, name: string) => string,
304
- ended: string,
305
- ): Layer.Layer<SessionRestart.Service, never, unknown> => {
306
- if (restart === 'none') return Layer.succeed(SessionRestart.Service, { resumeSuspendedSessions: Effect.void });
307
- if (restart === 'resume') return SessionRestart.layer({ maxAttempts: Infinity });
308
- return closer === 'budget' ? SessionRestart.layer({ maxAttempts: 0 }) : closing(cutOff, ended);
309
- };
310
-
311
- /** `service`, whose sweep completes `done` as it ends, however it ends. */
312
- const observed = (
313
- layer: Layer.Layer<SessionRestart.Service, never, unknown>,
314
- done: Deferred.Deferred<void, unknown>,
315
- ): Layer.Layer<SessionRestart.Service, never, unknown> =>
316
- Layer.effect(
317
- SessionRestart.Service,
318
- Effect.map(SessionRestart.Service, (inner: SessionRestart.Interface) =>
319
- SessionRestart.Service.of({
320
- resumeSuspendedSessions: inner.resumeSuspendedSessions.pipe(
321
- Effect.onExit((exit) => Effect.asVoid(Deferred.done(done, Exit.asVoid(exit)))),
322
- ),
323
- }),
324
- ),
325
- ).pipe(Layer.provide(layer));
326
-
327
- /** What a replacement replaces: `LayerNode`'s own record of it (its source node). */
328
- const sourceOf = (replacement: ReturnType<typeof ServerWorkerd.replacements>[number]): unknown => {
329
- const key = Object.getOwnPropertySymbols(replacement).find((s) => s.description === 'LayerNode.Replacement');
330
- return key && (replacement as unknown as Record<symbol, { source: unknown }>)[key]?.source;
331
- };
332
-
333
- /**
334
- * Boot OpenCode with its database in `db`; the boot sweeps the turns left
335
- * claimed as `restart` says. Close the host when done.
336
- */
337
- export async function openOpenCode(
338
- db: Database,
339
- fence: Fence,
340
- {
341
- plugins = [],
342
- config = {},
343
- local = false,
344
- restart = 'resume',
345
- closer = 'budget',
346
- committed,
347
- cutOff = () => CUT_OFF,
348
- ended = ENDED,
349
- }: OpenOptions,
350
- ): Promise<Host> {
351
- // The workerd profile, but for its database, which comes first. (The
352
- // Promise API's OpenCode.create takes no replacements; the Effect API's does.)
353
- const profile = { storage: undefined as never, models: { fetch: false } };
354
- // Taken by the node each replaces, not by position (2.1 added Npm's). Local
355
- // keeps the stubs of snapshots, the pty and plugin discovery only.
356
- const kept = local ? new Set<unknown>([Snapshot.node, Pty.node, ConfigPluginSource.node]) : undefined;
357
- const rest = ServerWorkerd.replacements(profile).filter((r: Parameters<typeof sourceOf>[0]) => {
358
- const source = sourceOf(r);
359
- if (source === undefined) throw new Error('OpenCode: a workerd replacement of unknown node');
360
- return source !== OpenCodeDatabase.node && (kept === undefined || kept.has(source));
361
- });
362
- const scope = Scope.makeUnsafe();
363
- const done = Deferred.makeUnsafe<void, unknown>();
364
- const sweep = observed(restarts(restart, closer, cutOff, ended), done);
365
- const client = await Effect.runPromise(
366
- OpenCode.create(
367
- {
368
- ...ServerWorkerd.serverOptions({ ...profile, config: { content: JSON.stringify(config) } }),
369
- plugins: plugins.map(fromPromise),
370
- },
371
- {
372
- overrides: [
373
- OpenCodeDatabase.node.replace(OpenCodeDatabase.configuredClient(sqlClient(db, fence, committed))),
374
- ...rest,
375
- SessionRestart.node.replace(SessionRestart.node.mapLayer(() => sweep as never)),
376
- ],
377
- },
378
- ).pipe(Scope.provide(scope)),
379
- );
380
- return {
381
- client,
382
- // The client's calls need nothing more: OpenCode provided it all.
383
- call: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.runPromise(effect as Effect.Effect<A, E>),
384
- swept: Effect.runPromise(Deferred.await(done)),
385
- close: () => Effect.runPromise(Scope.close(scope, Exit.void)),
386
- };
387
- }