@restatedev/agents 0.10.3 → 0.11.1

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 (84) 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 +29 -8
  5. package/dist/calls.d.ts.map +1 -1
  6. package/dist/calls.js +63 -19
  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 +34 -1
  14. package/dist/common.js.map +1 -1
  15. package/dist/deepseek/barriers.d.ts +11 -0
  16. package/dist/deepseek/barriers.d.ts.map +1 -0
  17. package/dist/deepseek/barriers.js +36 -0
  18. package/dist/deepseek/barriers.js.map +1 -0
  19. package/dist/deepseek/index.d.ts.map +1 -1
  20. package/dist/deepseek/index.js +52 -17
  21. package/dist/deepseek/index.js.map +1 -1
  22. package/dist/deepseek/persistence.d.ts +16 -0
  23. package/dist/deepseek/persistence.d.ts.map +1 -1
  24. package/dist/deepseek/persistence.js +33 -1
  25. package/dist/deepseek/persistence.js.map +1 -1
  26. package/dist/langgraph/checkpointer.d.ts +8 -1
  27. package/dist/langgraph/checkpointer.d.ts.map +1 -1
  28. package/dist/langgraph/checkpointer.js +117 -31
  29. package/dist/langgraph/checkpointer.js.map +1 -1
  30. package/dist/langgraph/graph.d.ts.map +1 -1
  31. package/dist/langgraph/graph.js +15 -2
  32. package/dist/langgraph/graph.js.map +1 -1
  33. package/dist/langgraph/index.d.ts.map +1 -1
  34. package/dist/langgraph/index.js +2 -2
  35. package/dist/langgraph/index.js.map +1 -1
  36. package/dist/langgraph/keepalive.d.ts +16 -0
  37. package/dist/langgraph/keepalive.d.ts.map +1 -0
  38. package/dist/langgraph/keepalive.js +51 -0
  39. package/dist/langgraph/keepalive.js.map +1 -0
  40. package/dist/opencode/index.d.ts.map +1 -1
  41. package/dist/opencode/index.js +129 -25
  42. package/dist/opencode/index.js.map +1 -1
  43. package/dist/pi/commits.d.ts +6 -0
  44. package/dist/pi/commits.d.ts.map +1 -0
  45. package/dist/pi/commits.js +3 -0
  46. package/dist/pi/commits.js.map +1 -0
  47. package/dist/pi/index.d.ts +14 -1
  48. package/dist/pi/index.d.ts.map +1 -1
  49. package/dist/pi/index.js +91 -9
  50. package/dist/pi/index.js.map +1 -1
  51. package/dist/pi/keepalive.d.ts +21 -0
  52. package/dist/pi/keepalive.d.ts.map +1 -0
  53. package/dist/pi/keepalive.js +98 -0
  54. package/dist/pi/keepalive.js.map +1 -0
  55. package/dist/pi/storage.d.ts +62 -3
  56. package/dist/pi/storage.d.ts.map +1 -1
  57. package/dist/pi/storage.js +355 -12
  58. package/dist/pi/storage.js.map +1 -1
  59. package/dist/tools.d.ts +9 -0
  60. package/dist/tools.d.ts.map +1 -1
  61. package/dist/tools.js +9 -1
  62. package/dist/tools.js.map +1 -1
  63. package/package.json +3 -3
  64. package/src/agentlib/tools.ts +2 -0
  65. package/src/calls.ts +86 -21
  66. package/src/claude/index.ts +36 -6
  67. package/src/common.ts +36 -1
  68. package/src/deepseek/README.md +24 -5
  69. package/src/deepseek/barriers.ts +63 -0
  70. package/src/deepseek/index.ts +55 -14
  71. package/src/deepseek/persistence.ts +47 -6
  72. package/src/langgraph/README.md +19 -0
  73. package/src/langgraph/checkpointer.ts +134 -35
  74. package/src/langgraph/graph.ts +14 -2
  75. package/src/langgraph/index.ts +3 -3
  76. package/src/langgraph/keepalive.ts +58 -0
  77. package/src/opencode/README.md +15 -0
  78. package/src/opencode/index.ts +124 -23
  79. package/src/pi/README.md +64 -15
  80. package/src/pi/commits.ts +7 -0
  81. package/src/pi/index.ts +116 -7
  82. package/src/pi/keepalive.ts +121 -0
  83. package/src/pi/storage.ts +382 -10
  84. package/src/tools.ts +12 -1
package/src/calls.ts CHANGED
@@ -19,6 +19,18 @@
19
19
  // terminal error is its result too. Once stored, the model has its result,
20
20
  // and an identical call it makes later is a call of its own.
21
21
  //
22
+ // Only the record of a new call commits of its own, before the call is made.
23
+ // That a call answered rides a commit that is under way or starts at once
24
+ // ({@link rideCommit}): the one that stores the call's result, so that the
25
+ // transcript never has a result of a call that is not recorded as answered;
26
+ // if none does (a slow tool of the round is still running, another call
27
+ // waits), it is written on its own at the end of that macrotask, so it is
28
+ // never left unrecorded for long. That its record is forgotten rides the next
29
+ // commit, whenever it comes. A crash in the few moments before an answer is
30
+ // written reads the call as one that did not answer, as a crash just before
31
+ // a commit of its own would have: made again, under the same key, and cut off
32
+ // for a stopped turn that another invocation closes.
33
+ //
22
34
  // A framework's own wait ({@link waitFor} of tools.ts) is its tool call's
23
35
  // alone: the framework stored its tool call before it waits, so a retried
24
36
  // attempt waits again under the same id, and a new call with the same input
@@ -26,7 +38,7 @@
26
38
  // a tool call waited for is not the call: a stopped turn does not report the
27
39
  // call as done because its approval returned ({@link outcomes}).
28
40
  import type * as restate from '@restatedev/sessions';
29
- import { Schema, ScopeKey } from '@restatedev/sessions/internal';
41
+ import { flushRiders, rideCommit, Schema, ScopeKey } from '@restatedev/sessions/internal';
30
42
  import { randomUUID } from 'node:crypto';
31
43
 
32
44
  /** A tool's call: the tool, its input as JSON, the ids it was made with (the first is its own), and the attempt that last made it. */
@@ -69,37 +81,74 @@ export const SCHEMA = new Schema('restate-agents.calls', [
69
81
  /** What the calls need of a handler's context. */
70
82
  type CallsContext = Pick<restate.SessionContext, 'db' | 'request'>;
71
83
 
72
- /** What writes the rows the conversation of the attempt's turn holds back, by its context. */
73
- const HELD = new ScopeKey<() => Promise<void>>('the held rows of the conversation');
84
+ /** What writes what is held back before anything visible, by holder: the conversation's rows, pi's batch of commits. */
85
+ const HELD = new ScopeKey<Map<string, () => Promise<void>>>('what the attempt holds back');
74
86
 
75
87
  /**
76
- * Have {@link flushHeld} write, with `flush`, the rows that the conversation
77
- * of the attempt's turn holds back (`Conversation.hold`): `answerOnce` does.
88
+ * Have {@link flushHeld} write, with `flush`, what a holder keeps back: by
89
+ * default the rows that the conversation of the attempt's turn holds back
90
+ * (`Conversation.hold`), which `answerOnce` sets. A holder of another `slot`
91
+ * (pi's storage, which holds its commits until an effect starts) coexists
92
+ * with it; one of the same slot replaces it, and without a `flush` the slot
93
+ * is released.
78
94
  */
79
- export const holding = (ctx: restate.SessionContext, flush: () => Promise<void>) => HELD.set(ctx, flush);
95
+ export const holding = (
96
+ ctx: restate.SessionContext,
97
+ flush: (() => Promise<void>) | undefined,
98
+ slot = 'conversation',
99
+ ) => {
100
+ const held = HELD.of(ctx, () => new Map());
101
+ if (flush) held.set(slot, flush);
102
+ else held.delete(slot);
103
+ };
80
104
 
81
105
  /**
82
- * Write the rows that the conversation of the attempt's turn holds back, if
83
- * any (see `Conversation.hold`). Call it before what another party sees, or
84
- * what outlives the attempt: a publish, a Restate call, send or wait. A held
85
- * row is lost in a crash, and the retried attempt makes it again; what was
86
- * seen or called must not depend on it.
106
+ * Write what the holders keep back, in the order they were set, one after
107
+ * the other: the rows that the conversation of the attempt's turn holds back,
108
+ * if any (see `Conversation.hold`), and pi's batched commits. Call it before
109
+ * what another party sees, or what outlives the attempt: a publish, a
110
+ * Restate call, send or wait. What is held is lost in a crash, and the
111
+ * retried attempt makes it again; what was seen or called must not depend
112
+ * on it.
87
113
  */
88
114
  export async function flushHeld(ctx: restate.SessionContext) {
89
- await HELD.get(ctx)?.();
115
+ for (const flush of HELD.get(ctx)?.values() ?? []) await flush();
90
116
  }
91
117
 
118
+ const UPSERT = 'INSERT OR REPLACE INTO restate_agent_calls (row, invocation, calls) VALUES (0, ?, ?)';
119
+
120
+ /** The slot of the calls' write that rides the next commit ({@link ride}). */
121
+ const RIDER = 'restate-agents.calls';
122
+
92
123
  /**
93
124
  * Store `calls`, committed before the call they record is made. The rows the
94
125
  * conversation holds back are written first: the call outlives the attempt,
95
- * and what led to it must too.
126
+ * and what led to it must too. It is the whole row: what rides the next
127
+ * commit is written, and no longer pending.
96
128
  */
97
129
  async function store(ctx: restate.SessionContext, { invocation, calls }: Calls) {
98
130
  await flushHeld(ctx);
99
- await ctx.db.execute('INSERT OR REPLACE INTO restate_agent_calls (row, invocation, calls) VALUES (0, ?, ?)', [
100
- invocation,
101
- JSON.stringify(calls),
102
- ]);
131
+ rideCommit(ctx.db, RIDER, undefined);
132
+ await ctx.db.execute(UPSERT, [invocation, JSON.stringify(calls)]);
133
+ }
134
+
135
+ /**
136
+ * Store `state` with the next commit of the database, rather than commit it
137
+ * (see the top of this file), as it is then: a later change replaces it, and
138
+ * the latest state is written. An `urgent` one (an answer) is written on its
139
+ * own unless a commit is under way to write it; one pending that is urgent
140
+ * stays so. A database that cannot ride (a view's) commits it at once.
141
+ */
142
+ async function ride(ctx: restate.SessionContext, state: Calls, urgent = false) {
143
+ const written = rideCommit(
144
+ ctx.db,
145
+ RIDER,
146
+ (tx) => tx.execute(UPSERT, [state.invocation, JSON.stringify(state.calls)]),
147
+ {
148
+ urgent,
149
+ },
150
+ );
151
+ if (!written) await store(ctx, state);
103
152
  }
104
153
 
105
154
  /** The calls of `invocation`, as stored: none if the row is another invocation's. */
@@ -122,7 +171,7 @@ const ATTEMPT = new ScopeKey<{ id: string; calls?: Promise<Calls> }>('the calls
122
171
  * cancelled, say) is not kept: the next asks again, so that a stopped turn's
123
172
  * close reads the calls as stored, rather than fail on the load it found.
124
173
  */
125
- function attemptOf(ctx: restate.SessionContext): { id: string; calls: Promise<Calls> } {
174
+ function attemptOf(ctx: restate.SessionContext) {
126
175
  const attempt = ATTEMPT.of(ctx, () => ({ id: randomUUID() }));
127
176
  if (attempt.calls === undefined) {
128
177
  const calls = load(ctx, ctx.request.id);
@@ -131,7 +180,7 @@ function attemptOf(ctx: restate.SessionContext): { id: string; calls: Promise<Ca
131
180
  if (attempt.calls === calls) attempt.calls = undefined;
132
181
  });
133
182
  }
134
- return attempt as { id: string; calls: Promise<Calls> };
183
+ return attempt as typeof attempt & { calls: Promise<Calls> };
135
184
  }
136
185
 
137
186
  /** `value` as JSON with its objects' keys sorted: the same input, however its keys came, is the same call. */
@@ -206,11 +255,21 @@ export async function callOf(
206
255
  /**
207
256
  * It answered, with `failed` if a terminal error answered it: kept until
208
257
  * the transcript has its result.
258
+ *
259
+ * It rides a commit that is under way (the one that stores the call's
260
+ * result, when the framework's write has started), and is otherwise
261
+ * written on its own at once ({@link ride}): a call that answered must
262
+ * not stay unrecorded while something else runs (a slow tool of the same
263
+ * round, a call that waits for a signal). A crash before it is written
264
+ * reads the call as one that did not answer, as a crash just before a
265
+ * commit of its own would have: made again under the same key, and cut off
266
+ * for a stopped turn that another invocation closes ({@link outcomes} reads
267
+ * the stored row; the attempt's own turn reads its state).
209
268
  */
210
269
  async answered(failed?: string) {
211
270
  made.done = true;
212
271
  if (failed !== undefined) made.failed = failed;
213
- await store(ctx, state);
272
+ await ride(ctx, state, true);
214
273
  },
215
274
  };
216
275
  }
@@ -229,7 +288,7 @@ export async function settleCalls(ctx: restate.SessionContext, stored: (id: stri
229
288
  const kept = state.calls.filter((c) => !c.done || !stored(c.ids.at(-1)!, c.failed));
230
289
  if (kept.length === state.calls.length) return;
231
290
  state.calls = kept;
232
- await store(ctx, state);
291
+ await ride(ctx, state);
233
292
  }
234
293
 
235
294
  /**
@@ -263,3 +322,9 @@ export async function outcomes(
263
322
  }
264
323
  return found;
265
324
  }
325
+
326
+ /**
327
+ * Write what rides the next commit ({@link ride}) now, if it is pending: at
328
+ * the end of a turn, when no commit follows that would.
329
+ */
330
+ export const flushCalls = (ctx: restate.SessionContext) => flushRiders(ctx.db);
@@ -43,6 +43,7 @@ import {
43
43
  type Configure,
44
44
  configured,
45
45
  fromTool,
46
+ keepAlive,
46
47
  modelIdOf,
47
48
  modelOf,
48
49
  RETURNED_UNRECORDED,
@@ -245,7 +246,7 @@ const runOf =
245
246
  await step();
246
247
  }
247
248
  let paused = false;
248
- for await (const message of runner) {
249
+ for await (const message of requests(ctx, runner)) {
249
250
  // A reply that cannot go on ends the turn, whose tool calls do not run.
250
251
  const stopped = stoppedShort(message, maxTokens);
251
252
  if (stopped) throw new restate.TerminalError(stopped);
@@ -274,6 +275,33 @@ const runOf =
274
275
  }
275
276
  };
276
277
 
278
+ /**
279
+ * `runner`'s replies, each model request kept alive: from the moment the
280
+ * loop asks for the next reply until it arrives (the runner does not stream,
281
+ * so the reply is the whole response), however it ends: an error, or the turn
282
+ * stopped. The tools run outside it: the loop runs them (`generateToolResponse`)
283
+ * before it asks again, and the runner then finds their results done.
284
+ */
285
+ async function* requests<T>(ctx: restate.SessionContext, runner: AsyncIterable<T>): AsyncGenerator<T> {
286
+ const replies = runner[Symbol.asyncIterator]();
287
+ try {
288
+ for (;;) {
289
+ const release = keepAlive(ctx);
290
+ let next: IteratorResult<T>;
291
+ try {
292
+ next = await replies.next();
293
+ } finally {
294
+ release();
295
+ }
296
+ if (next.done) return;
297
+ yield next.value;
298
+ }
299
+ } finally {
300
+ // Ends the runner's loop (its span and its stream) when the caller leaves it early, as a final reply does.
301
+ await replies.return?.();
302
+ }
303
+ }
304
+
277
305
  /**
278
306
  * Why the model's `message` stopped short of a reply to go on from: cut off
279
307
  * at `maxTokens` (its text, or a tool call's input, unfinished), declined, or
@@ -425,11 +453,13 @@ export const summarizer =
425
453
  (options: Options = {}): Summarize =>
426
454
  async (ctx, request) => {
427
455
  const { client, model, maxTokens } = agentOf(ctx, { ...options, tools: [] });
428
- const message = await client.beta.messages.create({
429
- model,
430
- max_tokens: maxTokens,
431
- messages: [{ role: 'user', content: request }],
432
- });
456
+ const message = await ctx.working(() =>
457
+ client.beta.messages.create({
458
+ model,
459
+ max_tokens: maxTokens,
460
+ messages: [{ role: 'user', content: request }],
461
+ }),
462
+ );
433
463
  return textOf(message.content);
434
464
  };
435
465
 
package/src/common.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  // budget.
6
6
  import * as restate from '@restatedev/sessions';
7
7
  import { cancelCalls, cancelled, definitionOf, Link, ScopeKey } from '@restatedev/sessions/internal';
8
- import { flushHeld, settleCalls } from './calls.ts';
8
+ import { flushCalls, flushHeld, settleCalls } from './calls.ts';
9
9
  import { companionHere, type Published, type Steer } from './companion.ts';
10
10
 
11
11
  /**
@@ -259,6 +259,38 @@ export class AttemptEnded extends Error {
259
259
  */
260
260
  export const stopSignalOf = (ctx: restate.SessionContext): AbortSignal | undefined => TURN.get(ctx);
261
261
 
262
+ // --- Keeping an attempt alive
263
+ //
264
+ // A model's request runs in `ctx.working`, so that Restate does not shut its
265
+ // attempt down while it streams: the request would be made again, from the
266
+ // start of the turn. Nothing else of a turn does, unless a tool says so
267
+ // (`keepalive`): a wait on Restate (a call, a signal) suspends.
268
+
269
+ /**
270
+ * Open a `ctx.working` scope until the function it returns is called (once
271
+ * or more): for a framework's hooks that bracket a model's request without
272
+ * wrapping it. A scope never released keeps the attempt alive to its end.
273
+ */
274
+ export function keepAlive(ctx: restate.SessionContext): () => void {
275
+ const released = Promise.withResolvers<void>();
276
+ void ctx.working(() => released.promise);
277
+ return () => released.resolve();
278
+ }
279
+
280
+ /**
281
+ * `source`, kept alive while it is iterated: from the first pull to its end,
282
+ * however it ends (done, thrown, or returned early, as a `break` does). A
283
+ * model's streamed response, say.
284
+ */
285
+ export async function* keptAlive<T>(ctx: restate.SessionContext, source: AsyncIterable<T>): AsyncGenerator<T> {
286
+ const release = keepAlive(ctx);
287
+ try {
288
+ yield* source;
289
+ } finally {
290
+ release();
291
+ }
292
+ }
293
+
262
294
  /**
263
295
  * An agent's settings: whether it runs in the background (`background:
264
296
  * true`: no one follows it as it works), and, for an agent on the
@@ -455,6 +487,9 @@ export async function answering<T>(ctx: restate.SessionContext, stored: Stored,
455
487
  } finally {
456
488
  if (outer) ANSWERING.set(ctx, outer);
457
489
  else ANSWERING.delete(ctx);
490
+ // What rides the next commit is written if none is to come: after a turn that answered, the commit that
491
+ // stored its answer wrote it, and this does nothing. A failed attempt's own error is not this write's.
492
+ await (failed ? flushCalls(ctx).catch(() => {}) : flushCalls(ctx));
458
493
  }
459
494
  }
460
495
  }
@@ -107,15 +107,29 @@ cancelled: its approval is not its outcome.
107
107
 
108
108
  The persistence ([`persistence.ts`](persistence.ts),
109
109
  `SqlSessionPersistence`) keeps each session's header, and its event log, one
110
- row per event; a flush, the harness's durability barrier, stores what was
111
- appended before it in one SQL transaction. The handler is not replayed: a
110
+ row per event; a write stores what was appended before it in one SQL
111
+ transaction. The harness's flushes, its durability barrier, are soft here:
112
+ the adapter does the writing, right before each effect (below). The handler is not replayed: a
112
113
  retried attempt boots the harness again and resumes the session from the
113
114
  stored log. The harness does not resume an interrupted turn: resuming closes
114
115
  it, and leaves the model to decide what to do about it. So:
115
116
 
116
117
  - **A tool runs only once its call is stored.** The harness's checkpoint
117
118
  policy flushes the session before each model request, each tool body and
118
- each step.
119
+ each step, but those flushes store nothing once the adapter's own barriers
120
+ are in place ([`barriers.ts`](barriers.ts)). The adapter stores everything
121
+ queued right before each model request (the innermost listener of the
122
+ harness's `llm/stream`, checked to be the last on each request) and each
123
+ tool body (the wrapper of each tool it registers), before each Restate
124
+ effect and publish, and when the run ends, and it does not start the
125
+ request or the body if the write fails. So a flush at a step and the one
126
+ before its request are one commit: a turn of 4 model requests and 3 tool
127
+ calls commits the ask, one write before each effect, the final flush and
128
+ the answer. If a barrier cannot be installed, every flush stays a write.
129
+ A crash loses what was queued since the last write, which nothing has
130
+ acted on; the tool's result of a body that ran is then unknown to the retry,
131
+ as below. The wait for an approval is the exception: it opens with the
132
+ tool call not stored, as before.
119
133
  - **A tool call stored without a result has an unknown outcome.** Resuming
120
134
  gives each such call an error result that says so, and tells the model to
121
135
  retry only an idempotent operation; the handler then asks the agent to
@@ -145,8 +159,8 @@ transaction: what `messages` shows
145
159
  reply with tool calls, or tools' results, is published once it is stored,
146
160
  in a `chat` turn (a `prompt()` in a handler of your own publishes nothing),
147
161
  and nothing else is: a tool call's start publishes nothing. The tools of a
148
- reply run one after another, and each result is flushed with the next call,
149
- before its tool runs (the checkpoint policy's barrier): one commit, and one
162
+ reply run one after another, and each result is written with the next call,
163
+ before its tool runs (the adapter's barrier): one commit, and one
150
164
  publish, per tool call. The harness's input
151
165
  stays within the model's context window: as it nears the window (or
152
166
  overflows it), the harness condenses the oldest history into a summary, one
@@ -177,6 +191,11 @@ which makes a fresh tool call id for every call, as a model does
177
191
  through a crash, at any state request, and cancelled); and
178
192
  `messages`. Without the checkpoint policy four of its tests fail, and with
179
193
  a transfer tool that ignores `retryOf` three do.
194
+ - [`test/deepseek-commits.test.ts`](../../test/deepseek-commits.test.ts) and
195
+ [`test/deepseek-barriers.test.ts`](../../test/deepseek-barriers.test.ts):
196
+ the commits of a turn, what is stored before each effect, a follower's
197
+ publishes, a turn that condenses, a crash before a result is written, and
198
+ the barriers (and a turn without them).
180
199
  - [`test/deepseek.ts`](../../test/deepseek.ts): the
181
200
  bank agent, whose `transfer` uses `retryOf`, or its own call id, as the
182
201
  transfer id, through crashes in [the crash test](../../../e2e/crash.ts)
@@ -0,0 +1,63 @@
1
+ // The adapter's own barriers before the harness's effects. The session
2
+ // checkpoint policy flushes before each model request and each tool body, but
3
+ // those flushes are soft (persistence.ts): what the adapter stores, it stores
4
+ // itself, right before the effect starts, so that nothing the harness or a
5
+ // plugin does can come between the write and the effect.
6
+ //
7
+ // A tool's body is wrapped where the adapter registers the tool (`tracked` of
8
+ // index.ts: its `execute` is the last thing before the body, for a nested call
9
+ // too). The model's request has no such place, as the model adapter is a
10
+ // plugin's: the barrier is the innermost `llm/stream` listener, run right
11
+ // before the adapter's stream starts. Listeners run outermost first, and the
12
+ // one registered last is the innermost: so each request checks that the
13
+ // barrier is still the last registered, and fails the request if a listener
14
+ // was added after it.
15
+ import type { Context } from '@deepseek-ai/cordis';
16
+ import type { SessionId } from '@deepseek-ai/dsh-session';
17
+ import type { StreamChunk } from '@deepseek-ai/dsh-llm';
18
+ import type { SqlSessionPersistence } from './persistence.ts';
19
+
20
+ /** What the event service keeps of a listener (cordis's `Hook`): the barrier's is marked. */
21
+ interface Hook {
22
+ barrier?: symbol;
23
+ }
24
+
25
+ /** The mark of the barrier's listener. */
26
+ const BARRIER = Symbol('the adapter barrier before a model request');
27
+
28
+ /** The `llm/stream` listeners, in the order they run: outermost first, `undefined` if the harness does not keep them so. */
29
+ const listeners = (harness: Context): Hook[] | undefined => {
30
+ const hooks = Reflect.get(harness.events, '_hooks') as Record<string, unknown> | undefined;
31
+ const found = hooks?.['llm/stream'];
32
+ return Array.isArray(found) ? (found as Hook[]) : undefined;
33
+ };
34
+
35
+ /** Whether the barrier is the innermost `llm/stream` listener. */
36
+ const innermost = (harness: Context) => listeners(harness)?.at(-1)?.barrier === BARRIER;
37
+
38
+ /**
39
+ * Store the events of each model request's session right before its stream
40
+ * starts, as the innermost `llm/stream` listener; a request is not made if
41
+ * they are not stored, nor if a listener came after the barrier. Returns
42
+ * whether the barrier is installed, and innermost: if not (the hooks are not
43
+ * where they were), it is removed and the harness's flushes must stay writes.
44
+ */
45
+ export function guardModelRequests(harness: Context, persistence: SqlSessionPersistence): boolean {
46
+ const dispose = harness.on(
47
+ 'llm/stream',
48
+ (options: { sessionId?: SessionId }, next: () => AsyncIterable<StreamChunk>): AsyncIterable<StreamChunk> => {
49
+ const { sessionId } = options;
50
+ if (sessionId === undefined) return next();
51
+ return (async function* () {
52
+ if (!innermost(harness)) throw new Error('deepseek: a listener of llm/stream runs after the barrier');
53
+ await persistence.writeNow(sessionId);
54
+ yield* next();
55
+ })();
56
+ },
57
+ { barrier: BARRIER } as never,
58
+ );
59
+ if (innermost(harness)) return true;
60
+ // Not where it must be: left in, it would fail every request, not leave the flushes writes.
61
+ dispose();
62
+ return false;
63
+ }
@@ -17,9 +17,13 @@
17
17
  //
18
18
  // The handler is not replayed: a retried attempt (a crash, a lost connection)
19
19
  // boots the harness again and resumes the session from the stored log.
20
- // - The harness's session checkpoint policy stores the log before each model
21
- // request and before each tool body: a tool runs only once its call is
22
- // stored.
20
+ // - The log is stored before each model request and before each tool body:
21
+ // a tool runs only once its call is stored. The harness's session
22
+ // checkpoint policy flushes there, but its flushes are soft (persistence.ts)
23
+ // once the adapter's own barriers are in place (barriers.ts): they store
24
+ // what the harness queued right before each of those effects, before each
25
+ // Restate effect and publish, and when the run ends. So back-to-back flushes
26
+ // with no effect between them are one commit.
23
27
  // - A crash leaves the turn open. Resuming closes it, and gives each tool
24
28
  // call that was stored without a result an error result saying its outcome
25
29
  // is unknown; the handler then asks the agent to continue. The model sees
@@ -69,6 +73,7 @@ import {
69
73
  configured,
70
74
  fromTool,
71
75
  inboxOf,
76
+ keptAlive,
72
77
  ModelError,
73
78
  modelOf,
74
79
  providerOf,
@@ -84,6 +89,9 @@ import { type Answer, withChecked } from '../output.ts';
84
89
  import { type Definition, sessionObject } from '../object.ts';
85
90
  import { type Approval, isTool, jsonSchemaOf, type Tool as AnyTool, waitFor } from '../tools.ts';
86
91
  import type { z } from 'zod';
92
+ import { AsyncLocalStorage } from 'node:async_hooks';
93
+ import { holding } from '../calls.ts';
94
+ import { guardModelRequests } from './barriers.ts';
87
95
  import { SqlSessionPersistence } from './persistence.ts';
88
96
 
89
97
  export { SqlSessionPersistence };
@@ -138,6 +146,7 @@ function routeOf(model: string): Route {
138
146
  * approval runs (see {@link approving}).
139
147
  */
140
148
  async function boot(
149
+ ctx: restate.SessionContext,
141
150
  db: restate.Database,
142
151
  route: Route,
143
152
  system?: string,
@@ -145,6 +154,10 @@ async function boot(
145
154
  approvals = false,
146
155
  ): Promise<Context> {
147
156
  const harness = new Context();
157
+ // Every model request (a turn's, a compaction's) runs kept alive, from its
158
+ // first pull to the stream's end however it ends. Tools and the approval's
159
+ // wait are not in it.
160
+ harness.on('llm/stream', (_options, next) => keptAlive(ctx, next()));
148
161
  await harness.plugin(LlmRuntime);
149
162
  await harness.plugin(SessionStore);
150
163
  await harness.plugin(SystemPrompt, system ? { personaPrefix: system } : {});
@@ -303,7 +316,8 @@ const decided = (value: unknown): ApprovalOutcome => (approves(value) ? 'allowed
303
316
  * person is asked once. The wait is an approval (`approval`): a stopped
304
317
  * turn does not report its call as done because it was approved. An error
305
318
  * of the wait fails the attempt (`fail`), and its ask never ends: the
306
- * harness does not go on without a decision.
319
+ * harness does not go on without a decision. The wait stores nothing queued
320
+ * (the call's reply), unlike other Restate effects (see `UNSTORED`).
307
321
  */
308
322
  function approving(agentCtx: Context, ctx: restate.SessionContext, approval: Approval, fail: (error: unknown) => void) {
309
323
  const needs = typeof approval === 'function' ? approval : ({ name }: { name: string }) => approval.includes(name);
@@ -323,8 +337,13 @@ function approving(agentCtx: Context, ctx: restate.SessionContext, approval: App
323
337
  try {
324
338
  // The calls whose results are stored are forgotten first: an earlier
325
339
  // attempt's call with the same arguments, approved and done, is not this one.
326
- await toolCallStarted(ctx);
327
- return decided(await waitFor(ctx, callId, APPROVAL, call, { approval: true, rejoin: true }));
340
+ // Forgetting one is a write, which stores nothing queued either (`UNSTORED`).
341
+ return decided(
342
+ await UNSTORED.run(true, async () => {
343
+ await toolCallStarted(ctx);
344
+ return waitFor(ctx, callId, APPROVAL, call, { approval: true, rejoin: true });
345
+ }),
346
+ );
328
347
  } catch (error) {
329
348
  fromTool(ctx, error);
330
349
  fail(error);
@@ -333,6 +352,14 @@ function approving(agentCtx: Context, ctx: restate.SessionContext, approval: App
333
352
  });
334
353
  }
335
354
 
355
+ /**
356
+ * Where the writes before a Restate effect (`holding`) are not made: a publish
357
+ * right after a write (`flushed`), which has nothing more to show, and an
358
+ * approval's wait, whose tool call is not stored until the person decides (see
359
+ * {@link approving}).
360
+ */
361
+ const UNSTORED = new AsyncLocalStorage<true>();
362
+
336
363
  /** An agent's options: `chat` and `prompt` take them. */
337
364
  export interface Options<O extends z.ZodObject | undefined = z.ZodObject | undefined> {
338
365
  /**
@@ -491,7 +518,7 @@ const runOf =
491
518
  async (conversation) => {
492
519
  const turn = conversation.turn;
493
520
  const route = routeOf(modelOf(named, DEEPSEEK_MODEL));
494
- const harness = await boot(ctx.db, route, system, compaction, approval !== undefined);
521
+ const harness = await boot(ctx, ctx.db, route, system, compaction, approval !== undefined);
495
522
  const persistence = harness.sessionPersistence as SqlSessionPersistence;
496
523
  // A tool's error fails the attempt, which Restate retries: the harness
497
524
  // stores nothing more, so the retry finds the tool's call without a result.
@@ -508,6 +535,8 @@ const runOf =
508
535
  stop?.addEventListener('abort', onStop, { once: true });
509
536
  let agent: Agent | undefined;
510
537
  let unlisten: (() => void) | undefined;
538
+ // Whether the tools are registered behind a barrier (`tracked`), once `setup` has.
539
+ let toolsGuarded = false;
511
540
  // The turn asked again (its output's check, say): the harness is asked that, and answers it.
512
541
  const asked = turn.latestAsk();
513
542
  const again = asked !== turn.prompt;
@@ -516,10 +545,12 @@ const runOf =
516
545
  let from: number | undefined;
517
546
  try {
518
547
  const sessionId = SessionId(ctx.key);
548
+ const stored = () => persistence.writeNow(sessionId);
519
549
  const options = {
520
550
  agentOptions: route,
521
551
  setup: (agentCtx: Context) => {
522
- for (const t of tools) agentCtx.tools.register(tracked(isTool(t) ? native(t, ctx) : t, ctx, fail));
552
+ for (const t of tools) agentCtx.tools.register(tracked(isTool(t) ? native(t, ctx) : t, ctx, fail, stored));
553
+ toolsGuarded = true;
523
554
  if (approval !== undefined) approving(agentCtx, ctx, approval, fail);
524
555
  },
525
556
  };
@@ -528,6 +559,11 @@ const runOf =
528
559
  ? await harness.agents.resume({ resumeSessionId: sessionId, ...options })
529
560
  : await harness.agents.create({ sessionId, ...options });
530
561
  agent = started.agent;
562
+ // The harness's flushes are soft only with every barrier in place: the tools' (`tracked`), the model
563
+ // requests' (the innermost `llm/stream` listener), and what is stored before each Restate effect and
564
+ // publish (`holding`). Any one missing, they stay writes.
565
+ holding(ctx, async () => (UNSTORED.getStore() ? undefined : stored()), 'deepseek');
566
+ persistence.barriered = guardModelRequests(harness, persistence) && toolsGuarded;
531
567
  const found = agent.session.snapshotEvents().length;
532
568
  from = agent.session.snapshotEvents().find((e) => e.type === 'user/message' && e.data.id === id)?.seq;
533
569
  // A flush that copied steps (a reply with tool calls, tools' results) is published once it is stored,
@@ -557,7 +593,7 @@ const runOf =
557
593
  if (!copiedSteps) return;
558
594
  copiedSteps = false;
559
595
  // Failing, it fails the attempt, as a tool's error does: never the flush, which is done.
560
- await turn.stepsCommitted().catch(fail);
596
+ await UNSTORED.run(true, () => turn.stepsCommitted()).catch(fail);
561
597
  };
562
598
  // The messages steered to the turn, handed to the harness's step inbox as a publish lists them: only
563
599
  // once a reply with tool calls or a result is stored, so that a step after them places them, in this turn.
@@ -587,14 +623,15 @@ const runOf =
587
623
  const ask = again ? message(id, textOf(asked.item)) : promptOf(turn, before);
588
624
  agent.followup(end.asked ? message(`continue:${events.length}`, CONTINUE) : ask);
589
625
  await Promise.race([agent.whenIdle(), failed]);
590
- await harness.sessions.flush(agent.session);
626
+ await stored();
591
627
  }
592
628
  } catch (e) {
593
629
  // A cancelled invocation cancels the agent's turn, which the log keeps.
594
- if (e instanceof restate.CancelledError && agent) await cancelTurn(harness, agent);
630
+ if (e instanceof restate.CancelledError && agent) await cancelTurn(agent, persistence, SessionId(ctx.key));
595
631
  else persistence.abandon();
596
632
  throw e;
597
633
  } finally {
634
+ holding(ctx, undefined, 'deepseek');
598
635
  unlisten?.();
599
636
  stop?.removeEventListener('abort', onStop);
600
637
  await harness.fiber.dispose();
@@ -602,25 +639,29 @@ const runOf =
602
639
  };
603
640
 
604
641
  /** Cancel `agent`'s turn, and store it cancelled. */
605
- async function cancelTurn(harness: Context, agent: Agent) {
642
+ async function cancelTurn(agent: Agent, persistence: SqlSessionPersistence, sessionId: SessionId) {
606
643
  agent.cancel({ kind: 'user' });
607
644
  await agent.whenIdle();
608
- await harness.sessions.flush(agent.session);
645
+ await persistence.writeNow(sessionId);
609
646
  }
610
647
 
611
648
  /**
612
649
  * `definition`, the calls whose results are stored forgotten as each of its
613
650
  * calls starts (its call and its result are published once a flush stores
614
- * them, `runOf`); its error failing the attempt.
651
+ * them, `runOf`); its error failing the attempt. What the harness has queued
652
+ * is stored (`barrier`) before its body runs: the harness's flush before it is soft.
615
653
  */
616
654
  const tracked = (
617
655
  definition: ToolDefinition,
618
656
  ctx: restate.SessionContext,
619
657
  fail: (error: unknown) => void,
658
+ barrier: () => Promise<void>,
620
659
  ): ToolDefinition => ({
621
660
  ...definition,
622
661
  execute: async (args, exec) => {
623
662
  try {
663
+ // The last thing before the body, nested calls too: what is queued is stored, or the body does not run.
664
+ await barrier();
624
665
  await toolCallStarted(ctx);
625
666
  return await definition.execute(args, exec);
626
667
  } catch (error) {