@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
@@ -4,13 +4,21 @@
4
4
  //
5
5
  // The harness writes a session through a handle: `append` accepts a batch,
6
6
  // and `flush` is the durability barrier. Here an append is kept in memory and
7
- // a flush stores everything appended before it in one SQL transaction; a new
8
- // session's header is stored with its first flush, so a session that crashed
7
+ // a write stores everything appended before it in one SQL transaction; a new
8
+ // session's header is stored with its first write, so a session that crashed
9
9
  // before then never existed. The session checkpoint policy
10
10
  // (dsh-session-checkpoint-policy) flushes before each model request, before
11
- // each tool body, and before each step; so the events a tool's call follows
12
- // from are stored before the tool runs, and a crash loses only events that
13
- // nothing has acted on.
11
+ // each tool body, and before each step.
12
+ //
13
+ // A write is a commit to Restate, so the harness's flushes are soft once the
14
+ // adapter has put its own barriers in place (`barriered`, set by index.ts
15
+ // only when it has): a soft flush stores nothing and resolves, leaving the
16
+ // events queued. The adapter's barriers (`writeNow`) store everything queued
17
+ // right before each model request and each tool body, before each Restate
18
+ // effect and publish, and at the end of the run. So the events a tool's call
19
+ // follows from are stored before the tool runs, and a crash loses only
20
+ // events that nothing has acted on. Without the barriers every flush is a
21
+ // write.
14
22
  import type { Context } from '@deepseek-ai/cordis';
15
23
  import { SessionLogOffset, type SessionEvent, type SessionHeader, type SessionId } from '@deepseek-ai/dsh-session';
16
24
  import {
@@ -58,6 +66,12 @@ export class SqlSessionPersistence extends SessionPersistence {
58
66
  created = new Map<SessionId, Omit<Stored, 'count'>>();
59
67
  handles = new Set<SqlSessionHandle>();
60
68
  abandoned = false;
69
+ /**
70
+ * Whether the harness's flushes are soft: set by the code that installs the
71
+ * adapter's barriers (index.ts), once every one of them is in place. Unset,
72
+ * each flush stores what is queued.
73
+ */
74
+ barriered = false;
61
75
  /**
62
76
  * What each flush's events are copied into beside the log, in the flush's
63
77
  * transaction: the conversation of turns (index.ts), so that the copy and
@@ -74,7 +88,7 @@ export class SqlSessionPersistence extends SessionPersistence {
74
88
  // The live session's events go to its write handle; its flushes and its
75
89
  // disposal reach the handle too.
76
90
  ctx.on('session/event', (session, event) => this.writers.get(session.id)?.enqueue(event));
77
- ctx.on('session/flush', (session) => this.writers.get(session.id)?.flush());
91
+ ctx.on('session/flush', (session) => this.writers.get(session.id)?.harnessFlush());
78
92
  ctx.on('session/disposed', (session) => void this.writers.get(session.id)?.close());
79
93
  ctx.effect(
80
94
  () => async () => {
@@ -138,6 +152,11 @@ export class SqlSessionPersistence extends SessionPersistence {
138
152
  return handle;
139
153
  }
140
154
 
155
+ /** Store everything queued for session `id` now, or throw: the adapter's barrier before an effect (see the top). */
156
+ async writeNow(id: SessionId): Promise<void> {
157
+ await this.writers.get(id)?.writeNow();
158
+ }
159
+
141
160
  async flush(): Promise<void> {
142
161
  const results = await Promise.allSettled([...this.writers.values()].map((writer) => writer.flush()));
143
162
  const errors = results.flatMap((r) => (r.status === 'rejected' ? [r.reason] : []));
@@ -240,6 +259,28 @@ class SqlSessionHandle implements SessionHandle {
240
259
  this.#pending.push(...materializeAppendBatch([event]));
241
260
  }
242
261
 
262
+ /**
263
+ * The harness's flush (`session/flush`): a write, unless the adapter's
264
+ * barriers cover the effects (`barriered`), when the events stay queued for
265
+ * the next barrier.
266
+ */
267
+ harnessFlush(): Promise<void> {
268
+ if (!this.#store.barriered) return this.flush();
269
+ this.#check('flush');
270
+ if (this.access !== 'write') throw new SessionReadOnlyError(this.id, 'flush');
271
+ return Promise.resolve();
272
+ }
273
+
274
+ /** Store every event appended before the call, or throw if one is not stored. */
275
+ async writeNow(): Promise<void> {
276
+ const end = this.#end;
277
+ await this.flush();
278
+ // Events appended while it stored are for the next write; none before may be left.
279
+ if (this.#stored < end || this.#store.created.has(this.id)) {
280
+ throw new Error(`sql session persistence: the events of session ${this.id} are not stored`);
281
+ }
282
+ }
283
+
243
284
  /** Store every event appended so far, in one transaction. */
244
285
  flush(): Promise<void> {
245
286
  this.#check('flush');
@@ -106,6 +106,16 @@ graph })` gives it, and a handler of your own passes it as the run context
106
106
  `SqlCheckpointSaver(ctx.db)`). A node refuses to run without it, a
107
107
  checkpointer, or `durability: 'sync'`.
108
108
 
109
+ ## Kept alive
110
+
111
+ An attempt of a session object is shut down by Restate after its inactivity
112
+ timeout (a minute), and run again from the start, unless work keeps it alive
113
+ (`ctx.working`). Each request of a model does: the built-in graph's model
114
+ node, the summarizer's, and, in a graph of your own, every chat model's request
115
+ wherever the graph makes it (a node's, `createAgent`'s), through a callback
116
+ handler the agent passes in the run's config (so a graph of your own needs
117
+ nothing). A tool is not kept alive, unless it sets `keepalive`.
118
+
109
119
  ## Through crashes
110
120
 
111
121
  The built-in agent keeps no checkpoints: its conversation is the object's
@@ -141,6 +151,15 @@ writes in three tables; a step stores only the channels it changed. With
141
151
  ancestors a `DeltaChannel` is rebuilt from; by default it keeps them all,
142
152
  for LangGraph's history.
143
153
 
154
+ A task's pending writes are stored in the transaction of the checkpoint that
155
+ follows them, when that comes in the same macrotask (the step's last task has
156
+ just finished): a step is one commit. While other tasks of the step still run,
157
+ the writes of one that finished are stored on their own at the end of the
158
+ macrotask, so that it does not run again after a crash. A `putWrites` promise
159
+ resolves once its rows are stored (and fails with the error of the commit that
160
+ carried them), so a graph's `invoke` that returns has everything stored, as
161
+ LangGraph awaits them. Reads and `prune` store what is pending first.
162
+
144
163
  ## Run
145
164
 
146
165
  ```sh
@@ -17,9 +17,26 @@
17
17
  // a step's writes in. A write without a path (graph input, a `Command`)
18
18
  // comes first.
19
19
  //
20
- // Each `put` and `putWrites` is one SQL transaction, so a step is stored whole,
21
- // in order with everything else the handler does. Operations run one at a
22
- // time, in call order: LangGraph writes the results of parallel tasks at once.
20
+ // Each `put` is one SQL transaction, so a step is stored whole, in order with
21
+ // everything else the handler does. Operations run one at a time, in call
22
+ // order: LangGraph writes the results of parallel tasks at once.
23
+ //
24
+ // A task's `putWrites` is kept pending, and its promise resolves once its
25
+ // rows are stored, as LangGraph awaits it (before a run ends, whatever ends
26
+ // it, and before a step's `put` if it carries delta writes), and fails with
27
+ // its error. The `put` of its step, if called before the macrotask ends,
28
+ // which it is when the step's last task has just finished, stores the pending
29
+ // writes and then its checkpoint in one transaction: the writes' promises and
30
+ // the `put`'s settle when it commits, or fail with its error, so a step is
31
+ // stored before any task of the next starts. Else, the step has tasks still
32
+ // running, and the pending writes are stored on their own, in one
33
+ // transaction, at the end of the macrotask: a task that finished has its
34
+ // writes stored while its siblings run, so it does not run again after a
35
+ // crash, and no promise waits for a `put` to be called. Reads (`getTuple`,
36
+ // `list`), `prune` and `deleteThread` store what is pending first. Nothing
37
+ // is remembered of a failure: a failed `put` or store rejects the promises of
38
+ // what it carried, which are not stored again, and the attempt fails and
39
+ // goes on from what is stored.
23
40
  //
24
41
  // By default a thread keeps every checkpoint (LangGraph's history: `list`,
25
42
  // time travel, forks). With `history: 'latest'`, each `put` drops the
@@ -184,7 +201,29 @@ async function dropEarlier(tx: DatabaseWriter, threadId: string, ns: string, kep
184
201
  );
185
202
  }
186
203
 
187
- /** A LangGraph checkpointer whose threads are in the database session `db`: see the top of this file. */
204
+ /** One `putWrites`: its rows (a serialization in progress), the statement's verb, and how its promise settles. */
205
+ interface PendingWrites {
206
+ verb: string;
207
+ rows: Promise<SqlValue[][]>;
208
+ stored: PromiseWithResolvers<void>;
209
+ }
210
+
211
+ /** Settles the promises of `writes`: resolved once stored, or rejected with the `error` of what carried them. */
212
+ function settle(writes: PendingWrites[], error?: { error: unknown }) {
213
+ for (const { stored } of writes) {
214
+ if (error) stored.reject(error.error);
215
+ else stored.resolve();
216
+ }
217
+ }
218
+
219
+ /**
220
+ * A LangGraph checkpointer whose threads are in the database session `db`:
221
+ * see the top of this file. A task's pending writes are stored with the `put`
222
+ * that follows them in the same macrotask, else at the end of it; a
223
+ * `putWrites` promise resolves once they are stored, so awaiting it, as
224
+ * LangGraph does before a run ends, has them stored. This holds for a user's
225
+ * own use of the saver too.
226
+ */
188
227
  export class SqlCheckpointSaver extends BaseCheckpointSaver {
189
228
  #db: Database;
190
229
  #latest: boolean;
@@ -197,6 +236,10 @@ export class SqlCheckpointSaver extends BaseCheckpointSaver {
197
236
  #needed = new Map<string, Needed[]>();
198
237
  #ready: Promise<void> | undefined;
199
238
  #tail: Promise<unknown> = Promise.resolve();
239
+ /** The writes of tasks that no operation has taken yet, in the order LangGraph called `putWrites`. */
240
+ #pending: PendingWrites[] = [];
241
+ /** Stores what is pending, when the macrotask ends. */
242
+ #timer: NodeJS.Immediate | undefined;
200
243
 
201
244
  /**
202
245
  * `db`: a database session (`ctx.db`). `history`: the checkpoints a thread
@@ -237,6 +280,42 @@ export class SqlCheckpointSaver extends BaseCheckpointSaver {
237
280
  return result;
238
281
  }
239
282
 
283
+ /** The writes pending now, which the caller must store, in order; the end of the macrotask has nothing to store then. */
284
+ #take(): PendingWrites[] {
285
+ if (this.#timer) clearImmediate(this.#timer);
286
+ this.#timer = undefined;
287
+ return this.#pending.splice(0);
288
+ }
289
+
290
+ /** Stores `writes` in `tx`, in order. */
291
+ async #store(tx: DatabaseWriter, writes: PendingWrites[]) {
292
+ for (const { verb, rows } of writes) {
293
+ for (const row of await rows) {
294
+ await tx.execute(
295
+ `${verb} INTO restate_langgraph_writes (thread_id, checkpoint_ns, checkpoint_id, task_id, idx, channel, type, value, task_path) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
296
+ row,
297
+ );
298
+ }
299
+ }
300
+ }
301
+
302
+ /**
303
+ * Stores what is pending, on its own, in order with the operations: the
304
+ * ones called after it are after it. Its promises settle with the commit.
305
+ */
306
+ #storePending(): void {
307
+ const writes = this.#take();
308
+ if (writes.length === 0) return;
309
+ this.#serial(async () => {
310
+ // Serialized before the transaction opens, as a `put`'s values are.
311
+ await Promise.all(writes.map(({ rows }) => rows));
312
+ await this.#db.transaction((tx) => this.#store(tx, writes));
313
+ }).then(
314
+ () => settle(writes),
315
+ (error: unknown) => settle(writes, { error }),
316
+ );
317
+ }
318
+
240
319
  /** The values of `checkpoint`'s channels, at its versions. */
241
320
  async #channelValues(threadId: string, ns: string, checkpoint: Checkpoint): Promise<Record<string, unknown>> {
242
321
  const versions = Object.entries(checkpoint.channel_versions ?? {});
@@ -346,6 +425,7 @@ export class SqlCheckpointSaver extends BaseCheckpointSaver {
346
425
  }
347
426
 
348
427
  getTuple(config: RunnableConfig): Promise<CheckpointTuple | undefined> {
428
+ this.#storePending();
349
429
  return this.#serial(async () => {
350
430
  const { thread_id, checkpoint_ns = '', checkpoint_id } = config.configurable ?? {};
351
431
  const rows = checkpoint_id
@@ -365,6 +445,7 @@ export class SqlCheckpointSaver extends BaseCheckpointSaver {
365
445
  config: RunnableConfig,
366
446
  { limit, before, filter }: CheckpointListOptions = {},
367
447
  ): AsyncGenerator<CheckpointTuple> {
448
+ this.#storePending();
368
449
  const tuples = await this.#serial(async () => {
369
450
  const { thread_id, checkpoint_ns } = config.configurable ?? {};
370
451
  const where: string[] = [];
@@ -401,6 +482,8 @@ export class SqlCheckpointSaver extends BaseCheckpointSaver {
401
482
  metadata: CheckpointMetadata,
402
483
  newVersions: ChannelVersions,
403
484
  ): Promise<RunnableConfig> {
485
+ // The writes called before it, whose transaction this is.
486
+ const writes = this.#take();
404
487
  return this.#serial(async () => {
405
488
  const { thread_id, checkpoint_ns = '', checkpoint_id: parentId } = config.configurable ?? {};
406
489
  if (!thread_id) throw new Error('Missing "thread_id" field in passed "config.configurable".');
@@ -415,8 +498,10 @@ export class SqlCheckpointSaver extends BaseCheckpointSaver {
415
498
  return [channel, String(version), valueType, value];
416
499
  }),
417
500
  );
501
+ await Promise.all(writes.map(({ rows }) => rows));
418
502
  let kept: Needed[] | undefined;
419
503
  await this.#db.transaction(async (tx) => {
504
+ await this.#store(tx, writes);
420
505
  for (const row of changed) {
421
506
  await tx.execute(
422
507
  'INSERT OR REPLACE INTO restate_langgraph_channel_values (thread_id, checkpoint_ns, channel, version, type, value) VALUES (?, ?, ?, ?, ?, ?)',
@@ -435,41 +520,53 @@ export class SqlCheckpointSaver extends BaseCheckpointSaver {
435
520
  // Once stored: a transaction rolled back keeps the ones before.
436
521
  if (kept) this.#needed.set(JSON.stringify([thread_id, checkpoint_ns]), kept);
437
522
  return { configurable: { thread_id, checkpoint_ns, checkpoint_id: checkpoint.id } };
438
- });
523
+ }).then(
524
+ (stored) => {
525
+ settle(writes);
526
+ return stored;
527
+ },
528
+ (error: unknown) => {
529
+ // The writes it carried fail with it, and are not stored again: the attempt fails, and goes on from what is stored.
530
+ settle(writes, { error });
531
+ throw error;
532
+ },
533
+ );
439
534
  }
440
535
 
441
536
  putWrites(config: RunnableConfig, writes: PendingWrite[], taskId: string, taskPath?: string): Promise<void> {
442
- return this.#serial(async () => {
443
- const { thread_id, checkpoint_ns = '', checkpoint_id } = config.configurable ?? {};
444
- if (!thread_id) throw new Error('Missing thread_id field in config.configurable.');
445
- if (!checkpoint_id) throw new Error('Missing checkpoint_id field in config.configurable.');
446
- // Special writes (errors, interrupts) replace; others keep the first.
447
- const verb = writes.every(([channel]) => channel in WRITES_IDX_MAP) ? 'INSERT OR REPLACE' : 'INSERT OR IGNORE';
448
- const rows = await Promise.all(
449
- writes.map(async ([channel, value], idx): Promise<SqlValue[]> => {
450
- const [type, stored] = await this.serde.dumpsTyped(value);
451
- return [
452
- thread_id,
453
- checkpoint_ns,
454
- checkpoint_id,
455
- taskId,
456
- WRITES_IDX_MAP[channel] ?? idx,
457
- channel,
458
- type,
459
- stored,
460
- taskPath ?? null,
461
- ];
462
- }),
463
- );
464
- await this.#db.transaction(async (tx) => {
465
- for (const row of rows) {
466
- await tx.execute(
467
- `${verb} INTO restate_langgraph_writes (thread_id, checkpoint_ns, checkpoint_id, task_id, idx, channel, type, value, task_path) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
468
- row,
469
- );
470
- }
471
- });
537
+ const { thread_id, checkpoint_ns = '', checkpoint_id } = config.configurable ?? {};
538
+ if (!thread_id) return Promise.reject(new Error('Missing thread_id field in config.configurable.'));
539
+ if (!checkpoint_id) return Promise.reject(new Error('Missing checkpoint_id field in config.configurable.'));
540
+ // Special writes (errors, interrupts) replace; others keep the first.
541
+ const verb = writes.every(([channel]) => channel in WRITES_IDX_MAP) ? 'INSERT OR REPLACE' : 'INSERT OR IGNORE';
542
+ const rows = Promise.all(
543
+ writes.map(async ([channel, value], idx): Promise<SqlValue[]> => {
544
+ const [type, stored] = await this.serde.dumpsTyped(value);
545
+ return [
546
+ thread_id,
547
+ checkpoint_ns,
548
+ checkpoint_id,
549
+ taskId,
550
+ WRITES_IDX_MAP[channel] ?? idx,
551
+ channel,
552
+ type,
553
+ stored,
554
+ taskPath ?? null,
555
+ ];
556
+ }),
557
+ );
558
+ // Whoever stores it awaits it, and fails with it; until then it is not an unhandled rejection.
559
+ rows.catch(() => {});
560
+ const stored = Promise.withResolvers<void>();
561
+ // The caller awaits `stored`, as LangGraph does; a rejection is observed either way.
562
+ stored.promise.catch(() => {});
563
+ this.#pending.push({ verb, rows, stored });
564
+ // A `put` in this macrotask takes it, else it is stored on its own when the macrotask ends.
565
+ this.#timer ??= setImmediate(() => {
566
+ this.#timer = undefined;
567
+ this.#storePending();
472
568
  });
569
+ return stored.promise;
473
570
  }
474
571
 
475
572
  /**
@@ -482,6 +579,7 @@ export class SqlCheckpointSaver extends BaseCheckpointSaver {
482
579
  * (`''`) or a subgraph run's, which keeps its latest checkpoint too.
483
580
  */
484
581
  prune(threadIds: string[], { strategy = 'keepLatest' }: { strategy?: 'keepLatest' | 'delete' } = {}): Promise<void> {
582
+ this.#storePending();
485
583
  return this.#serial(() =>
486
584
  this.#db.transaction(async (tx) => {
487
585
  for (const threadId of threadIds) {
@@ -506,6 +604,7 @@ export class SqlCheckpointSaver extends BaseCheckpointSaver {
506
604
  }
507
605
 
508
606
  deleteThread(threadId: string): Promise<void> {
607
+ this.#storePending();
509
608
  return this.#serial(() =>
510
609
  this.#db.transaction(async (tx) => {
511
610
  for (const table of TABLES) await tx.execute(`DELETE FROM ${table} WHERE thread_id = ?`, [threadId]);
@@ -7,7 +7,9 @@
7
7
  // the message as a new `HumanMessage`:
8
8
  //
9
9
  // - The graph's checkpoints are in the key's database (`SqlCheckpointSaver`),
10
- // stored before each step runs (`durability: 'sync'`), and the prebuilt
10
+ // stored before each step runs (`durability: 'sync'`; a step's writes
11
+ // with its checkpoint, see checkpointer.ts; LangGraph awaits them all
12
+ // before a run ends, an error or a stop included), and the prebuilt
11
13
  // nodes (nodes.ts) and the tools of `tools()` get the handler's context
12
14
  // there (context.ts). LangGraph's run context is the graph's own (`context`),
13
15
  // else the handler's. A retried attempt resumes the run it cut off. A run
@@ -66,6 +68,7 @@ import { companionHere } from '../companion.ts';
66
68
  import { SqlCheckpointSaver } from './checkpointer.ts';
67
69
  import { running } from './context.ts';
68
70
  import { terminalOf } from './errors.ts';
71
+ import { KeepModelsAlive } from './keepalive.ts';
69
72
 
70
73
  /** A graph of your own: a `StateGraph` (not compiled), or a compiled one such as LangChain's `createAgent` makes. */
71
74
  export type AnyGraph =
@@ -357,14 +360,20 @@ async function runGraph(
357
360
  // version its structured answer had before it.
358
361
  const saver = new SqlCheckpointSaver(ctx.db, { metadata: { [PROMPT]: promptId, [STRUCTURED_BEFORE]: before } });
359
362
  const run = compiled(graph, saver);
363
+ // Each request of a model is kept alive, wherever the graph makes it (see keepalive.ts).
364
+ const kept = new KeepModelsAlive(ctx);
360
365
  const options = {
361
366
  ...THREAD,
362
367
  context,
363
368
  durability: 'sync',
364
369
  streamMode: 'values',
365
370
  signal: stopSignalOf(ctx),
371
+ callbacks: [kept],
366
372
  };
367
- if (asked && snapshot.next.length === 0) {
373
+ // `next` leaves out the tasks whose writes are stored, so a step whose writes were stored before its checkpoint
374
+ // (a crash between them) has no `next` but still has tasks: that run goes on, from those writes, without running
375
+ // the tasks again. A finished run has no tasks.
376
+ if (asked && snapshot.tasks.length === 0) {
368
377
  // The run had finished, but its answer was not stored: that is the answer, rather than run again.
369
378
  await copied(turn, known, messages, promptId);
370
379
  await saver.prune([THREAD_ID]);
@@ -394,6 +403,9 @@ async function runGraph(
394
403
  // No refusal, whatever its name: a graph's models, tools and nodes are all its own.
395
404
  fromTool(ctx, error);
396
405
  throw error;
406
+ } finally {
407
+ // A request that never reported its end (a stopped run's) must not keep the attempt alive while it waits.
408
+ kept.releaseAll();
397
409
  }
398
410
  // The run stops at its interrupts: it goes on with the signals that answer them.
399
411
  const paused = await storedState(run);
@@ -254,7 +254,7 @@ function toolLoop(
254
254
  .addNode('model', async ({ messages }) => {
255
255
  const steered = await takeSteers(ctx, conversation);
256
256
  const asked = [...messages, ...steered];
257
- const reply = await withTools.invoke(system ? [new SystemMessage(system), ...asked] : asked);
257
+ const reply = await ctx.working(() => withTools.invoke(system ? [new SystemMessage(system), ...asked] : asked));
258
258
  await turn.appendReply([reply]);
259
259
  return { messages: [...steered, reply] };
260
260
  })
@@ -472,8 +472,8 @@ export const messages = () => conversationView(items);
472
472
  */
473
473
  export const summarizer =
474
474
  (model?: Options['model']): Summarize =>
475
- async (_ctx, request) =>
476
- (await (await modelOfOptions(model)).invoke([new HumanMessage(request)])).text;
475
+ async (ctx, request) =>
476
+ ctx.working(async () => (await (await modelOfOptions(model)).invoke([new HumanMessage(request)])).text);
477
477
 
478
478
  /** An agent: a virtual object `name`, one per key, whose `chat` handler is {@link chat}, and `messages` {@link messages}. */
479
479
  export const agent = <P extends string, O extends z.ZodObject | undefined = undefined>({
@@ -0,0 +1,58 @@
1
+ // A graph of your own calls its models as it likes: its nodes, or LangChain's
2
+ // `createAgent`. The attempt must be kept alive (`ctx.working`) while a model
3
+ // serves a request, and a request is what LangChain's callbacks bracket: a
4
+ // chat model's start opens a scope, its end or error closes it.
5
+ //
6
+ // The handler awaits its handlers (`awaitHandlers`): LangChain awaits the
7
+ // start callback before it sends the request, so the scope is open by then.
8
+ // Not every request ends in a callback: a stream its consumer abandons, or a
9
+ // run cut off by a stop, calls neither the end nor the error. The run
10
+ // releases what is left (`releaseAll`) when its stream ends, however it ends.
11
+ import { BaseCallbackHandler } from '@langchain/core/callbacks/base';
12
+ import type * as restate from '@restatedev/sessions';
13
+ import { keepAlive } from '../common.ts';
14
+
15
+ /** A callback handler that keeps the attempt of `ctx` alive while a model's request of the run is out. */
16
+ export class KeepModelsAlive extends BaseCallbackHandler {
17
+ name = 'restate-keep-models-alive';
18
+ // Awaited, so that the scope is open before LangChain sends the request.
19
+ override awaitHandlers = true;
20
+ readonly #ctx: restate.SessionContext;
21
+ readonly #open = new Map<string, () => void>();
22
+
23
+ constructor(ctx: restate.SessionContext) {
24
+ super();
25
+ this.#ctx = ctx;
26
+ }
27
+
28
+ #begin(runId: string) {
29
+ if (!this.#open.has(runId)) this.#open.set(runId, keepAlive(this.#ctx));
30
+ }
31
+
32
+ #end(runId: string) {
33
+ this.#open.get(runId)?.();
34
+ this.#open.delete(runId);
35
+ }
36
+
37
+ override handleChatModelStart(_llm: unknown, _messages: unknown, runId: string) {
38
+ this.#begin(runId);
39
+ }
40
+
41
+ override handleLLMStart(_llm: unknown, _prompts: unknown, runId: string) {
42
+ this.#begin(runId);
43
+ }
44
+
45
+ override handleLLMEnd(_output: unknown, runId: string) {
46
+ this.#end(runId);
47
+ }
48
+
49
+ override handleLLMError(_error: unknown, runId: string) {
50
+ this.#end(runId);
51
+ }
52
+
53
+ /** Close the scopes of requests that never reported their end: a run's, once its stream has ended. */
54
+ releaseAll() {
55
+ for (const release of this.#open.values()) release();
56
+ this.#open.clear();
57
+ }
58
+ }
@@ -183,6 +183,21 @@ then the file) has each ask answered by the first's answer. OpenCode's hook
183
183
  does not tell an ask from a probe (an edit's hint on a miss), so a probe
184
184
  that would ask waits too.
185
185
 
186
+ ## Keeping alive
187
+
188
+ Restate shuts an attempt down after its inactivity timeout (a minute) and starts it again, unless
189
+ something keeps it alive. The adapter keeps it alive (`ctx.working`) while OpenCode's turn runs:
190
+ while the model streams its requests, and while OpenCode's own tools (shell, read, write, edit,
191
+ glob, grep) work on the machine, a command that runs for minutes included. But not:
192
+
193
+ - while a tool of your own runs, unless it says so itself (`tool({ keepalive: true })`): it may
194
+ wait on Restate (a call, a signal), and such a wait suspends.
195
+ - while it waits for an approval, even of the shell: a wait on Restate suspends.
196
+
197
+ OpenCode has no hook at the end of a model's request, so this is the turn's scope with a gap for
198
+ each tool that runs (tools may overlap: the scope reopens once none runs). A request OpenCode
199
+ makes outside a turn (a session's title, say) is not kept alive.
200
+
186
201
  ## Not yet
187
202
 
188
203
  - **A change of `model`** for a key that has a session already: the session