@restatedev/agents 0.10.3 → 0.11.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 (68) hide show
  1. package/README.md +10 -0
  2. package/dist/agentlib/tools.js +2 -0
  3. package/dist/agentlib/tools.js.map +1 -1
  4. package/dist/calls.d.ts +14 -8
  5. package/dist/calls.d.ts.map +1 -1
  6. package/dist/calls.js +24 -11
  7. package/dist/calls.js.map +1 -1
  8. package/dist/claude/index.d.ts.map +1 -1
  9. package/dist/claude/index.js +33 -4
  10. package/dist/claude/index.js.map +1 -1
  11. package/dist/common.d.ts +12 -0
  12. package/dist/common.d.ts.map +1 -1
  13. package/dist/common.js +30 -0
  14. package/dist/common.js.map +1 -1
  15. package/dist/deepseek/index.d.ts.map +1 -1
  16. package/dist/deepseek/index.js +7 -3
  17. package/dist/deepseek/index.js.map +1 -1
  18. package/dist/langgraph/graph.d.ts.map +1 -1
  19. package/dist/langgraph/graph.js +8 -0
  20. package/dist/langgraph/graph.js.map +1 -1
  21. package/dist/langgraph/index.d.ts.map +1 -1
  22. package/dist/langgraph/index.js +2 -2
  23. package/dist/langgraph/index.js.map +1 -1
  24. package/dist/langgraph/keepalive.d.ts +16 -0
  25. package/dist/langgraph/keepalive.d.ts.map +1 -0
  26. package/dist/langgraph/keepalive.js +51 -0
  27. package/dist/langgraph/keepalive.js.map +1 -0
  28. package/dist/opencode/index.d.ts.map +1 -1
  29. package/dist/opencode/index.js +108 -24
  30. package/dist/opencode/index.js.map +1 -1
  31. package/dist/pi/commits.d.ts +6 -0
  32. package/dist/pi/commits.d.ts.map +1 -0
  33. package/dist/pi/commits.js +3 -0
  34. package/dist/pi/commits.js.map +1 -0
  35. package/dist/pi/index.d.ts +14 -1
  36. package/dist/pi/index.d.ts.map +1 -1
  37. package/dist/pi/index.js +91 -9
  38. package/dist/pi/index.js.map +1 -1
  39. package/dist/pi/keepalive.d.ts +21 -0
  40. package/dist/pi/keepalive.d.ts.map +1 -0
  41. package/dist/pi/keepalive.js +98 -0
  42. package/dist/pi/keepalive.js.map +1 -0
  43. package/dist/pi/storage.d.ts +62 -3
  44. package/dist/pi/storage.d.ts.map +1 -1
  45. package/dist/pi/storage.js +355 -12
  46. package/dist/pi/storage.js.map +1 -1
  47. package/dist/tools.d.ts +9 -0
  48. package/dist/tools.d.ts.map +1 -1
  49. package/dist/tools.js +9 -1
  50. package/dist/tools.js.map +1 -1
  51. package/package.json +3 -3
  52. package/src/agentlib/tools.ts +2 -0
  53. package/src/calls.ts +25 -11
  54. package/src/claude/index.ts +36 -6
  55. package/src/common.ts +32 -0
  56. package/src/deepseek/index.ts +7 -1
  57. package/src/langgraph/README.md +10 -0
  58. package/src/langgraph/graph.ts +7 -0
  59. package/src/langgraph/index.ts +3 -3
  60. package/src/langgraph/keepalive.ts +58 -0
  61. package/src/opencode/README.md +15 -0
  62. package/src/opencode/index.ts +104 -22
  63. package/src/pi/README.md +64 -15
  64. package/src/pi/commits.ts +7 -0
  65. package/src/pi/index.ts +116 -7
  66. package/src/pi/keepalive.ts +121 -0
  67. package/src/pi/storage.ts +382 -10
  68. package/src/tools.ts +12 -1
@@ -0,0 +1,121 @@
1
+ // pi-durable makes a model's request in this process, through the model
2
+ // registry (`runtime.models`): `streamSimple` for a turn's request, `fetchDeferred`
3
+ // for one a provider answers later, `completeSimple` for a compaction's. A
4
+ // request keeps the attempt alive (`ctx.working`) from its call to its end.
5
+ // `Harness.open({ models })` takes the registry, so each of its requests is
6
+ // covered by wrapping it, with nothing of pi-durable's own patched.
7
+ import type { Models } from '@earendil-works/pi-ai';
8
+ import type { AssistantMessageEventStream } from '@earendil-works/pi-ai';
9
+ import type * as restate from '@restatedev/sessions';
10
+ import { keepAlive } from '../common.ts';
11
+
12
+ /** `Models`' methods that return an event stream: the request is out as it is called, and ends with the stream. */
13
+ const STREAMS = new Set<PropertyKey>(['stream', 'streamSimple', 'streamDeferred']);
14
+
15
+ /** `Models`' methods that return a promise of the request's result: the request is out until it settles. */
16
+ const REQUESTS = new Set<PropertyKey>([
17
+ 'complete',
18
+ 'completeSimple',
19
+ 'fetchDeferred',
20
+ 'cancelDeferred',
21
+ 'generateImages',
22
+ 'classify',
23
+ ]);
24
+
25
+ /**
26
+ * What a request of the model does with pi's batched commits (storage.ts): it
27
+ * is an effect, so what pi committed before it is written, and its own
28
+ * commits are not batched until it is over.
29
+ */
30
+ export interface Effects {
31
+ /** The request starts: commits are written at once until the returned function is called (once at most). */
32
+ started(): () => void;
33
+ /** Write what is batched. */
34
+ flush(): Promise<void>;
35
+ }
36
+
37
+ /**
38
+ * `stream`, kept alive until its response is over: it ends or fails (its
39
+ * `result()` settles: pi-ai ends a stream that is aborted with an error
40
+ * event), its consumer leaves it early, or `signal` aborts. Then `ended`
41
+ * is called too: the same events, and no more, so a stream that none of
42
+ * them reaches never ends its effect, and the batching stays off.
43
+ */
44
+ function keptStream(
45
+ ctx: restate.SessionContext,
46
+ stream: AssistantMessageEventStream,
47
+ signal: AbortSignal | undefined,
48
+ ended: () => void,
49
+ ): AssistantMessageEventStream {
50
+ const alive = keepAlive(ctx);
51
+ const release = () => {
52
+ alive();
53
+ ended();
54
+ };
55
+ stream.result().then(release, release);
56
+ signal?.addEventListener('abort', release, { once: true });
57
+ if (signal?.aborted) release();
58
+ const iterate = stream[Symbol.asyncIterator].bind(stream);
59
+ // A consumer that stops iterating (a `break`, a throw) abandons the stream: the response is not waited for.
60
+ stream[Symbol.asyncIterator] = () => {
61
+ const iterator = iterate();
62
+ return {
63
+ next: (...args) => iterator.next(...args),
64
+ return: (value) => {
65
+ release();
66
+ return iterator.return?.(value) ?? Promise.resolve({ done: true as const, value });
67
+ },
68
+ throw: async (error) => {
69
+ release();
70
+ if (iterator.throw) return iterator.throw(error);
71
+ throw error;
72
+ },
73
+ };
74
+ };
75
+ return stream;
76
+ }
77
+
78
+ /**
79
+ * `models`, each request of whose methods keeps the attempt of `ctx` alive as
80
+ * long as it is out. With `effects`, each is also an effect: a stream's flush
81
+ * is started as the stream is made and not waited for (the request has no
82
+ * effect that must not repeat), a promise-returning method's is waited for.
83
+ */
84
+ export function keptModels<M extends Models>(ctx: restate.SessionContext, models: M, effects?: Effects): M {
85
+ return new Proxy(models, {
86
+ get(target, property) {
87
+ const member: unknown = Reflect.get(target, property, target);
88
+ if (typeof member !== 'function') return member;
89
+ const method = member.bind(target) as (...args: unknown[]) => unknown;
90
+ if (STREAMS.has(property)) {
91
+ return (...args: unknown[]) => {
92
+ const options = args.at(-1) as { signal?: AbortSignal } | undefined;
93
+ const ended = effects?.started() ?? (() => {});
94
+ // A failed flush fails the attempt itself (storage.ts), and is never this request's error.
95
+ void effects?.flush().catch(() => {});
96
+ let stream: AssistantMessageEventStream;
97
+ try {
98
+ stream = method(...args) as AssistantMessageEventStream;
99
+ } catch (error) {
100
+ ended();
101
+ throw error;
102
+ }
103
+ return keptStream(ctx, stream, options?.signal, ended);
104
+ };
105
+ }
106
+ if (REQUESTS.has(property)) {
107
+ if (!effects) return (...args: unknown[]) => ctx.working(() => method(...args) as Promise<unknown>);
108
+ return async (...args: unknown[]) => {
109
+ const ended = effects.started();
110
+ try {
111
+ await effects.flush();
112
+ return await ctx.working(() => method(...args) as Promise<unknown>);
113
+ } finally {
114
+ ended();
115
+ }
116
+ };
117
+ }
118
+ return method;
119
+ },
120
+ });
121
+ }
package/src/pi/storage.ts CHANGED
@@ -8,9 +8,17 @@
8
8
  // once its body settles. A statement outside a transaction is its own
9
9
  // transaction.
10
10
  //
11
+ // With `commits: 'effects'` the adapter batches: between two effects (a model
12
+ // call, a tool) the commits of pi share one transaction of the session, held
13
+ // open and written once, when an effect starts, something else is about to
14
+ // see what was stored, or another call to the session waits for it. See
15
+ // {@link SqlKvDatabase}.
16
+ //
11
17
  // pi-durable's tables and indexes are named `restate_pi_<name>` (its
12
18
  // storage's `prefix`), apart from the tables of yours in the same database.
19
+ import { AsyncLocalStorage } from 'node:async_hooks';
13
20
  import type { DatabaseWriter, Database, Transaction } from '@restatedev/sessions';
21
+ import { deferSql, undeferSql } from '@restatedev/sessions/internal';
14
22
  import {
15
23
  SqliteStorage,
16
24
  type SqliteDatabase,
@@ -46,43 +54,407 @@ class Executor implements SqliteExecutor {
46
54
  }
47
55
  }
48
56
 
57
+ /** The savepoint of a pi commit in a batch, and its end. */
58
+ const SAVEPOINT = 'SAVEPOINT restate_pi';
59
+ const RELEASE = 'RELEASE restate_pi';
60
+
49
61
  /** What runs at the end of each pi commit, in its transaction: the copy of its entries (index.ts). */
50
62
  export type OnCommit = (tx: Transaction) => Promise<void>;
51
63
 
52
- /** The `SqliteDatabase` facade over the session `db`. */
64
+ /** How pi's commits are written: one each, or one for all those between two effects. */
65
+ export type Commits = 'effects' | 'each';
66
+
67
+ /** What the adapter reports and takes. */
68
+ export interface SqlKvOptions {
69
+ /** Default `'each'`: every pi commit is a transaction of the session, as ever. */
70
+ commits?: Commits;
71
+ /**
72
+ * Told once, with the error, when a batch fails to commit: the pi commits
73
+ * in it were reported to pi as done and are lost, so the attempt must
74
+ * fail (the adapter's later calls all reject with that error, too).
75
+ */
76
+ failed?: (error: unknown) => void;
77
+ }
78
+
79
+ /** The transaction that holds a batch of pi's commits open: its handle, and how to end it. */
80
+ interface Batch {
81
+ readonly tx: Transaction;
82
+ /** Run a function in the async context of the transaction's body, where the session refuses `ctx.db` calls. */
83
+ readonly run: <R>(fn: () => R) => R;
84
+ /** Let the body return, so that the transaction commits. */
85
+ readonly release: () => void;
86
+ /** Make the body throw `error`, so that the session rolls the whole transaction back, its sends with it. */
87
+ readonly abort: (error: unknown) => void;
88
+ }
89
+
90
+ /** An open batch, and the promise that settles when its transaction has committed or failed. */
91
+ interface Held {
92
+ readonly batch: Batch;
93
+ readonly done: Promise<void>;
94
+ /** Whether a write of it was told to its caller as done: only then is a failure to commit it a loss. */
95
+ acknowledged: boolean;
96
+ }
97
+
98
+ /** `tx`, whose `send` is the real one, and tells `sent` when it is called. */
99
+ function noting(tx: Transaction, sent: () => void): Transaction {
100
+ const send = new Proxy(tx.send, {
101
+ apply(target, thisArg, args: Parameters<Transaction['send']>) {
102
+ sent();
103
+ return Reflect.apply(target, thisArg, args) as unknown;
104
+ },
105
+ });
106
+ return { ...tx, send };
107
+ }
108
+
109
+ /** The refusal of a call to the adapter from the callback of one of its transactions, which would wait for itself. */
110
+ const REFUSED = 'inside a transaction, use the transaction handle its callback gets';
111
+
112
+ /**
113
+ * The `SqliteDatabase` facade over the session `db`.
114
+ *
115
+ * With the default `commits: 'each'`, each `transaction(callback)` of pi is
116
+ * one transaction of the session: one write, one round trip to Restate.
117
+ *
118
+ * With `'effects'`, while it is {@link armed} and no effect is in flight
119
+ * ({@link effectStarted}), the first write opens one transaction of the
120
+ * session that stays open, and each pi transaction is a savepoint in it
121
+ * (a failed one undoes only itself). {@link flush} ends it: the real commit,
122
+ * and then the `afterCommit` of every pi commit in it. It ends also when
123
+ * another call to the session queues behind it (a `ctx.db` call of the
124
+ * handler): that call then waits for one commit and no more. While an
125
+ * effect is in flight, every pi commit is a transaction of its own, as with
126
+ * `'each'`. Reads see the open batch. All calls run one at a time on a chain
127
+ * of their own.
128
+ */
53
129
  export class SqlKvDatabase extends Executor implements SqliteDatabase {
54
130
  readonly #session: Database;
131
+ readonly #batching: boolean;
132
+ readonly #failed: ((error: unknown) => void) | undefined;
55
133
  /** Runs at the end of each commit, in its transaction, so that what it writes commits with it. */
56
134
  onCommit: OnCommit | undefined;
57
135
  /** Runs once each commit is done, outside its transaction: to tell others what it stored, say. */
58
136
  afterCommit: (() => Promise<void>) | undefined;
137
+ /** Settles when the last call made so far has: the next runs after it. */
138
+ #chain: Promise<unknown> = Promise.resolve();
139
+ #batch: Held | undefined;
140
+ #armed = false;
141
+ #effects = 0;
142
+ /** The `afterCommit` of each commit in the batch, run after its real commit. */
143
+ #after: (() => Promise<void>)[] = [];
144
+ /** The error of the first batch that failed, which every later call fails with. */
145
+ #failure: { error: unknown } | undefined;
146
+ /** Whether the attempt has been told of it. */
147
+ #told = false;
148
+ /** Settles when the `afterCommit` callbacks started so far have run. */
149
+ #afterRun: Promise<unknown> = Promise.resolve();
150
+ /** Set while `afterCommit` callbacks run: a flush from one of them has them to wait for. */
151
+ readonly #inAfter = new AsyncLocalStorage<true>();
152
+ /** Set inside the callback of a transaction: a call to the adapter from there would wait for itself. */
153
+ readonly #inside = new AsyncLocalStorage<true>();
59
154
 
60
- constructor(db: Database) {
155
+ constructor(db: Database, { commits = 'each', failed }: SqlKvOptions = {}) {
61
156
  super(db);
62
157
  this.#session = db;
158
+ this.#batching = commits === 'effects';
159
+ this.#failed = failed;
160
+ }
161
+
162
+ /**
163
+ * Whether commits are batched while no effect is in flight: set while pi
164
+ * runs a prompt, and off otherwise. Ending the batch is the caller's
165
+ * ({@link flush}). Without `'effects'` it does nothing.
166
+ */
167
+ set armed(armed: boolean) {
168
+ this.#armed = armed && this.#batching;
169
+ }
170
+
171
+ /**
172
+ * An effect starts: a model call or a tool, which must see what pi stored
173
+ * before, and which may store commits of its own. Until the returned
174
+ * function is called (once at most; later calls do nothing) every commit
175
+ * is written at once. It starts no flush: {@link flush} does. An effect
176
+ * whose end is never called leaves the batching off, which is how it was.
177
+ */
178
+ effectStarted(): () => void {
179
+ if (!this.#batching) return () => {};
180
+ this.#effects++;
181
+ let ended = false;
182
+ return () => {
183
+ if (ended) return;
184
+ ended = true;
185
+ this.#effects--;
186
+ };
187
+ }
188
+
189
+ /**
190
+ * Write what the batch holds: its real commit, then what `afterCommit`
191
+ * of each of its commits does, in order. Nothing if none is open.
192
+ * Rejects if the commit failed (see {@link SqlKvOptions.failed}), and from
193
+ * the callback of a transaction, which would wait for itself.
194
+ */
195
+ async flush(): Promise<void> {
196
+ if (!this.#batching) return;
197
+ if (this.#inside.getStore()) throw new Error(REFUSED);
198
+ await this.#run(() => this.#closeBatch());
199
+ await this.#runAfter();
63
200
  }
64
201
 
65
202
  /** Commits when the callback resolves; rolls back, and rejects with its error, when it rejects. */
66
203
  async transaction<T>(callback: (transaction: SqliteExecutor) => Promise<T>): Promise<T> {
67
- const result = await this.#session.transaction(async (tx) => {
68
- const done = await callback(new Executor(tx));
69
- if (this.onCommit) await this.onCommit(tx);
70
- return done;
204
+ if (!this.#batching) {
205
+ const result = await this.#session.transaction(async (tx) => {
206
+ const done = await callback(new Executor(tx));
207
+ if (this.onCommit) await this.onCommit(tx);
208
+ return done;
209
+ });
210
+ if (this.afterCommit) await this.afterCommit();
211
+ return result;
212
+ }
213
+ this.#refuseInside();
214
+ const after = this.afterCommit;
215
+ const { result, batched } = await this.#run(async () => {
216
+ if (!this.#writesBatched()) return { result: await this.#commitAlone(callback), batched: false };
217
+ return { result: await this.#savepoint(callback, after), batched: true };
71
218
  });
72
- if (this.afterCommit) await this.afterCommit();
219
+ // Outside the chain: it may publish, which flushes.
220
+ if (!batched && after) await after();
73
221
  return result;
74
222
  }
75
223
 
224
+ override exec(sql: string) {
225
+ return this.#batching ? this.#write((e) => e.exec(sql)) : super.exec(sql);
226
+ }
227
+
228
+ override run(sql: string, ...params: SqliteValue[]) {
229
+ return this.#batching ? this.#write((e) => e.run(sql, ...params)) : super.run(sql, ...params);
230
+ }
231
+
76
232
  /**
77
233
  * Outside a transaction, the statement and its count are one: another
78
234
  * statement between them would be what `changes()` counted.
79
235
  */
80
236
  override runCounted(sql: string, ...params: SqliteValue[]): Promise<number> {
81
- return this.#session.transaction((tx) => new Executor(tx).runCounted(sql, ...params));
237
+ if (!this.#batching) return this.#session.transaction((tx) => new Executor(tx).runCounted(sql, ...params));
238
+ return this.#write((e) => e.runCounted(sql, ...params), true);
239
+ }
240
+
241
+ override get<T extends object>(sql: string, ...params: SqliteValue[]): Promise<T | undefined> {
242
+ return this.#batching ? this.#read((e) => e.get<T>(sql, ...params)) : super.get<T>(sql, ...params);
243
+ }
244
+
245
+ override all<T extends object>(sql: string, ...params: SqliteValue[]): Promise<T[]> {
246
+ return this.#batching ? this.#read((e) => e.all<T>(sql, ...params)) : super.all<T>(sql, ...params);
247
+ }
248
+
249
+ /**
250
+ * Writes what the batch holds (a prompt's end has written it already: a batch left now is one of a run that
251
+ * was abandoned as the attempt ended or failed), without failing: the error the attempt ends with is the
252
+ * attempt's, not this write's, which is told to the attempt and refused to every later call. The session is
253
+ * the caller's to end, after the calls made before.
254
+ */
255
+ async close() {
256
+ await this.flush().catch(() => {});
82
257
  }
83
258
 
84
- /** The session is the caller's to end, after the calls made before. */
85
- async close() {}
259
+ /** Whether the next write joins the batch: armed, and no effect in flight. */
260
+ #writesBatched(): boolean {
261
+ return this.#armed && this.#effects === 0;
262
+ }
263
+
264
+ #refuseInside() {
265
+ if (this.#inside.getStore()) throw new Error(REFUSED);
266
+ }
267
+
268
+ /** `call`, once the calls before it have ended, unless a batch failed. */
269
+ #run<T>(call: () => Promise<T>): Promise<T> {
270
+ const result = this.#chain.then(() => {
271
+ if (this.#failure) {
272
+ this.#tell();
273
+ throw this.#failure.error;
274
+ }
275
+ return call();
276
+ });
277
+ this.#chain = result.catch(() => {});
278
+ return result;
279
+ }
280
+
281
+ /** A read: in the batch if one is open (it sees its writes), else on the session, which opens nothing. */
282
+ #read<T>(read: (executor: Executor) => Promise<T>): Promise<T> {
283
+ this.#refuseInside();
284
+ return this.#run(() => read(new Executor(this.#batch ? this.#batch.batch.tx : this.#session)));
285
+ }
286
+
287
+ /** A write outside a transaction: in the batch if batched, else a transaction of its own. */
288
+ #write<T>(write: (executor: Executor) => Promise<T>, counted = false): Promise<T> {
289
+ this.#refuseInside();
290
+ return this.#run(async () => {
291
+ if (this.#writesBatched()) {
292
+ const batch = await this.#opened();
293
+ const result = await write(new Executor(batch.tx));
294
+ this.#batch!.acknowledged = true;
295
+ return result;
296
+ }
297
+ await this.#closeBatch();
298
+ // `runCounted` is a transaction of its own, as ever; the others are one statement.
299
+ return counted ? this.#session.transaction((tx) => write(new Executor(tx))) : write(new Executor(this.#session));
300
+ });
301
+ }
302
+
303
+ /** One pi transaction that is a transaction of the session: not batched, with its `onCommit` in it. */
304
+ async #commitAlone<T>(callback: (transaction: SqliteExecutor) => Promise<T>): Promise<T> {
305
+ await this.#closeBatch();
306
+ return this.#session.transaction((tx) =>
307
+ this.#inside.run(true, async () => {
308
+ const done = await callback(new Executor(tx));
309
+ if (this.onCommit) await this.onCommit(tx);
310
+ return done;
311
+ }),
312
+ );
313
+ }
314
+
315
+ /**
316
+ * One pi transaction in the batch, as a savepoint: released when it
317
+ * succeeds, rolled back (and released) when it fails, so that a failed
318
+ * one undoes only itself. Its `afterCommit` waits for the batch's commit.
319
+ */
320
+ async #savepoint<T>(
321
+ callback: (transaction: SqliteExecutor) => Promise<T>,
322
+ after: (() => Promise<void>) | undefined,
323
+ ): Promise<T> {
324
+ const { tx, run } = await this.#opened();
325
+ const held = this.#batch!;
326
+ // The savepoint goes with the first statement of the commit, and the release that ended the one before it
327
+ // (queued below), in the same crossing, in order. A session that cannot defer runs it at once.
328
+ const deferred = deferSql(tx, SAVEPOINT);
329
+ if (!deferred) await tx.execute(SAVEPOINT);
330
+ // Whether this commit sent something. A send is recorded on the held transaction, and its real commit
331
+ // makes it whatever a savepoint did: rolling the savepoint back does not take it back. So a commit that
332
+ // sent and then failed cannot be undone alone; the whole batch is (below).
333
+ let sent = false;
334
+ let result: T;
335
+ try {
336
+ // In the async context of the batch's body, so that a call to `ctx.db` from the callback is refused
337
+ // at once, as it is in a transaction of the session, and not left to wait for the batch.
338
+ result = await run(() =>
339
+ this.#inside.run(true, async () => {
340
+ const done = await callback(new Executor(tx));
341
+ if (this.onCommit) await this.onCommit(noting(tx, () => (sent = true)));
342
+ return done;
343
+ }),
344
+ );
345
+ // A savepoint still queued had no statement run in it: with nothing to undo, it and its release are
346
+ // no-ops, and neither is run. Otherwise the release rides with the next statement of the batch, or goes
347
+ // with the batch's end (see `#closeBatch`).
348
+ if (!deferred) await tx.execute(RELEASE);
349
+ else if (!undeferSql(tx, SAVEPOINT) && !deferSql(tx, RELEASE)) await tx.execute(RELEASE);
350
+ } catch (error) {
351
+ if (sent) {
352
+ await this.#abandon(held, error);
353
+ throw error;
354
+ }
355
+ try {
356
+ await tx.execute('ROLLBACK TO restate_pi');
357
+ await tx.execute(RELEASE);
358
+ } catch {
359
+ // The session failed too: the error of the commit is what the caller gets, and the next call fails.
360
+ }
361
+ throw error;
362
+ }
363
+ held.acknowledged = true;
364
+ if (after) this.#after.push(after);
365
+ return result;
366
+ }
367
+
368
+ /**
369
+ * Drop the batch with `error`: its body throws, the session rolls the whole transaction back, and its sends
370
+ * are never made. If the commits in it were told to pi as done, they are lost, as with a failed write.
371
+ */
372
+ async #abandon(held: Held, error: unknown): Promise<void> {
373
+ this.#batch = undefined;
374
+ held.batch.abort(error);
375
+ await held.done.catch(() => {});
376
+ if (held.acknowledged) this.#fail(error);
377
+ }
378
+
379
+ /** The open batch, opened if there is none. */
380
+ async #opened(): Promise<Batch> {
381
+ if (this.#batch) return this.#batch.batch;
382
+ const opened = Promise.withResolvers<Batch>();
383
+ const released = Promise.withResolvers<void>();
384
+ const done = this.#session.transaction(async (tx) => {
385
+ opened.resolve({ tx, run: AsyncLocalStorage.snapshot(), release: released.resolve, abort: released.reject });
386
+ await released.promise;
387
+ });
388
+ // A failure before the body ran: the open itself.
389
+ done.catch((error: unknown) => opened.reject(error));
390
+ // A batch that could not be opened lost nothing: the call that asked for it fails, as one does without
391
+ // batching (a cancellation owed to the handler is delivered once, say), and the next one tries again.
392
+ const batch = await opened.promise;
393
+ const held: Held = { batch, done, acknowledged: false };
394
+ // Failing while it waits to be ended, with something told as done, is every later call's error.
395
+ done.catch((error: unknown) => (held.acknowledged ? this.#fail(error, false) : undefined));
396
+ this.#batch = held;
397
+ // Another call to the session queued behind it: end it, after the call of pi under way.
398
+ // A failure is the attempt's already (`#fail`): nobody waits for this flush.
399
+ void batch.tx.queued.then(() => (this.#batch === held ? this.flush().catch(() => {}) : undefined));
400
+ return batch;
401
+ }
402
+
403
+ /** End the batch, if one is open: its commit, which the calls after it wait for. */
404
+ async #closeBatch(): Promise<void> {
405
+ const held = this.#batch;
406
+ if (!held) return;
407
+ this.#batch = undefined;
408
+ // The release of the last commit's savepoint, if nothing ran after it, is not run: the commit ends every
409
+ // savepoint of its transaction.
410
+ undeferSql(held.batch.tx, RELEASE);
411
+ held.batch.release();
412
+ try {
413
+ await held.done;
414
+ } catch (error) {
415
+ // What was told to pi as done is lost; if nothing was, this fails as the commit it was would have.
416
+ if (!held.acknowledged) throw error;
417
+ this.#after = [];
418
+ throw this.#fail(error);
419
+ }
420
+ }
421
+
422
+ /**
423
+ * Run what the commits of the last batch asked to run after it, in order,
424
+ * after what an earlier flush is running: a flush that returns has had
425
+ * all of those done, so that effects that start together start after the
426
+ * publish that they all wait for, in the order they asked. A callback that
427
+ * flushes (a publish does) does not wait for itself.
428
+ */
429
+ #runAfter(): Promise<void> {
430
+ if (this.#inAfter.getStore()) return Promise.resolve();
431
+ const callbacks = this.#after.splice(0);
432
+ const run = this.#afterRun.then(() =>
433
+ this.#inAfter.run(true, async () => {
434
+ for (const after of callbacks) await after();
435
+ }),
436
+ );
437
+ this.#afterRun = run.catch(() => {});
438
+ return run;
439
+ }
440
+
441
+ /**
442
+ * A batch failed: the first error is every later call's, and the attempt is told once, unless `tell` is
443
+ * false: a failure that nobody has run into yet (the session closing as the attempt ends is one) is told
444
+ * when the next call meets it, not before, so that the error the attempt ends with is its own.
445
+ */
446
+ #fail(error: unknown, tell = true): unknown {
447
+ this.#failure ??= { error };
448
+ this.#after = [];
449
+ if (tell) this.#tell();
450
+ return this.#failure.error;
451
+ }
452
+
453
+ #tell() {
454
+ if (this.#told || !this.#failure) return;
455
+ this.#told = true;
456
+ this.#failed?.(this.#failure.error);
457
+ }
86
458
  }
87
459
 
88
460
  /** Open pi-durable storage on the session `db`, through `database`, its facade, if given (to set its `onCommit`). */
package/src/tools.ts CHANGED
@@ -110,12 +110,21 @@ export const text = (value: unknown) =>
110
110
  * a Restate call it makes fails with) is its answer, `Error: <message>`, for
111
111
  * the model to act on; and so are arguments that do not fit `input`, which
112
112
  * `run` never sees.
113
+ *
114
+ * A tool does not keep its attempt alive: one that works for longer than
115
+ * Restate's inactivity timeout (a minute, by default) is cut off, and done
116
+ * again from the start of the turn, by every attempt. One that must work
117
+ * that long sets `keepalive`, and runs in `ctx.working`; it keeps long waits
118
+ * on Restate (a call, a signal) out of its `run`, or holds its process for
119
+ * as long as they take.
113
120
  */
114
121
  export const tool = <S extends z.ZodObject>(options: {
115
122
  name: string;
116
123
  description: string;
117
124
  input: S;
118
125
  run: (input: z.infer<S>, context: ToolContext) => unknown;
126
+ /** Keep the attempt alive while `run` runs: see {@link tool}. */
127
+ keepalive?: boolean;
119
128
  }): Tool => withSpec(ownTool(options), { kind: 'run', run: options.run });
120
129
 
121
130
  /** {@link tool}, without its spec: Restate's tools give their own. */
@@ -124,6 +133,7 @@ const ownTool = <S extends z.ZodObject>(options: {
124
133
  description: string;
125
134
  input: S;
126
135
  run: (input: z.infer<S>, context: ToolContext) => unknown;
136
+ keepalive?: boolean;
127
137
  }): Tool => ({
128
138
  [TOOL]: true,
129
139
  name: options.name,
@@ -136,7 +146,8 @@ const ownTool = <S extends z.ZodObject>(options: {
136
146
  if (!parsed.success) return `Error: the arguments do not fit the tool's input: ${z.prettifyError(parsed.error)}`;
137
147
  const input = parsed.data;
138
148
  try {
139
- return text(await options.run(input, { ctx, callId, idempotencyKey: `${ctx.request.id}:${callId}` }));
149
+ const run = () => options.run(input, { ctx, callId, idempotencyKey: `${ctx.request.id}:${callId}` });
150
+ return text(await (options.keepalive ? ctx.working(run) : run()));
140
151
  } catch (error) {
141
152
  // The turn stopped (its invocation was cancelled, or its attempt
142
153
  // ended): it ends, rather than the model going on with the tool's error