@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
package/dist/object.js DELETED
@@ -1,309 +0,0 @@
1
- // Virtual objects set up for SQL and agents.
2
- import * as restate from '@restatedev/sessions';
3
- import { reset } from '@restatedev/sessions/internal';
4
- import { BUDGET, chatOf, chatTurn, checkWindow, isAgent, ITEMS, messageSerde, publish, refusalOf, WINDOW, } from './common.js';
5
- import { compact, nextStart, restart, SCHEMA, settle, steerStored } from './conversation.js';
6
- import { companionAt, withCompanion, } from './companion.js';
7
- /**
8
- * The options of every object here, beside a session object's: retries for
9
- * weeks, since each attempt resumes from the database: soon after a crash,
10
- * then twice as long each time, up to 10 seconds apart (a provider's rate
11
- * limit, say, is not asked again twice a second).
12
- */
13
- const OPTIONS = {
14
- retryPolicy: { initialInterval: 50, exponentiationFactor: 2, maxInterval: 10_000, maxAttempts: 100_000 },
15
- };
16
- /**
17
- * A call of the companion of the object of `ctx` (its own, at its key); with
18
- * `step`, a change, keyed by the request and `step`: a restarted view joins
19
- * the same call. A read has no key: asked again, it answers again, and
20
- * Restate keeps nothing of it.
21
- */
22
- const companion = (ctx, step) => ctx.rpc(companionAt(ctx), ctx.key, step === undefined ? {} : { idempotencyKey: `${ctx.request.id}:${step}` });
23
- /**
24
- * Cancel the invocation of the message being answered, if any, and say
25
- * which. The companion's `status` says which, with a key of the request and
26
- * `step`: a restarted view gets the same answer, and cancels the same
27
- * invocation again (which does nothing), not the message that started once
28
- * it was cancelled.
29
- */
30
- async function stopped(ctx, step) {
31
- const turn = (await companion(ctx, step).status()).answering;
32
- if (turn)
33
- ctx.cancel(turn.invocationId);
34
- return { stopped: turn?.invocationId ?? null };
35
- }
36
- /**
37
- * Views that wait on the companion (`watch`, `sync`, up to a minute) or on
38
- * the object (`clear`): Restate
39
- * suspends one that waits past its inactivity timeout, which restarts it,
40
- * so it is longer than the wait.
41
- */
42
- const WAITS = { inactivityTimeout: { minutes: 5 } };
43
- /**
44
- * The views every object here has, beside its own: `signal`, which resolves
45
- * a wait of the object's tools (see `signal` in tools.ts), `pending`, the
46
- * waits, `status`, what the object is doing, `stop`, which stops the message
47
- * it answers, and `notifications` and `watch`, the revision of its
48
- * conversation, and a wait for a newer one (an agent's
49
- * has `clear` and `sync` too: {@link FOLLOWED}). Each asks the object's
50
- * companion (its own `<name>.prebuilt.restate`, at the same key), which
51
- * knows what the object does: they run while the object's handler works.
52
- * They are the only way a client reaches the companion, whose handlers
53
- * Restate's ingress refuses.
54
- */
55
- const BUILT_IN = {
56
- signal: async (ctx, signal) => companion(ctx, 'signal').resolve(signal),
57
- pending: async (ctx) => companion(ctx).pending(),
58
- status: async (ctx) => companion(ctx).status(),
59
- /** Cancel the invocation of the message being answered (`status`'s), as Restate's admin API cancels one. */
60
- stop: async (ctx) => stopped(ctx, 'stop'),
61
- /** The revision of the conversation: each change of what `messages` and `status` give increases it. */
62
- notifications: async (ctx) => companion(ctx).notifications(),
63
- /**
64
- * The revision, once there is one newer than `revision`, or at the timeout (50 s by
65
- * default, at most 60 s), whichever comes first: a client then reads what
66
- * changed. It waits in Restate, holding no process; a client that retries
67
- * it with the same idempotency key joins the same wait.
68
- */
69
- watch: {
70
- ...WAITS,
71
- handler: async (ctx, watch) => companion(ctx, 'watch').watch(watch),
72
- },
73
- };
74
- /**
75
- * The views that agents (an object with a `messages` view) have beside
76
- * those of every object: `clear`, which forgets the conversation; `steer`,
77
- * which sends a message while a turn is answered (for an agent whose `chat`
78
- * a framework's `chat()` made: `chatHandler`'s, which answers it as a turn
79
- * of its own if no turn takes it); and `sync`, the conversation since
80
- * `cursor` (by default, all of it), what the agent is doing, and the
81
- * revision, in one request; with `revision`, once there is a newer one, or
82
- * at the timeout. A client follows the conversation by sending each
83
- * answer's `revision` and `cursor` back, at once while it has `more`.
84
- */
85
- const followed = (steerable) => ({
86
- /**
87
- * Forget the conversation: stop the message being answered (as `stop`),
88
- * then empty the key's database, and what its companion holds (waits and
89
- * kept signals). The conversation's ids and cursors go on (see
90
- * conversation.ts), so a follower reads on, and drops the messages before `first`.
91
- * A message sent before it is answered first, then forgotten too; one sent
92
- * after starts anew.
93
- */
94
- clear: {
95
- // `erase` waits for the messages sent before it.
96
- ...WAITS,
97
- handler: async (ctx) => {
98
- const stop = await stopped(ctx, 'clear');
99
- await ctx.rpc({
100
- service: ctx.request.target.service,
101
- key: ctx.key,
102
- handler: 'erase',
103
- idempotencyKey: `${ctx.request.id}:erase`,
104
- });
105
- return stop;
106
- },
107
- },
108
- /**
109
- * Send a message to the agent while it answers another: the turn being
110
- * answered takes it at its next step (once the model's tool calls have
111
- * their results), if its framework takes steered messages and it reaches
112
- * one; otherwise the message is answered as a turn of its own, after the
113
- * messages before it, in the order it was sent. With no message being
114
- * answered, it starts a turn. Either way it is answered once: send it with
115
- * an idempotency key, so that a retried request is the same message. It
116
- * takes the message as plain text or as a JSON string, as `chat` does.
117
- */
118
- steer: {
119
- input: messageSerde,
120
- accept: '*/*',
121
- handler: async (ctx, text) => {
122
- if (!steerable) {
123
- throw new restate.TerminalError(`${ctx.request.target.service} takes no steered messages: its \`chat\` handler is no framework's \`chat()\` (chatHandler)`, { errorCode: 400 });
124
- }
125
- return companion(ctx, 'steer').steer({ id: ctx.request.id, text });
126
- },
127
- },
128
- sync: {
129
- ...WAITS,
130
- handler: async (ctx, { cursor = 0, revision, timeoutSeconds = 50, limit = 100, view } = {}) => {
131
- if (revision !== undefined)
132
- await companion(ctx, 'watch').watch({ revision, timeoutSeconds });
133
- // The revision first: a change after it shows in the next sync. Then
134
- // what the object does, and its conversation, in an invocation of its
135
- // own, which starts after the revision: a view reads the database as
136
- // committed when it started, and this one started before the revision
137
- // (by the whole wait, when it waited). So the page has every change the
138
- // revision counts.
139
- const now = await companion(ctx).notifications();
140
- const status = await companion(ctx).status();
141
- const request = { cursor, limit, ...(view ? { view } : {}) };
142
- const page = (await ctx.rpc({
143
- service: ctx.request.target.service,
144
- key: ctx.key,
145
- handler: 'messages',
146
- input: request,
147
- }));
148
- return { revision: now.revision, status, ...page };
149
- },
150
- },
151
- });
152
- /** The views of every agent: {@link followed}'s. */
153
- const FOLLOWED = followed(false);
154
- /**
155
- * The agents' handlers that only their own views call (Restate's ingress
156
- * refuses them), and their types leave out: `erase`, `clear`'s work, once
157
- * the handlers before it are done. It empties the key's database and what its
158
- * companion holds, and the conversation's ids and cursors go on where they got to
159
- * (conversation.ts).
160
- */
161
- const internal = (items) => ({
162
- erase: {
163
- ingressPrivate: true,
164
- handler: async (ctx) => {
165
- // Read first, which also makes the reset apply the conversation's schema again.
166
- await SCHEMA.ensure(ctx.db);
167
- const start = await nextStart(ctx.db);
168
- // A framework's database of its own first: the conversation's rows say what is left.
169
- await items?.erase?.(ctx);
170
- await ctx.db.transaction(async (tx) => {
171
- await reset(tx);
172
- await restart(tx, start);
173
- });
174
- await ctx.rpc(companionAt(ctx), ctx.key, { idempotencyKey: `${ctx.request.id}:reset` }).reset();
175
- },
176
- },
177
- /**
178
- * Close the latest turn, unanswered, if invocation `invocationId` ran it
179
- * and is gone: the companion sends this once it finds the turn's
180
- * invocation ended without answering (killed, say), so that the
181
- * conversation shows the turn closed before the next message. Whether it
182
- * closed it.
183
- */
184
- settle: {
185
- ingressPrivate: true,
186
- handler: async (ctx, invocationId) => {
187
- if (!items || !(await settle(ctx, items, invocationId)))
188
- return false;
189
- // The companion published as it closed the turn, before this stored how it ended: publish that too.
190
- await publish(ctx);
191
- return true;
192
- },
193
- },
194
- /** Summarize the earliest turns, past the agent's budget. Whether it did. */
195
- compact: {
196
- ingressPrivate: true,
197
- handler: async (ctx) => (items ? compact(ctx, items) : false),
198
- },
199
- });
200
- /**
201
- * The private `steered` of an agent whose `chat` is `chat` (`chatHandler`'s):
202
- * it answers a message sent to `steer` as a turn of its own, with that
203
- * `chat`, unless the turn it was sent to took it. The companion sends it as
204
- * the message is sent, so that it keeps its place in the key's queue: it runs
205
- * once the messages before it are answered.
206
- */
207
- const steeredOf = ({ answer, steers }) => ({
208
- ingressPrivate: true,
209
- explicitCancellation: true,
210
- handler: async (ctx, { id, text }) => {
211
- if (await steerStored(ctx.db, id))
212
- return;
213
- await chatTurn(ctx, text, answer, steers);
214
- },
215
- });
216
- /**
217
- * A Restate virtual object with a SQL database per key, `ctx.db`: a
218
- * `restate.sessionObject` of @restatedev/sessions, set up for agents.
219
- *
220
- * const notes = sessionObject({
221
- * name: 'notes',
222
- * handlers: {
223
- * add: (ctx, note: string) => ctx.db.execute('INSERT INTO notes VALUES (?)', [note]),
224
- * },
225
- * });
226
- *
227
- * Besides its own handlers and views, it has the views `status`, what it is
228
- * doing (the message it answers, and what its tools wait for), `stop`,
229
- * which stops that message, `pending`, the waits
230
- * of its tools (`signal()`), `signal({ id, value })`, which resolves one,
231
- * and `notifications` and `watch({ revision })`, to follow its
232
- * conversation. An agent, an object with a `messages` view (such as
233
- * `claude.messages()`), has `clear` too, which forgets its conversation
234
- * (its database too), and `sync`, which `follow()` of @restatedev/agents/client
235
- * reads.
236
- *
237
- * `schema`, optional: tables of your own, beside the agent's (which are its
238
- * own business), made in each key's database as a session object makes
239
- * them. Any name is yours but those starting with `restate_`, the agent's
240
- * (`restate_pi_tasks`, `restate_agent_turns`, `restate_agent_items`...).
241
- *
242
- * `options` and `metadata` add to (or replace) the ones set here, such as
243
- * `options: { retryPolicy: ... }`.
244
- */
245
- export const sessionObject = (definition) => {
246
- const { name, description, schema, background, handlers = {}, views = {}, metadata, options } = definition;
247
- const { window = WINDOW, budget = BUDGET, summarize } = definition;
248
- checkWindow(window);
249
- if (!(Number.isInteger(budget) && budget >= 0)) {
250
- throw new Error(`${name}: budget must be a number of tokens (0 or more), not ${JSON.stringify(budget)}`);
251
- }
252
- const own = [...Object.keys(BUILT_IN), ...Object.keys(FOLLOWED), ...Object.keys(internal(undefined)), 'steered'];
253
- if ('messages' in handlers) {
254
- throw new Error(`${name}: \`messages\` is a view: put it in \`views\`, so that the object is an agent`);
255
- }
256
- for (const key of own) {
257
- if (key in handlers || key in views)
258
- throw new Error(`${name}: \`${key}\` is a handler of @restatedev/agents' own: name yours otherwise`);
259
- }
260
- // A model provider's refusal (a missing API key) ends a handler's invocation.
261
- const yours = Object.fromEntries(Object.entries(handlers).map(([key, entry]) => [
262
- key,
263
- answering(entry),
264
- ]));
265
- const messages = views.messages;
266
- const page = (typeof messages === 'function' ? messages : messages?.handler);
267
- // A `chat` that `chatHandler` made: its answer answers the steered messages no turn took (`steered`).
268
- const chatEntry = handlers.chat;
269
- const chat = typeof chatEntry === 'object' || typeof chatEntry === 'function' ? chatOf(chatEntry) : undefined;
270
- const agent = page === undefined ? {} : followed(chat !== undefined);
271
- // A framework on the conversation of turns: its view carries its items.
272
- const items = (page && ITEMS.of(page));
273
- // Its `compact` summarizes: without the conversation of turns, it has none, and nothing would.
274
- if (summarize && !items) {
275
- throw new Error(`${name}: \`summarize\` needs the conversation of turns: a framework's \`messages\` view (\`claude.messages()\`, say)`);
276
- }
277
- const { erase, ...stored } = internal(items);
278
- const steering = chat ? { steered: steeredOf(chat) } : {};
279
- const privates = messages === undefined
280
- ? {}
281
- : items
282
- ? { erase, ...stored, ...steering }
283
- : { erase, ...steering };
284
- return withCompanion(isAgent(restate.sessionObject({
285
- name,
286
- description,
287
- schema,
288
- handlers: { ...privates, ...yours },
289
- views: { ...BUILT_IN, ...agent, ...views },
290
- metadata,
291
- options: { ...OPTIONS, ...options },
292
- }), { background, items, window, budget, summarize }));
293
- };
294
- /** `entry`, but a model provider's refusal it fails with ends its invocation, as `chat`'s does. */
295
- function answering(entry) {
296
- const { handler, ...options } = typeof entry === 'function' ? { handler: entry } : entry;
297
- return {
298
- ...options,
299
- handler: async (ctx, input) => {
300
- try {
301
- return await handler(ctx, input);
302
- }
303
- catch (error) {
304
- throw refusalOf(ctx, error) ?? error;
305
- }
306
- },
307
- };
308
- }
309
- //# sourceMappingURL=object.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"object.js","sourceRoot":"","sources":["../src/object.ts"],"names":[],"mappings":"AAAA,6CAA6C;AAC7C,OAAO,KAAK,OAAO,MAAM,sBAAsB,CAAC;AAChD,OAAO,EAAE,KAAK,EAAE,MAAM,+BAA+B,CAAC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QAAQ,EAAE;YACnC,CAAC,CAAC,EAAE,KAAK,EAAE,GAAG,QAAQ,EAAE,CAAC;IAC7B,OAAO,aAAa,CAClB,OAAO,CACL,OAAO,CAAC,aAAa,CAAC;QACpB,IAAI;QACJ,WAAW;QACX,MAAM;QACN,QAAQ,EAAE,EAAE,GAAG,QAAQ,EAAE,GAAG,KAAK,EAAE;QACnC,KAAK,EAAE,EAAE,GAAG,QAAQ,EAAE,GAAG,KAAK,EAAE,GAAG,KAAK,EAAE;QAC1C,QAAQ;QACR,OAAO,EAAE,EAAE,GAAG,OAAO,EAAE,GAAG,OAAO,EAAE;KACpC,CAAC,EACF,EAAE,UAAU,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,CACjD,CACF,CAAC;AACJ,CAAC,CAAC;AAEF,mGAAmG;AACnG,SAAS,SAAS,CAAC,KAAkC;IACnD,MAAM,EAAE,OAAO,EAAE,GAAG,OAAO,EAAE,GAAG,OAAO,KAAK,KAAK,UAAU,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC;IACzF,OAAO;QACL,GAAG,OAAO;QACV,OAAO,EAAE,KAAK,EAAE,GAAiB,EAAE,KAAc,EAAE,EAAE;YACnD,IAAI,CAAC;gBACH,OAAO,MAAM,OAAO,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;YACnC,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,MAAM,SAAS,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,KAAK,CAAC;YACvC,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -1,81 +0,0 @@
1
- import { Effect, Layer } from 'effect';
2
- import { SqlClient } from 'effect/sql';
3
- import { OpenCode } from '@opencode/sdk/effect';
4
- import type { Plugin } from '@opencode/plugin';
5
- import type { Database } from '@restatedev/sessions';
6
- /** Closed: every later statement fails. */
7
- export interface Fence {
8
- closed: boolean;
9
- }
10
- /**
11
- * An Effect SqlClient over `db`, with its statements refused once `fence`
12
- * closes. `committed` runs after each write is committed: a transaction that
13
- * wrote, or a statement that writes outside one.
14
- */
15
- export declare function sqlClient(db: Database, fence: Fence, committed?: () => void): Layer.Layer<SqlClient.SqlClient>;
16
- /**
17
- * What a boot does with the turns a previous process left claimed (OpenCode's
18
- * execution claims), before any prompt of its own:
19
- *
20
- * - `resume`: OpenCode's own restart, however often the turn was resumed
21
- * before (Restate's retry policy decides): a synthetic "Continue" message,
22
- * its running tool calls failed, and a new step. A crashed attempt's turn
23
- * goes on.
24
- * - `close`: each is closed without asking the model: an idle marker
25
- * (`Execution.Failed`) and the claim released. A killed invocation's turn
26
- * is over. How, `closer` says.
27
- * - `none`: nothing; the claims stay. A reader beside a running turn.
28
- */
29
- export type Restart = 'resume' | 'close' | 'none';
30
- /**
31
- * How `restart: 'close'` closes a claimed turn:
32
- *
33
- * - `own`: a `SessionRestart` of ours. Each streaming or running tool call
34
- * fails with `cutOff(toolCallId, name)` as its result, then the turn with
35
- * `ended`, the claim released in the same transaction.
36
- * - `budget`: OpenCode's own restart with no resumes left
37
- * (`maxAttempts: 0`): the idle marker with OpenCode's text, the claim
38
- * released; the running tool calls stay running until the next drain fails
39
- * them ("Tool execution interrupted").
40
- */
41
- export type Closer = 'own' | 'budget';
42
- export interface OpenOptions {
43
- /** OpenCode plugins: models, tools, agents. */
44
- plugins?: Plugin.Plugin[];
45
- /** OpenCode's config (opencode.json), inline. */
46
- config?: Record<string, unknown>;
47
- /**
48
- * OpenCode's own filesystem, search and shell, on the local machine, for
49
- * its built-in tools (read, write, edit, bash, glob, grep...) in a
50
- * session's directory. Without it, the workerd profile has none.
51
- */
52
- local?: boolean;
53
- /** What this boot does with the turns left claimed (default `resume`). */
54
- restart?: Restart;
55
- /** How `close` closes them (default `budget`: the spike found ours buys little over it). */
56
- closer?: Closer;
57
- /** The result of a tool call that a closed turn left running (`own` only). */
58
- cutOff?: (toolCallId: string, name: string) => string;
59
- /** The error a closed turn ends with (`own` only). */
60
- ended?: string;
61
- /** Runs after each of OpenCode's writes is committed: for a copy of what it wrote. */
62
- committed?: () => void;
63
- }
64
- /** A booted OpenCode: `call` runs one of `client`'s calls (which return Effects); `close` shuts it down. */
65
- export interface Host {
66
- client: OpenCode.Interface;
67
- call<A, E, R>(effect: Effect.Effect<A, E, R>): Promise<A>;
68
- /**
69
- * Settles once the boot's sweep of claimed turns is done: closed, for
70
- * `close`; their resumes started, for `resume`. The host forks the sweep, so
71
- * a prompt submitted before it settles may join a claimed turn.
72
- */
73
- swept: Promise<void>;
74
- close(): Promise<void>;
75
- }
76
- /**
77
- * Boot OpenCode with its database in `db`; the boot sweeps the turns left
78
- * claimed as `restart` says. Close the host when done.
79
- */
80
- export declare function openOpenCode(db: Database, fence: Fence, { plugins, config, local, restart, closer, committed, cutOff, ended, }: OpenOptions): Promise<Host>;
81
- //# sourceMappingURL=db.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"db.d.ts","sourceRoot":"","sources":["../../src/opencode/db.ts"],"names":[],"mappings":"AAuBA,OAAO,EAAqB,MAAM,EAAQ,KAAK,EAAiB,MAAM,QAAQ,CAAC;AAE/E,OAAO,EAAE,SAAS,EAAa,MAAM,YAAY,CAAC;AAclD,OAAO,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAChD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,KAAK,EAAkB,QAAQ,EAAY,MAAM,sBAAsB,CAAC;AAE/E,2CAA2C;AAC3C,MAAM,WAAW,KAAK;IACpB,MAAM,EAAE,OAAO,CAAC;CACjB;AAqDD;;;;GAIG;AACH,wBAAgB,SAAS,CACvB,EAAE,EAAE,QAAQ,EACZ,KAAK,EAAE,KAAK,EACZ,SAAS,GAAE,MAAM,IAAe,GAC/B,KAAK,CAAC,KAAK,CAAC,SAAS,CAAC,SAAS,CAAC,CAyElC;AAED;;;;;;;;;;;;GAYG;A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B,KAAa,GACd,EAAE,WAAW,GACb,OAAO,CAAC,IAAI,CAAC,CAqCf"}
@@ -1,249 +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 { Bus } from '@opencode/core/bus';
29
- import { Database as OpenCodeDatabase } from '@opencode/core/database/database';
30
- import { fromPromise } from '@opencode/core/plugin/promise';
31
- import { SessionEvent } from '@opencode/core/session/event';
32
- import { SessionExecution } from '@opencode/core/session/execution';
33
- import { SessionRestart } from '@opencode/core/session/execution/restart';
34
- import { SessionStore } from '@opencode/core/session/store';
35
- import { ConfigPluginSource } from '@opencode/core/config/plugin/source';
36
- import { Pty } from '@opencode/core/pty';
37
- import { Snapshot } from '@opencode/core/snapshot';
38
- import { ServerWorkerd } from '@opencode/server/workerd';
39
- import { OpenCode } from '@opencode/sdk/effect';
40
- const error = (operation, cause) => new SqlError({
41
- reason: new UnknownError({
42
- cause,
43
- message: cause instanceof Error ? cause.message : String(cause),
44
- operation,
45
- }),
46
- });
47
- /** The connection inside a transaction, for statements of that transaction. */
48
- const InTransaction = Context.Service('@restatedev/agents/OpenCodeTransaction');
49
- /** A statement that writes. */
50
- const WRITE = /^\s*(INSERT|UPDATE|DELETE|REPLACE)\b/i;
51
- /**
52
- * A connection whose statements go to `target`: the session, which runs one
53
- * call at a time and holds them while a transaction runs, or that
54
- * transaction's database. Each is refused once `fence` closes; `wrote` is
55
- * told of each statement that writes.
56
- */
57
- function connection(target, fence, wrote = () => { }) {
58
- // Effect binds what the compiler made of OpenCode's values: SQL values.
59
- const exec = (read, sql, params) => Effect.tryPromise({
60
- try: async () => {
61
- if (fence.closed)
62
- throw new Error('the attempt is over');
63
- const result = await read(sql, params);
64
- if (WRITE.test(sql))
65
- wrote();
66
- return result;
67
- },
68
- catch: (cause) => error('execute', cause),
69
- });
70
- const run = (sql, params = []) => exec((s, p) => target.query(s, p), sql, params);
71
- const runValues = (sql, params = []) => exec((s, p) => target.values(s, p), sql, params);
72
- const transformed = (sql, params, transformRows) => transformRows ? Effect.map(run(sql, params), transformRows) : run(sql, params);
73
- return {
74
- execute: transformed,
75
- executeRaw: (sql, params) => run(sql, params),
76
- executeValues: (sql, params) => runValues(sql, params),
77
- executeValuesUnprepared: (sql, params) => runValues(sql, params),
78
- executeUnprepared: transformed,
79
- executeStream: () => {
80
- throw new Error('executeStream is not supported');
81
- },
82
- };
83
- }
84
- /**
85
- * An Effect SqlClient over `db`, with its statements refused once `fence`
86
- * closes. `committed` runs after each write is committed: a transaction that
87
- * wrote, or a statement that writes outside one.
88
- */
89
- export function sqlClient(db, fence, committed = () => { }) {
90
- // `effect` as one SQL transaction: it commits when `effect` succeeds
91
- // and rolls back when it fails. Its statements go to the transaction's
92
- // database.
93
- const withTransaction = (effect) => Effect.withFiber((fiber) => {
94
- if (Option.isSome(Context.getOption(fiber.context, InTransaction))) {
95
- return Effect.fail(error('transaction', new Error('nested transactions are not supported')));
96
- }
97
- return Effect.callback((resume) => {
98
- const rollback = new Error('rollback');
99
- let interrupted = false;
100
- let resumed = false;
101
- let wrote = false;
102
- // Settles when the transaction has committed, or rejects: with
103
- // `rollback` once `effect` failed, or with the error of BEGIN or COMMIT.
104
- const ended = db.transaction((tx) => new Promise((resolve, reject) => {
105
- if (interrupted)
106
- return reject(rollback);
107
- const inner = Effect.provideContext(effect, Context.add(fiber.context, InTransaction, [connection(tx, fence, () => (wrote = true)), 0]));
108
- resumed = true;
109
- resume(
110
- // A finalizer, so that the body settles however `effect`
111
- // ends, an interruption included: otherwise the transaction
112
- // would hold the session for good.
113
- Effect.onExit(inner, (exit) => {
114
- if (Exit.isSuccess(exit)) {
115
- resolve();
116
- return Effect.void;
117
- }
118
- reject(rollback);
119
- return Effect.promise(() => settled);
120
- }).pipe(
121
- // The commit is part of the transaction: if it fails, so
122
- // does the transaction.
123
- Effect.flatMap((value) => Effect.as(Effect.tryPromise({ try: () => ended, catch: (e) => error('commit', e) }), value))));
124
- }));
125
- ended.then(() => (wrote ? committed() : undefined), () => undefined);
126
- const settled = ended.catch((cause) => {
127
- // BEGIN failed: `effect` never ran.
128
- if (!resumed && cause !== rollback)
129
- resume(Effect.fail(error('transaction', cause)));
130
- });
131
- return Effect.suspend(() => {
132
- interrupted = true;
133
- return Effect.promise(() => settled);
134
- });
135
- });
136
- });
137
- const make = Effect.gen(function* () {
138
- const client = yield* SqlClient.make({
139
- // Outside a transaction, a statement commits as it runs.
140
- acquirer: Effect.succeed(connection(db, fence, committed)),
141
- compiler: Statement.makeCompilerSqlite(),
142
- driver: 'sqlite-restate',
143
- spanAttributes: [['db.system.name', 'sqlite']],
144
- transactionService: InTransaction,
145
- });
146
- return Object.assign(client, { withTransaction, transactionStatements: false });
147
- });
148
- return Layer.effect(SqlClient.SqlClient, make).pipe(Layer.provide(Reactivity.layer));
149
- }
150
- /** The result `own` gives a running tool call of a closed turn, by default. */
151
- const CUT_OFF = 'The turn ended before this call returned: it may or may not have happened.';
152
- /** The error `own` closes a turn with, by default. */
153
- const ENDED = 'Ended: the turn was killed before it finished.';
154
- /**
155
- * A `SessionRestart` that closes each claimed top-level session this process
156
- * does not run: OpenCode's budget's events (`Execution.Failed`, the release
157
- * as its commit), and before them a `Tool.Failed` of our result for each
158
- * streaming or running tool part. No synthetic message, no drain, no model.
159
- */
160
- const closing = (cutOff, ended) => Layer.effect(SessionRestart.Service, Effect.gen(function* () {
161
- const store = yield* SessionStore.Service;
162
- const execution = yield* SessionExecution.Service;
163
- const bus = yield* Bus.Service;
164
- const close = Effect.fnUntraced(function* (sessionID) {
165
- for (const message of yield* Effect.orDie(store.context(sessionID))) {
166
- if (message.type !== 'assistant')
167
- continue;
168
- for (const part of message.content) {
169
- if (part.type !== 'tool')
170
- continue;
171
- if (part.state.status !== 'streaming' && part.state.status !== 'running')
172
- continue;
173
- yield* bus.publish(SessionEvent.Tool.Failed, {
174
- sessionID,
175
- assistantMessageID: message.id,
176
- id: part.id,
177
- error: { type: 'aborted', message: cutOff(part.id, part.name) },
178
- executed: part.executed === true,
179
- });
180
- }
181
- }
182
- yield* bus.publish(SessionEvent.Execution.Failed, { sessionID, error: { type: 'aborted', message: ended } }, { commit: () => store.release(sessionID) });
183
- });
184
- return SessionRestart.Service.of({
185
- resumeSuspendedSessions: Effect.gen(function* () {
186
- const active = yield* execution.active;
187
- // Child sessions' claims: v1 has no background subagents to recover.
188
- yield* store.releaseChildClaims([]);
189
- const claimed = (yield* store.listSuspended()).filter((id) => !active.has(id));
190
- yield* Effect.forEach(claimed, close, { discard: true });
191
- }),
192
- });
193
- }));
194
- /** The sweep's service for `restart` and `closer`. */
195
- const restarts = (restart, closer, cutOff, ended) => {
196
- if (restart === 'none')
197
- return Layer.succeed(SessionRestart.Service, { resumeSuspendedSessions: Effect.void });
198
- if (restart === 'resume')
199
- return SessionRestart.layer({ maxAttempts: Infinity });
200
- return closer === 'budget' ? SessionRestart.layer({ maxAttempts: 0 }) : closing(cutOff, ended);
201
- };
202
- /** `service`, whose sweep completes `done` as it ends, however it ends. */
203
- const observed = (layer, done) => Layer.effect(SessionRestart.Service, Effect.map(SessionRestart.Service, (inner) => SessionRestart.Service.of({
204
- resumeSuspendedSessions: inner.resumeSuspendedSessions.pipe(Effect.onExit((exit) => Effect.asVoid(Deferred.done(done, Exit.asVoid(exit))))),
205
- }))).pipe(Layer.provide(layer));
206
- /** What a replacement replaces: `LayerNode`'s own record of it (its source node). */
207
- const sourceOf = (replacement) => {
208
- const key = Object.getOwnPropertySymbols(replacement).find((s) => s.description === 'LayerNode.Replacement');
209
- return key && replacement[key]?.source;
210
- };
211
- /**
212
- * Boot OpenCode with its database in `db`; the boot sweeps the turns left
213
- * claimed as `restart` says. Close the host when done.
214
- */
215
- export async function openOpenCode(db, fence, { plugins = [], config = {}, local = false, restart = 'resume', closer = 'budget', committed, cutOff = () => CUT_OFF, ended = ENDED, }) {
216
- // The workerd profile, but for its database, which comes first. (The
217
- // Promise API's OpenCode.create takes no replacements; the Effect API's does.)
218
- const profile = { storage: undefined, models: { fetch: false } };
219
- // Taken by the node each replaces, not by position (2.1 added Npm's). Local
220
- // keeps the stubs of snapshots, the pty and plugin discovery only.
221
- const kept = local ? new Set([Snapshot.node, Pty.node, ConfigPluginSource.node]) : undefined;
222
- const rest = ServerWorkerd.replacements(profile).filter((r) => {
223
- const source = sourceOf(r);
224
- if (source === undefined)
225
- throw new Error('OpenCode: a workerd replacement of unknown node');
226
- return source !== OpenCodeDatabase.node && (kept === undefined || kept.has(source));
227
- });
228
- const scope = Scope.makeUnsafe();
229
- const done = Deferred.makeUnsafe();
230
- const sweep = observed(restarts(restart, closer, cutOff, ended), done);
231
- const client = await Effect.runPromise(OpenCode.create({
232
- ...ServerWorkerd.serverOptions({ ...profile, config: { content: JSON.stringify(config) } }),
233
- plugins: plugins.map(fromPromise),
234
- }, {
235
- overrides: [
236
- OpenCodeDatabase.node.replace(OpenCodeDatabase.configuredClient(sqlClient(db, fence, committed))),
237
- ...rest,
238
- SessionRestart.node.replace(SessionRestart.node.mapLayer(() => sweep)),
239
- ],
240
- }).pipe(Scope.provide(scope)));
241
- return {
242
- client,
243
- // The client's calls need nothing more: OpenCode provided it all.
244
- call: (effect) => Effect.runPromise(effect),
245
- swept: Effect.runPromise(Deferred.await(done)),
246
- close: () => Effect.runPromise(Scope.close(scope, Exit.void)),
247
- };
248
- }
249
- //# sourceMappingURL=db.js.map