@restatedev/agents 0.0.0-stage → 0.1.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 (108) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +689 -2
  3. package/dist/calls.d.ts +29 -0
  4. package/dist/calls.d.ts.map +1 -0
  5. package/dist/calls.js +91 -0
  6. package/dist/calls.js.map +1 -0
  7. package/dist/claude/conversation.d.ts +33 -0
  8. package/dist/claude/conversation.d.ts.map +1 -0
  9. package/dist/claude/conversation.js +95 -0
  10. package/dist/claude/conversation.js.map +1 -0
  11. package/dist/claude/index.d.ts +78 -0
  12. package/dist/claude/index.d.ts.map +1 -0
  13. package/dist/claude/index.js +269 -0
  14. package/dist/claude/index.js.map +1 -0
  15. package/dist/client.d.ts +83 -0
  16. package/dist/client.d.ts.map +1 -0
  17. package/dist/client.js +88 -0
  18. package/dist/client.js.map +1 -0
  19. package/dist/common.d.ts +284 -0
  20. package/dist/common.d.ts.map +1 -0
  21. package/dist/common.js +475 -0
  22. package/dist/common.js.map +1 -0
  23. package/dist/deepseek/index.d.ts +69 -0
  24. package/dist/deepseek/index.d.ts.map +1 -0
  25. package/dist/deepseek/index.js +381 -0
  26. package/dist/deepseek/index.js.map +1 -0
  27. package/dist/deepseek/persistence.d.ts +61 -0
  28. package/dist/deepseek/persistence.d.ts.map +1 -0
  29. package/dist/deepseek/persistence.js +224 -0
  30. package/dist/deepseek/persistence.js.map +1 -0
  31. package/dist/index.d.ts +15 -0
  32. package/dist/index.d.ts.map +1 -0
  33. package/dist/index.js +37 -0
  34. package/dist/index.js.map +1 -0
  35. package/dist/langgraph/checkpointer.d.ts +29 -0
  36. package/dist/langgraph/checkpointer.d.ts.map +1 -0
  37. package/dist/langgraph/checkpointer.js +275 -0
  38. package/dist/langgraph/checkpointer.js.map +1 -0
  39. package/dist/langgraph/index.d.ts +67 -0
  40. package/dist/langgraph/index.d.ts.map +1 -0
  41. package/dist/langgraph/index.js +265 -0
  42. package/dist/langgraph/index.js.map +1 -0
  43. package/dist/log.d.ts +29 -0
  44. package/dist/log.d.ts.map +1 -0
  45. package/dist/log.js +145 -0
  46. package/dist/log.js.map +1 -0
  47. package/dist/object.d.ts +181 -0
  48. package/dist/object.d.ts.map +1 -0
  49. package/dist/object.js +232 -0
  50. package/dist/object.js.map +1 -0
  51. package/dist/opencode/db.d.ts +40 -0
  52. package/dist/opencode/db.d.ts.map +1 -0
  53. package/dist/opencode/db.js +161 -0
  54. package/dist/opencode/db.js.map +1 -0
  55. package/dist/opencode/index.d.ts +101 -0
  56. package/dist/opencode/index.d.ts.map +1 -0
  57. package/dist/opencode/index.js +464 -0
  58. package/dist/opencode/index.js.map +1 -0
  59. package/dist/output.d.ts +17 -0
  60. package/dist/output.d.ts.map +1 -0
  61. package/dist/output.js +81 -0
  62. package/dist/output.js.map +1 -0
  63. package/dist/pi/index.d.ts +90 -0
  64. package/dist/pi/index.d.ts.map +1 -0
  65. package/dist/pi/index.js +313 -0
  66. package/dist/pi/index.js.map +1 -0
  67. package/dist/pi/storage.d.ts +5 -0
  68. package/dist/pi/storage.d.ts.map +1 -0
  69. package/dist/pi/storage.js +41 -0
  70. package/dist/pi/storage.js.map +1 -0
  71. package/dist/signals.d.ts +195 -0
  72. package/dist/signals.d.ts.map +1 -0
  73. package/dist/signals.js +258 -0
  74. package/dist/signals.js.map +1 -0
  75. package/dist/tools.d.ts +158 -0
  76. package/dist/tools.d.ts.map +1 -0
  77. package/dist/tools.js +211 -0
  78. package/dist/tools.js.map +1 -0
  79. package/dist/webhook.d.ts +73 -0
  80. package/dist/webhook.d.ts.map +1 -0
  81. package/dist/webhook.js +104 -0
  82. package/dist/webhook.js.map +1 -0
  83. package/package.json +224 -3
  84. package/src/calls.ts +138 -0
  85. package/src/claude/README.md +84 -0
  86. package/src/claude/conversation.ts +114 -0
  87. package/src/claude/index.ts +364 -0
  88. package/src/client.ts +179 -0
  89. package/src/common.ts +593 -0
  90. package/src/deepseek/README.md +110 -0
  91. package/src/deepseek/index.ts +487 -0
  92. package/src/deepseek/persistence.ts +293 -0
  93. package/src/index.ts +60 -0
  94. package/src/langgraph/README.md +87 -0
  95. package/src/langgraph/checkpointer.ts +364 -0
  96. package/src/langgraph/index.ts +349 -0
  97. package/src/log.ts +193 -0
  98. package/src/object.ts +343 -0
  99. package/src/opencode/README.md +125 -0
  100. package/src/opencode/db.ts +223 -0
  101. package/src/opencode/index.ts +595 -0
  102. package/src/output.ts +95 -0
  103. package/src/pi/README.md +105 -0
  104. package/src/pi/index.ts +402 -0
  105. package/src/pi/storage.ts +65 -0
  106. package/src/signals.ts +426 -0
  107. package/src/tools.ts +343 -0
  108. package/src/webhook.ts +163 -0
@@ -0,0 +1,223 @@
1
+ // OpenCode on the object's database: `openOpenCode(db, fence, options)` boots
2
+ // OpenCode 2.0's embedded host (@opencode/sdk) with its database in a
3
+ // SQL 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 or version control,
7
+ // config given inline, plugins given in code. Only its database differs. The
8
+ // workerd profile reads a Durable Object's SQLite, whose `exec` is
9
+ // synchronous; here OpenCode gets an Effect SqlClient instead, which is
10
+ // asynchronous, through `Database.configuredClient` (OpenCode's), the seam OpenCode keeps
11
+ // for an injected client. Each transaction is an SQL transaction, and the
12
+ // session runs statements one at a time, as OpenCode's own clients do.
13
+ //
14
+ // `fence.closed` refuses every statement from then on: an attempt that is
15
+ // giving up stores nothing more, as Restate fences an attempt that a newer
16
+ // one replaced.
17
+ import { Context, Effect, Exit, Layer, Option, Scope } from 'effect';
18
+ import { Reactivity } from 'effect/reactivity';
19
+ import { SqlClient, Statement } from 'effect/sql';
20
+ import { SqlError, UnknownError } from 'effect/sql/SqlError';
21
+ import type { Connection } from 'effect/sql/SqlConnection';
22
+ import { Database as OpenCodeDatabase } from '@opencode/core/database/database';
23
+ import { SessionRestart } from '@opencode/core/session/execution/restart';
24
+ import { ServerWorkerd } from '@opencode/server/workerd';
25
+ import { fromPromise } from '@opencode/core/plugin/promise';
26
+ import { OpenCode } from '@opencode/sdk/effect';
27
+ import type { Plugin } from '@opencode/plugin';
28
+ import type { DatabaseWriter, Database, SqlValue } from '@restatedev/sessions';
29
+
30
+ /** Closed: every later statement fails. */
31
+ export interface Fence {
32
+ closed: boolean;
33
+ }
34
+
35
+ const error = (operation: string, cause: unknown) =>
36
+ new SqlError({
37
+ reason: new UnknownError({
38
+ cause,
39
+ message: cause instanceof Error ? cause.message : String(cause),
40
+ operation,
41
+ }),
42
+ });
43
+
44
+ /** The connection inside a transaction, for statements of that transaction. */
45
+ const InTransaction = Context.Service<SqlClient.TransactionConnection, SqlClient.TransactionConnection.Service>(
46
+ '@restatedev/agents/OpenCodeTransaction',
47
+ );
48
+
49
+ /**
50
+ * A connection whose statements go to `target`: the session, which runs one
51
+ * call at a time and holds them while a transaction runs, or that
52
+ * transaction's database. Each is refused once `fence` closes.
53
+ */
54
+ function connection(target: DatabaseWriter, fence: Fence): Connection {
55
+ // Effect binds what the compiler made of OpenCode's values: SQL values.
56
+ const exec = <T>(read: (sql: string, params: SqlValue[]) => Promise<T>, sql: string, params: readonly unknown[]) =>
57
+ Effect.tryPromise({
58
+ try: async () => {
59
+ if (fence.closed) throw new Error('the attempt is over');
60
+ return read(sql, params as SqlValue[]);
61
+ },
62
+ catch: (cause) => error('execute', cause),
63
+ });
64
+ const run = (sql: string, params: readonly unknown[] = []) => exec((s, p) => target.query(s, p), sql, params);
65
+ const runValues = (sql: string, params: readonly unknown[] = []) => exec((s, p) => target.values(s, p), sql, params);
66
+ const transformed: Connection['execute'] = (sql, params, transformRows) =>
67
+ transformRows ? Effect.map(run(sql, params), transformRows) : run(sql, params);
68
+ return {
69
+ execute: transformed,
70
+ executeRaw: (sql, params) => run(sql, params),
71
+ executeValues: (sql, params) => runValues(sql, params),
72
+ executeValuesUnprepared: (sql, params) => runValues(sql, params),
73
+ executeUnprepared: transformed,
74
+ executeStream: () => {
75
+ throw new Error('executeStream is not supported');
76
+ },
77
+ };
78
+ }
79
+
80
+ /** An Effect SqlClient over `db`, with its statements refused once `fence` closes. */
81
+ export function sqlClient(db: Database, fence: Fence): Layer.Layer<SqlClient.SqlClient> {
82
+ // `effect` as one SQL transaction: it commits when `effect` succeeds
83
+ // and rolls back when it fails. Its statements go to the transaction's
84
+ // database.
85
+ const withTransaction = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
86
+ Effect.withFiber<A, E | SqlError, R>((fiber) => {
87
+ if (Option.isSome(Context.getOption(fiber.context, InTransaction))) {
88
+ return Effect.fail(error('transaction', new Error('nested transactions are not supported')));
89
+ }
90
+ return Effect.callback<A, E | SqlError, R>((resume) => {
91
+ const rollback = new Error('rollback');
92
+ let interrupted = false;
93
+ let resumed = false;
94
+ // Settles when the transaction has committed, or rejects: with
95
+ // `rollback` once `effect` failed, or with the error of BEGIN or COMMIT.
96
+ const ended: Promise<void> = db.transaction(
97
+ (tx) =>
98
+ new Promise<void>((resolve, reject) => {
99
+ if (interrupted) return reject(rollback);
100
+ const inner = Effect.provideContext(
101
+ effect,
102
+ Context.add(fiber.context, InTransaction, [connection(tx, fence), 0]),
103
+ );
104
+ resumed = true;
105
+ resume(
106
+ // A finalizer, so that the body settles however `effect`
107
+ // ends, an interruption included: otherwise the transaction
108
+ // would hold the session for good.
109
+ Effect.onExit(inner, (exit) => {
110
+ if (Exit.isSuccess(exit)) {
111
+ resolve();
112
+ return Effect.void;
113
+ }
114
+ reject(rollback);
115
+ return Effect.promise(() => settled);
116
+ }).pipe(
117
+ // The commit is part of the transaction: if it fails, so
118
+ // does the transaction.
119
+ Effect.flatMap((value) =>
120
+ Effect.as(Effect.tryPromise({ try: () => ended, catch: (e) => error('commit', e) }), value),
121
+ ),
122
+ ),
123
+ );
124
+ }),
125
+ );
126
+ const settled = ended.catch((cause: unknown) => {
127
+ // BEGIN failed: `effect` never ran.
128
+ if (!resumed && cause !== rollback) resume(Effect.fail(error('transaction', cause)));
129
+ });
130
+ return Effect.suspend(() => {
131
+ interrupted = true;
132
+ return Effect.promise(() => settled);
133
+ });
134
+ });
135
+ });
136
+
137
+ const make = Effect.gen(function* () {
138
+ const client = yield* SqlClient.make({
139
+ acquirer: Effect.succeed(connection(db, fence)),
140
+ compiler: Statement.makeCompilerSqlite(),
141
+ spanAttributes: [['db.system.name', 'sqlite']],
142
+ transactionService: InTransaction,
143
+ });
144
+ return Object.assign(client, { withTransaction, transactionStatements: false });
145
+ });
146
+ return Layer.effect(SqlClient.SqlClient, make).pipe(Layer.provide(Reactivity.layer));
147
+ }
148
+
149
+ export interface OpenOptions {
150
+ /** OpenCode plugins: models, tools, agents. */
151
+ plugins?: Plugin.Plugin[];
152
+ /** OpenCode's config (opencode.json), inline. */
153
+ config?: Record<string, unknown>;
154
+ /**
155
+ * OpenCode's own filesystem, search and shell, on the local machine, for
156
+ * its built-in tools (read, write, edit, bash, glob, grep...) in a
157
+ * session's directory. Without it, the workerd profile has none.
158
+ */
159
+ local?: boolean;
160
+ /**
161
+ * Resume the turns a previous attempt left unfinished, as OpenCode does
162
+ * when it boots (default true). A reader beside a running turn does not.
163
+ */
164
+ resume?: boolean;
165
+ }
166
+
167
+ /** A booted OpenCode: `call` runs one of `client`'s calls (which return Effects); `close` shuts it down. */
168
+ export interface Host {
169
+ client: OpenCode.Interface;
170
+ call<A, E, R>(effect: Effect.Effect<A, E, R>): Promise<A>;
171
+ close(): Promise<void>;
172
+ }
173
+
174
+ /**
175
+ * How OpenCode resumes the turns a previous attempt left unfinished when it
176
+ * boots: each, however often it crashed (Restate's retry policy decides how
177
+ * often an attempt is retried), or, without `resume`, none.
178
+ */
179
+ const restarts = (resume: boolean) =>
180
+ resume
181
+ ? SessionRestart.layer({ maxAttempts: Infinity })
182
+ : Layer.succeed(SessionRestart.Service, { resumeSuspendedSessions: Effect.void });
183
+
184
+ /**
185
+ * Boot OpenCode with its database in `db`. Booting resumes the turns a
186
+ * previous attempt left unfinished. Close the host when done.
187
+ */
188
+ export async function openOpenCode(
189
+ db: Database,
190
+ fence: Fence,
191
+ { plugins = [], config = {}, local = false, resume = true }: OpenOptions,
192
+ ): Promise<Host> {
193
+ // The workerd profile, but for its database, which comes first. (The
194
+ // Promise API's OpenCode.create takes no replacements; the Effect API's does.)
195
+ const profile = { storage: undefined as never, models: { fetch: false } };
196
+ // In 2.0.27's order: database, process spawner, snapshot, version control,
197
+ // filesystem, filesystem search, pty, plugin discovery. Local keeps the
198
+ // stubs of snapshots, the pty and plugin discovery only.
199
+ const [, spawner, snapshot, vcs, fs, search, pty, discovery] = ServerWorkerd.replacements(profile);
200
+ const rest = local ? [snapshot, pty, discovery] : [spawner, snapshot, vcs, fs, search, pty, discovery];
201
+ const scope = Scope.makeUnsafe();
202
+ const client = await Effect.runPromise(
203
+ OpenCode.create(
204
+ {
205
+ ...ServerWorkerd.serverOptions({ ...profile, config: { content: JSON.stringify(config) } }),
206
+ plugins: plugins.map(fromPromise),
207
+ },
208
+ {
209
+ overrides: [
210
+ OpenCodeDatabase.node.replace(OpenCodeDatabase.configuredClient(sqlClient(db, fence))),
211
+ ...rest,
212
+ SessionRestart.node.replace(SessionRestart.node.mapLayer(() => restarts(resume) as never)),
213
+ ],
214
+ },
215
+ ).pipe(Scope.provide(scope)),
216
+ );
217
+ return {
218
+ client,
219
+ // The client's calls need nothing more: OpenCode provided it all.
220
+ call: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.runPromise(effect as Effect.Effect<A, E>),
221
+ close: () => Effect.runPromise(Scope.close(scope, Exit.void)),
222
+ };
223
+ }