@restatedev/agents 0.4.0 → 0.6.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 (101) hide show
  1. package/README.md +104 -38
  2. package/dist/calls.d.ts +20 -1
  3. package/dist/calls.d.ts.map +1 -1
  4. package/dist/calls.js +46 -7
  5. package/dist/calls.js.map +1 -1
  6. package/dist/claude/index.d.ts +11 -11
  7. package/dist/claude/index.d.ts.map +1 -1
  8. package/dist/claude/index.js +9 -6
  9. package/dist/claude/index.js.map +1 -1
  10. package/dist/client.d.ts +1 -1
  11. package/dist/client.d.ts.map +1 -1
  12. package/dist/common.d.ts +62 -23
  13. package/dist/common.d.ts.map +1 -1
  14. package/dist/common.js +67 -38
  15. package/dist/common.js.map +1 -1
  16. package/dist/{signals.d.ts → companion.d.ts} +106 -43
  17. package/dist/companion.d.ts.map +1 -0
  18. package/dist/companion.js +463 -0
  19. package/dist/companion.js.map +1 -0
  20. package/dist/conversation.d.ts +115 -5
  21. package/dist/conversation.d.ts.map +1 -1
  22. package/dist/conversation.js +308 -79
  23. package/dist/conversation.js.map +1 -1
  24. package/dist/deepseek/index.d.ts +11 -11
  25. package/dist/deepseek/index.d.ts.map +1 -1
  26. package/dist/deepseek/index.js +23 -26
  27. package/dist/deepseek/index.js.map +1 -1
  28. package/dist/index.d.ts +8 -4
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +7 -3
  31. package/dist/index.js.map +1 -1
  32. package/dist/langgraph/checkpointer.d.ts +2 -0
  33. package/dist/langgraph/checkpointer.d.ts.map +1 -1
  34. package/dist/langgraph/checkpointer.js +1 -1
  35. package/dist/langgraph/checkpointer.js.map +1 -1
  36. package/dist/langgraph/graph.d.ts.map +1 -1
  37. package/dist/langgraph/graph.js +32 -13
  38. package/dist/langgraph/graph.js.map +1 -1
  39. package/dist/langgraph/index.d.ts +11 -11
  40. package/dist/langgraph/index.d.ts.map +1 -1
  41. package/dist/langgraph/index.js +19 -13
  42. package/dist/langgraph/index.js.map +1 -1
  43. package/dist/langgraph/nodes.d.ts +2 -1
  44. package/dist/langgraph/nodes.d.ts.map +1 -1
  45. package/dist/langgraph/nodes.js +23 -20
  46. package/dist/langgraph/nodes.js.map +1 -1
  47. package/dist/object.d.ts +24 -22
  48. package/dist/object.d.ts.map +1 -1
  49. package/dist/object.js +16 -11
  50. package/dist/object.js.map +1 -1
  51. package/dist/opencode/db.d.ts +81 -0
  52. package/dist/opencode/db.d.ts.map +1 -0
  53. package/dist/opencode/db.js +249 -0
  54. package/dist/opencode/db.js.map +1 -0
  55. package/dist/opencode/index.d.ts +184 -0
  56. package/dist/opencode/index.d.ts.map +1 -0
  57. package/dist/opencode/index.js +982 -0
  58. package/dist/opencode/index.js.map +1 -0
  59. package/dist/pi/index.d.ts +11 -11
  60. package/dist/pi/index.d.ts.map +1 -1
  61. package/dist/pi/index.js +16 -17
  62. package/dist/pi/index.js.map +1 -1
  63. package/dist/steering.d.ts +2 -1
  64. package/dist/steering.d.ts.map +1 -1
  65. package/dist/steering.js +2 -2
  66. package/dist/steering.js.map +1 -1
  67. package/dist/tools.d.ts +21 -0
  68. package/dist/tools.d.ts.map +1 -1
  69. package/dist/tools.js +54 -14
  70. package/dist/tools.js.map +1 -1
  71. package/dist/webhook.js +1 -1
  72. package/dist/webhook.js.map +1 -1
  73. package/package.json +37 -4
  74. package/src/calls.ts +52 -11
  75. package/src/claude/README.md +4 -2
  76. package/src/claude/index.ts +9 -7
  77. package/src/client.ts +1 -1
  78. package/src/common.ts +99 -40
  79. package/src/companion.ts +674 -0
  80. package/src/conversation.ts +377 -105
  81. package/src/deepseek/README.md +7 -1
  82. package/src/deepseek/index.ts +22 -24
  83. package/src/index.ts +10 -4
  84. package/src/langgraph/README.md +8 -5
  85. package/src/langgraph/checkpointer.ts +1 -1
  86. package/src/langgraph/graph.ts +30 -16
  87. package/src/langgraph/index.ts +24 -17
  88. package/src/langgraph/nodes.ts +24 -20
  89. package/src/object.ts +45 -40
  90. package/src/opencode/README.md +234 -0
  91. package/src/opencode/db.ts +387 -0
  92. package/src/opencode/index.ts +1243 -0
  93. package/src/pi/README.md +6 -1
  94. package/src/pi/index.ts +16 -15
  95. package/src/steering.ts +8 -7
  96. package/src/tools.ts +60 -18
  97. package/src/webhook.ts +1 -1
  98. package/dist/signals.d.ts.map +0 -1
  99. package/dist/signals.js +0 -383
  100. package/dist/signals.js.map +0 -1
  101. package/src/signals.ts +0 -590
@@ -0,0 +1,387 @@
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
+ }