@restatedev/agents 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/README.md +79 -24
  2. package/dist/calls.d.ts +20 -1
  3. package/dist/calls.d.ts.map +1 -1
  4. package/dist/calls.js +46 -7
  5. package/dist/calls.js.map +1 -1
  6. package/dist/claude/index.d.ts +11 -11
  7. package/dist/claude/index.d.ts.map +1 -1
  8. package/dist/claude/index.js +12 -6
  9. package/dist/claude/index.js.map +1 -1
  10. package/dist/client.d.ts +1 -1
  11. package/dist/client.d.ts.map +1 -1
  12. package/dist/common.d.ts +62 -23
  13. package/dist/common.d.ts.map +1 -1
  14. package/dist/common.js +67 -38
  15. package/dist/common.js.map +1 -1
  16. package/dist/{signals.d.ts → companion.d.ts} +106 -43
  17. package/dist/companion.d.ts.map +1 -0
  18. package/dist/companion.js +463 -0
  19. package/dist/companion.js.map +1 -0
  20. package/dist/conversation.d.ts +103 -5
  21. package/dist/conversation.d.ts.map +1 -1
  22. package/dist/conversation.js +295 -75
  23. package/dist/conversation.js.map +1 -1
  24. package/dist/deepseek/index.d.ts +11 -11
  25. package/dist/deepseek/index.d.ts.map +1 -1
  26. package/dist/deepseek/index.js +26 -26
  27. package/dist/deepseek/index.js.map +1 -1
  28. package/dist/index.d.ts +8 -4
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +7 -3
  31. package/dist/index.js.map +1 -1
  32. package/dist/langgraph/checkpointer.d.ts +3 -1
  33. package/dist/langgraph/checkpointer.d.ts.map +1 -1
  34. package/dist/langgraph/checkpointer.js +15 -6
  35. package/dist/langgraph/checkpointer.js.map +1 -1
  36. package/dist/langgraph/graph.d.ts.map +1 -1
  37. package/dist/langgraph/graph.js +32 -13
  38. package/dist/langgraph/graph.js.map +1 -1
  39. package/dist/langgraph/index.d.ts +11 -11
  40. package/dist/langgraph/index.d.ts.map +1 -1
  41. package/dist/langgraph/index.js +19 -13
  42. package/dist/langgraph/index.js.map +1 -1
  43. package/dist/langgraph/nodes.d.ts +2 -1
  44. package/dist/langgraph/nodes.d.ts.map +1 -1
  45. package/dist/langgraph/nodes.js +23 -20
  46. package/dist/langgraph/nodes.js.map +1 -1
  47. package/dist/object.d.ts +24 -22
  48. package/dist/object.d.ts.map +1 -1
  49. package/dist/object.js +14 -11
  50. package/dist/object.js.map +1 -1
  51. package/dist/opencode/index.d.ts +11 -11
  52. package/dist/opencode/index.d.ts.map +1 -1
  53. package/dist/opencode/index.js +25 -27
  54. package/dist/opencode/index.js.map +1 -1
  55. package/dist/pi/index.d.ts +13 -13
  56. package/dist/pi/index.d.ts.map +1 -1
  57. package/dist/pi/index.js +18 -20
  58. package/dist/pi/index.js.map +1 -1
  59. package/dist/pi/storage.d.ts +7 -0
  60. package/dist/pi/storage.d.ts.map +1 -1
  61. package/dist/pi/storage.js +12 -0
  62. package/dist/pi/storage.js.map +1 -1
  63. package/dist/steering.d.ts +2 -1
  64. package/dist/steering.d.ts.map +1 -1
  65. package/dist/steering.js +2 -2
  66. package/dist/steering.js.map +1 -1
  67. package/dist/tools.d.ts +21 -0
  68. package/dist/tools.d.ts.map +1 -1
  69. package/dist/tools.js +54 -14
  70. package/dist/tools.js.map +1 -1
  71. package/dist/webhook.js +1 -1
  72. package/dist/webhook.js.map +1 -1
  73. package/package.json +90 -84
  74. package/src/calls.ts +52 -11
  75. package/src/claude/README.md +4 -2
  76. package/src/claude/index.ts +12 -7
  77. package/src/client.ts +1 -1
  78. package/src/common.ts +99 -40
  79. package/src/companion.ts +674 -0
  80. package/src/conversation.ts +353 -101
  81. package/src/deepseek/README.md +7 -1
  82. package/src/deepseek/index.ts +25 -24
  83. package/src/index.ts +10 -4
  84. package/src/langgraph/README.md +8 -5
  85. package/src/langgraph/checkpointer.ts +26 -15
  86. package/src/langgraph/graph.ts +30 -16
  87. package/src/langgraph/index.ts +24 -17
  88. package/src/langgraph/nodes.ts +24 -20
  89. package/src/object.ts +43 -40
  90. package/src/opencode/README.md +5 -2
  91. package/src/opencode/index.ts +26 -27
  92. package/src/pi/README.md +6 -1
  93. package/src/pi/index.ts +25 -19
  94. package/src/pi/storage.ts +13 -0
  95. package/src/steering.ts +8 -7
  96. package/src/tools.ts +60 -18
  97. package/src/webhook.ts +1 -1
  98. package/dist/signals.d.ts.map +0 -1
  99. package/dist/signals.js +0 -383
  100. package/dist/signals.js.map +0 -1
  101. package/src/signals.ts +0 -590
@@ -24,9 +24,10 @@
24
24
  // Both share one sequence of positions, which are the ids of the messages
25
25
  // the `messages` view renders (messages.ts); and each row has a `seq`, which
26
26
  // grows with every row written, for a client that reads from a cursor. Rows
27
- // are only appended, in one transaction per step, but for a reply at the end
28
- // that is dropped (to ask the model again), one range delete; and a turn's
29
- // answer is one update of its row.
27
+ // are only appended, in one transaction per step (a step no tool waits for,
28
+ // such as the final reply, is held for the next write in `answerOnce`'s run:
29
+ // see `Ledger`), but for a reply at the end that is dropped (to ask the model
30
+ // again), one range delete; and a turn's answer is one update of its row.
30
31
  //
31
32
  // The model gets the transcript, and the whole trajectories of the latest
32
33
  // `window` turns and of any turn after them that another invocation ended
@@ -42,9 +43,9 @@
42
43
  // gives its `Items` (how its items say what they are) and a `Run` (its own
43
44
  // loop, from the conversation to the answer, storing each step as it goes).
44
45
  import * as restate from '@restatedev/sessions';
45
- import { definitionOf, Schema } from '@restatedev/sessions/internal';
46
- import { forPrompt, outcomes } from './calls.js';
47
- import { answering, AttemptEnded, aborted, BUDGET, CANCELLED, checkWindow, cutOffResult, ENDED, nextPromptId, refusalOf, REFUSED, settingsOf, stopSignalOf, storedAnswer, SUMMARIZE, UNANSWERED, } from './common.js';
46
+ import { definitionOf, ensureSchemas, Schema } from '@restatedev/sessions/internal';
47
+ import { forPrompt, holding, outcomes, SCHEMA as CALLS } from './calls.js';
48
+ import { afterStepsOf, answering, AttemptEnded, settleAnswered, aborted, BUDGET, CANCELLED, checkWindow, cutOffResult, ENDED, nextPromptId, refusalOf, REFUSED, settingsOf, stopSignalOf, storedAnswer, SUMMARIZE, UNANSWERED, } from './common.js';
48
49
  /** The transcript: one row per turn. */
49
50
  export const TURNS = 'restate_agent_turns';
50
51
  /** The trajectories: the items of each turn but its prompt. */
@@ -210,7 +211,24 @@ class Lock {
210
211
  return done;
211
212
  }
212
213
  }
213
- /** What a conversation and its turns share: the database, the next position and `seq`, and the writes' lock. */
214
+ /**
215
+ * What a conversation and its turns share: the database, the next position
216
+ * and `seq`, and the writes' lock.
217
+ *
218
+ * In `answerOnce`'s run ({@link Conversation.hold}), a step that no tool
219
+ * waits for (a reply without tool calls, say) is held rather than written
220
+ * (`held`): every write writes the held rows first, in its own transaction,
221
+ * so that a turn's final reply commits with its answer, in one flush rather
222
+ * than two. A held row is in memory only: lost in a crash, it is made again
223
+ * by the retried attempt, which runs from what the database holds. So the
224
+ * run writes them ({@link Conversation.flush}) before anything another party
225
+ * sees or that outlives the attempt: a publish, a Restate call of the
226
+ * library, the attempt failing.
227
+ *
228
+ * After each write of steps that commits, the run makes what it was given
229
+ * to make then (`afterCommit`), if anything; not after held rows: they are
230
+ * no step that anyone waits for.
231
+ */
214
232
  class Ledger {
215
233
  /** The latest turn, if loaded whole: the only one that may be written. */
216
234
  latest;
@@ -230,6 +248,16 @@ class Ledger {
230
248
  next;
231
249
  /** The last `seq` given. */
232
250
  seq;
251
+ /** Whether steps that no tool waits for are held ({@link Conversation.hold}), rather than written at once. */
252
+ holds = false;
253
+ /**
254
+ * The rows of the trajectories given positions but not written yet, in
255
+ * order of position ({@link INSERT_STEP}'s parameters): the next write
256
+ * writes them first.
257
+ */
258
+ held = [];
259
+ /** What the run makes after each write of steps that commits ({@link Conversation.hold}), if anything. */
260
+ afterCommit;
233
261
  constructor(db, items, start, transcript, next, seq) {
234
262
  this.db = db;
235
263
  this.items = items;
@@ -250,12 +278,76 @@ class Ledger {
250
278
  if (this.closed)
251
279
  throw new Error('the run was stopped: it stores nothing more');
252
280
  }
281
+ /**
282
+ * Run `body`, a write of the conversation, in one transaction; then
283
+ * `done`, its bookkeeping (the entries it added, an answer's assignment);
284
+ * hold the lock. `body` takes the next position and `seq` as it runs, and
285
+ * sets them past its rows (a framework's copy into the turn, `copyIn`,
286
+ * waits for it, and takes those after).
287
+ *
288
+ * A write and its bookkeeping happen together, or not at all. A commit is
289
+ * stored once it is handed to Restate, before it waits for Restate's
290
+ * acknowledgment: a wait that fails then (one the SDK cancels, say) leaves
291
+ * the rows stored, so `done` runs, and the error is thrown after it.
292
+ * Without it, the ledger would lack what the database holds: a close would
293
+ * give a stored result again, miss a stored call, or close an answered
294
+ * turn. Only a `body` that fails, or a commit the engine refused (SQL: it
295
+ * rolled back), writes nothing, and changes nothing.
296
+ */
297
+ async write(body, done = () => { }) {
298
+ let handed;
299
+ let before = [this.next, this.seq];
300
+ // The held rows first, as the write runs (a framework's copy, which it may wait for, writes those it finds):
301
+ // they are no longer held once the write is stored, and still are if it rolls back.
302
+ let held = [];
303
+ const stored = () => {
304
+ this.held = this.held.filter((row) => !held.includes(row));
305
+ done();
306
+ };
307
+ try {
308
+ await this.db.transaction(async (tx) => {
309
+ before = [this.next, this.seq];
310
+ held = this.held;
311
+ await writeHeld(tx, held);
312
+ await body(tx);
313
+ handed = [this.next, this.seq];
314
+ });
315
+ }
316
+ catch (error) {
317
+ if (handed === undefined)
318
+ throw error;
319
+ if (rolledBack(error)) {
320
+ // The positions it took are given again, unless a copy took those after them meanwhile.
321
+ if (this.next === handed[0] && this.seq === handed[1])
322
+ [this.next, this.seq] = before;
323
+ throw error;
324
+ }
325
+ stored();
326
+ throw error;
327
+ }
328
+ stored();
329
+ }
330
+ /** Whether `entries`, which are read, are held rather than written: no tool call nor result, in a run that holds. */
331
+ holdsBack(entries) {
332
+ return (this.holds && !entries.some((e) => (e.parsed?.calls ?? []).length > 0 || (e.parsed?.results ?? []).length > 0));
333
+ }
253
334
  /** The agent and the framework's state that the latest answered turn left. */
254
335
  carried() {
255
336
  const latest = this.transcript.findLast((turn) => turn.answer !== undefined);
256
337
  return latest ? [latest.agent, latest.carried] : [undefined, undefined];
257
338
  }
258
339
  }
340
+ /** Write the held rows `held` in `tx`, the same statement for each: the database prepares it once. */
341
+ async function writeHeld(tx, held) {
342
+ for (const row of held)
343
+ await tx.execute(INSERT_STEP, row);
344
+ }
345
+ /**
346
+ * Whether a commit that failed was rolled back: the engine refused its SQL
347
+ * (an `SqlError`, which the handler gets as a terminal error). Any other
348
+ * failure of a commit is of its wait for Restate, once its rows were stored.
349
+ */
350
+ const rolledBack = (error) => error instanceof restate.TerminalError && error.cause?.name === 'SqlError';
259
351
  /** The index of the first of `entries` (by position) at `n` or after. */
260
352
  const bisect = (entries, n) => {
261
353
  let low = 0;
@@ -331,7 +423,7 @@ export class Turn {
331
423
  }
332
424
  #add(entries) {
333
425
  for (const entry of entries) {
334
- entry.parsed = this.#ledger.items.read(entry.item);
426
+ parsedOf(this.#ledger.items, entry);
335
427
  entry.turn = this.n;
336
428
  this.#index(entry);
337
429
  }
@@ -411,13 +503,37 @@ export class Turn {
411
503
  return result !== undefined && (!failed(result) || result.output === failedWith);
412
504
  }
413
505
  // Writing: only the latest turn, while it has no answer.
414
- /** Append `items` (a tool's results, say) to the turn, in one transaction; appends at once are each stored after the ones before. */
506
+ /**
507
+ * Append `items` (a tool's results, say) to the turn, in one transaction;
508
+ * appends at once are each stored after the ones before. In
509
+ * `answerOnce`'s run, a write that commits makes what the run makes after
510
+ * a commit ({@link Conversation.hold}).
511
+ */
415
512
  async append(...items) {
416
- await this.#insert((n) => items.map((item, i) => ({ n: n + i, item })));
513
+ await this.#stored((n) => items.map((item, i) => ({ n: n + i, item })));
417
514
  }
418
- /** Append the model's reply, of `items` (given by `agent`), to the turn, and return its id. */
515
+ /**
516
+ * Append the model's reply, of `items` (given by `agent`), to the turn,
517
+ * and return its id. In `answerOnce`'s run, a reply with tool calls
518
+ * commits, and makes what the run makes after a commit; one without is
519
+ * held, and commits with the next write (the answer, for the final reply).
520
+ */
419
521
  appendReply(items, agent) {
420
- return this.#insert((n) => items.map((item, i) => ({ n: n + i, item, reply: n, agent })));
522
+ return this.#stored((n) => items.map((item, i) => ({ n: n + i, item, reply: n, agent })));
523
+ }
524
+ /**
525
+ * Make what the turn's run makes after each write of its steps that
526
+ * commits ({@link Conversation.hold}), if anything, for a framework that
527
+ * copies steps into the turn in a transaction of its own ({@link copyIn}):
528
+ * call it once that transaction has committed with steps that a tool
529
+ * waits for (a reply with tool calls, the tools' results), and await it
530
+ * before the framework's next step. `append` and `appendReply` make it
531
+ * themselves. What it makes is the business of whoever runs the turn
532
+ * (`answerOnce` takes it from the `chat` turn it runs in, if any, which
533
+ * publishes there); the conversation only calls it.
534
+ */
535
+ async stepsCommitted() {
536
+ await this.#ledger.afterCommit?.();
421
537
  }
422
538
  /**
423
539
  * Ask the model again within the turn, with `text`: a message of the user
@@ -459,7 +575,7 @@ export class Turn {
459
575
  return [];
460
576
  let added = [];
461
577
  // The positions and seqs taken as the write runs, as `#insert` takes them.
462
- await ledger.db.transaction(async (tx) => {
578
+ await ledger.write(async (tx) => {
463
579
  const n = ledger.next;
464
580
  added = fresh.map((m, i) => ({ n: n + i, item: steeredItem(ledger.items, m.text, m.id), steer: m.id }));
465
581
  for (const [i, e] of added.entries()) {
@@ -469,10 +585,11 @@ export class Turn {
469
585
  taken(tx, fresh.map((m) => m.id));
470
586
  ledger.seq += added.length;
471
587
  ledger.next = n + added.length;
588
+ }, () => {
589
+ this.#add(added);
590
+ // The transcript's entry of the turn has them too, as the next turn loads it: for its size, say.
591
+ (this.prompt.steers ??= []).push(...added);
472
592
  });
473
- this.#add(added);
474
- // The transcript's entry of the turn has them too, as the next turn loads it: for its size, say.
475
- (this.prompt.steers ??= []).push(...added);
476
593
  return added.map((e) => e.item);
477
594
  });
478
595
  }
@@ -504,29 +621,32 @@ export class Turn {
504
621
  await ledger.lock.run(async () => {
505
622
  this.#checkWritable();
506
623
  const start = { ...ledger.start, seq: ledger.seq };
507
- await ledger.db.transaction(async (tx) => {
624
+ // The held rows it drops are never written; those before it are, with the deletes.
625
+ ledger.held = ledger.held.filter((row) => Number(row[0]) < reply);
626
+ await ledger.write(async (tx) => {
508
627
  await tx.execute(`DELETE FROM ${STEPS} WHERE n >= ?`, [reply]);
509
628
  await tx.execute(`DELETE FROM ${STEERED} WHERE n >= ?`, [reply]);
510
629
  await restart(tx, start);
630
+ }, () => {
631
+ ledger.start = start;
632
+ ledger.next = Math.min(ledger.next, reply);
633
+ if (this.prompt.steers)
634
+ this.prompt.steers = this.prompt.steers.filter((e) => e.n < reply);
635
+ const cut = bisect(this.#entries, reply);
636
+ const kept = this.#entries.slice(0, cut);
637
+ // The dropped calls are not made: their ids may be made again, by the reply that replaces them.
638
+ for (const entry of this.#entries.slice(cut))
639
+ for (const call of entry.parsed?.calls ?? [])
640
+ ledger.ids.delete(call.id);
641
+ for (const entry of kept)
642
+ for (const call of entry.parsed?.calls ?? [])
643
+ ledger.ids.add(call.id);
644
+ this.#entries = kept;
645
+ this.#results = new Map();
646
+ this.#open = [];
647
+ for (const entry of kept)
648
+ this.#index(entry, false);
511
649
  });
512
- ledger.start = start;
513
- ledger.next = Math.min(ledger.next, reply);
514
- if (this.prompt.steers)
515
- this.prompt.steers = this.prompt.steers.filter((e) => e.n < reply);
516
- const cut = bisect(this.#entries, reply);
517
- const kept = this.#entries.slice(0, cut);
518
- // The dropped calls are not made: their ids may be made again, by the reply that replaces them.
519
- for (const entry of this.#entries.slice(cut))
520
- for (const call of entry.parsed?.calls ?? [])
521
- ledger.ids.delete(call.id);
522
- for (const entry of kept)
523
- for (const call of entry.parsed?.calls ?? [])
524
- ledger.ids.add(call.id);
525
- this.#entries = kept;
526
- this.#results = new Map();
527
- this.#open = [];
528
- for (const entry of kept)
529
- this.#index(entry, false);
530
650
  });
531
651
  }
532
652
  /**
@@ -534,6 +654,9 @@ export class Turn {
534
654
  * in one update of its row. The answer's message is the assistant's
535
655
  * message the turn ends with; a turn that ends otherwise gets `answer` as
536
656
  * its reply first, and an empty answer gets none.
657
+ *
658
+ * The final reply, which is held (see {@link Ledger}), commits with the
659
+ * update: in one transaction.
537
660
  */
538
661
  async answered(answer, status = 'answered') {
539
662
  let at = this.#answerMessage();
@@ -548,12 +671,11 @@ export class Turn {
548
671
  const carried = 'carried' in this.#carried ? this.#carried.carried : ledger.carried()[1];
549
672
  let seq = ledger.seq + 1;
550
673
  // Its seq taken as the write runs, as `#insert` takes its own.
551
- await ledger.db.transaction(async (tx) => {
674
+ await ledger.write(async (tx) => {
552
675
  seq = ledger.seq + 1;
553
676
  await tx.execute(ANSWER, [status, answer, agent ?? null, carried ?? null, at ?? null, seq, this.n]);
554
677
  ledger.seq = seq;
555
- });
556
- Object.assign(this.prompt, { status, answer, agent, carried, answeredAt: at, answeredSeq: seq });
678
+ }, () => Object.assign(this.prompt, { status, answer, agent, carried, answeredAt: at, answeredSeq: seq }));
557
679
  });
558
680
  }
559
681
  /**
@@ -615,16 +737,17 @@ export class Turn {
615
737
  const answeredSeq = seq + added.length + 1;
616
738
  const agent = this.#agent();
617
739
  const carried = 'carried' in this.#carried ? this.#carried.carried : ledger.carried()[1];
618
- await ledger.db.transaction(async (tx) => {
740
+ await ledger.write(async (tx) => {
619
741
  for (const [i, e] of added.entries()) {
620
742
  await tx.execute(INSERT_STEP, [e.n, this.n, seq + i + 1, items.dump(e.item), null, null]);
621
743
  }
622
744
  await tx.execute(ANSWER, [status, note, agent ?? null, carried ?? null, at, answeredSeq, this.n]);
745
+ ledger.next = n + added.length;
746
+ ledger.seq = answeredSeq;
747
+ }, () => {
748
+ this.#add(added);
749
+ Object.assign(this.prompt, { status, answer: note, agent, carried, answeredAt: at, answeredSeq });
623
750
  });
624
- ledger.next = n + added.length;
625
- ledger.seq = answeredSeq;
626
- this.#add(added);
627
- Object.assign(this.prompt, { status, answer: note, agent, carried, answeredAt: at, answeredSeq });
628
751
  });
629
752
  }
630
753
  /** Whether the turn's run can write it: the latest, without an answer, not being closed, of a conversation not sealed. */
@@ -656,6 +779,9 @@ export class Turn {
656
779
  ...(reply ? { reply: n + i, agent } : {}),
657
780
  ...(steer === undefined ? {} : { steer }),
658
781
  }));
782
+ // The rows held before it first, in its transaction: they go in the order of their seqs.
783
+ const held = ledger.held;
784
+ ledger.held = [];
659
785
  // A rolled back transaction fails its attempt, whose state goes with it.
660
786
  ledger.next = n + added.length;
661
787
  ledger.seq += added.length;
@@ -663,6 +789,7 @@ export class Turn {
663
789
  const steered = added.filter((e) => e.steer !== undefined);
664
790
  if (steered.length > 0)
665
791
  (this.prompt.steers ??= []).push(...steered);
792
+ await writeHeld(tx, held);
666
793
  for (const [i, e] of added.entries()) {
667
794
  await tx.execute(INSERT_STEP, [
668
795
  e.n,
@@ -690,35 +817,60 @@ export class Turn {
690
817
  throw new Error(`turn ${this.id} is not the turn being answered: only that turn is written`);
691
818
  }
692
819
  }
693
- /** Store the entries `made` makes from the next position, and return that position. */
820
+ /**
821
+ * Store the entries `made` makes ({@link #insert}), and return their
822
+ * position; then, if they committed (they are not held), make what the run
823
+ * makes after a commit ({@link stepsCommitted}), outside the lock,
824
+ * awaited before the caller goes on (a `chat` turn's publish, whose answer
825
+ * the caller's next step may take). Writes that run at once each make
826
+ * their own.
827
+ */
828
+ async #stored(made) {
829
+ const [n, held] = await this.#insert(made);
830
+ if (!held)
831
+ await this.stepsCommitted();
832
+ return n;
833
+ }
834
+ /**
835
+ * Store the entries `made` makes from the next position, and return that
836
+ * position, and whether they are held.
837
+ *
838
+ * Entries that hold no tool call nor result (a reply that ends the run,
839
+ * say) are held, not written, in a conversation that holds them (see
840
+ * {@link Ledger}): no tool waits for them, and the next write writes them.
841
+ * Tool calls are written before their tools run, and results before the
842
+ * model is asked again, with the rows held before them.
843
+ */
694
844
  #insert(made) {
695
845
  const ledger = this.#ledger;
696
846
  return ledger.lock.run(async () => {
697
847
  this.#checkWritable();
698
- let n = ledger.next;
848
+ const first = ledger.next;
849
+ const making = made(first);
850
+ for (const entry of making)
851
+ parsedOf(ledger.items, entry);
852
+ if (ledger.holdsBack(making)) {
853
+ ledger.held.push(...making.map((e, i) => stepRow(this.n, ledger.seq + i + 1, ledger.items, e)));
854
+ ledger.seq += making.length;
855
+ ledger.next = first + making.length;
856
+ this.#add(making);
857
+ return [first, true];
858
+ }
859
+ let n = first;
699
860
  let added = [];
700
861
  // The positions and seqs taken as the write runs: a framework's copy
701
862
  // into the turn (`copyIn`, in a transaction of its own, which this one
702
863
  // may wait for) takes those after them, so that they go in the order
703
864
  // the rows commit in, as a follower's cursor needs.
704
- await ledger.db.transaction(async (tx) => {
865
+ await ledger.write(async (tx) => {
705
866
  n = ledger.next;
706
- added = made(n);
707
- for (const [i, e] of added.entries()) {
708
- await tx.execute(INSERT_STEP, [
709
- e.n,
710
- this.n,
711
- ledger.seq + i + 1,
712
- ledger.items.dump(e.item),
713
- e.reply ?? null,
714
- e.agent ?? null,
715
- ]);
716
- }
867
+ added = n === first ? making : made(n);
868
+ for (const [i, e] of added.entries())
869
+ await tx.execute(INSERT_STEP, stepRow(this.n, ledger.seq + i + 1, ledger.items, e));
717
870
  ledger.seq += added.length;
718
871
  ledger.next = n + added.length;
719
- });
720
- this.#add(added);
721
- return n;
872
+ }, () => this.#add(added));
873
+ return [n, false];
722
874
  });
723
875
  }
724
876
  }
@@ -843,6 +995,15 @@ async function transcriptOf(db, items, first, bounded) {
843
995
  }
844
996
  /** Store a step of a turn: its position, its turn's, its `seq`, its item, and the reply and agent it is of. */
845
997
  const INSERT_STEP = `INSERT INTO ${STEPS} (n, turn, seq, item, reply, agent) VALUES (?, ?, ?, ?, ?, ?)`;
998
+ /** {@link INSERT_STEP}'s parameters for `entry`, a step of turn `turn` with `seq` `seq`. */
999
+ const stepRow = (turn, seq, items, entry) => [
1000
+ entry.n,
1001
+ turn,
1002
+ seq,
1003
+ items.dump(entry.item),
1004
+ entry.reply ?? null,
1005
+ entry.agent ?? null,
1006
+ ];
846
1007
  /** Mark the step at a position a message steered to its turn: the position, its turn's, and the message's id. */
847
1008
  const INSERT_STEERED = `INSERT INTO ${STEERED} (n, turn, id) VALUES (?, ?, ?)`;
848
1009
  /** Store a turn's answer on its row: how it ended, the answer, what it carries, its message's position, its `seq`. */
@@ -1054,22 +1215,60 @@ export class Conversation {
1054
1215
  throw new Error(`turn ${running.id} has no answer yet: turns never overlap`);
1055
1216
  const n = ledger.next;
1056
1217
  const entry = { n, item: this.items.prompt(text), prompt: promptId, askedAt: Date.now() };
1057
- await this.db.execute(`INSERT INTO ${TURNS} (n, seq, prompt, item, asked_at) VALUES (?, ?, ?, ?, ?)`, [
1058
- n,
1059
- ledger.seq + 1,
1060
- promptId,
1061
- this.items.dump(entry.item),
1062
- entry.askedAt,
1063
- ]);
1064
- ledger.seq += 1;
1065
- ledger.next = n + 1;
1066
- ledger.transcript.push(entry);
1067
- const turn = new Turn(ledger, entry);
1068
- this.#turns.push(turn);
1069
- ledger.latest = turn;
1218
+ let turn;
1219
+ await ledger.write(async (tx) => {
1220
+ await tx.execute(`INSERT INTO ${TURNS} (n, seq, prompt, item, asked_at) VALUES (?, ?, ?, ?, ?)`, [
1221
+ n,
1222
+ ledger.seq + 1,
1223
+ promptId,
1224
+ this.items.dump(entry.item),
1225
+ entry.askedAt,
1226
+ ]);
1227
+ ledger.seq += 1;
1228
+ ledger.next = n + 1;
1229
+ }, () => {
1230
+ ledger.transcript.push(entry);
1231
+ turn = new Turn(ledger, entry);
1232
+ this.#turns.push(turn);
1233
+ ledger.latest = turn;
1234
+ });
1070
1235
  return turn;
1071
1236
  });
1072
1237
  }
1238
+ /**
1239
+ * Hold the steps that no tool waits for, rather than write each at once:
1240
+ * the next write writes them (see {@link Ledger}). For a run that writes
1241
+ * them ({@link flush}) before each publish and Restate call of the
1242
+ * library, and before its attempt fails: `answerOnce`'s. A conversation
1243
+ * that is written otherwise (step by step, from handlers of its own)
1244
+ * writes each step as it comes.
1245
+ *
1246
+ * `afterCommit`, if given, is awaited after each write of steps that
1247
+ * commits (a reply with tool calls, the tools' results, with the rows held
1248
+ * before them), outside the lock. The conversation does not know what it
1249
+ * does: `answerOnce` passes what the turn it runs in asked for, if
1250
+ * anything (a followed `chat` turn's publish), so that a framework's
1251
+ * integration publishes nothing by hand. Held rows make none, nor does
1252
+ * `flush`. A framework that copies its steps in a transaction of its own
1253
+ * makes it with {@link Turn.stepsCommitted}.
1254
+ */
1255
+ hold(afterCommit) {
1256
+ this.#ledger.holds = true;
1257
+ this.#ledger.afterCommit = afterCommit;
1258
+ }
1259
+ /**
1260
+ * Write the rows the turn's run holds (see {@link Ledger}), if any: before
1261
+ * whatever another party sees, or outlives the attempt. A publish tells
1262
+ * the clients to read them, and a Restate call is made once, while a held
1263
+ * row would be lost in a crash.
1264
+ */
1265
+ async flush() {
1266
+ const ledger = this.#ledger;
1267
+ await ledger.lock.run(async () => {
1268
+ if (ledger.held.length > 0)
1269
+ await ledger.write(async () => { });
1270
+ });
1271
+ }
1073
1272
  /**
1074
1273
  * Close the conversation to writes, once those under way are stored: for
1075
1274
  * a stopped run, which (unwinding, or a promise of it left behind) stores
@@ -1097,7 +1296,8 @@ export const invocationOf = (promptId) => promptId.split(':', 1)[0];
1097
1296
  * answer is checked: a message it returns asks the model again with it,
1098
1297
  * once, as a step of the turn ({@link Turn.askAgain}), and the turn's answer
1099
1298
  * is the reply to that. With `reminder`, the model is told it after the
1100
- * prompt ({@link Turn.reminder}), which is stored as it was asked.
1299
+ * prompt ({@link Turn.reminder}), which is stored as it was asked. With
1300
+ * `schemas`, the framework's own tables are applied with the conversation's.
1101
1301
  */
1102
1302
  export async function answerOnce(ctx, text, items, run, options = {}) {
1103
1303
  const settings = settingsOf(ctx);
@@ -1112,12 +1312,27 @@ export async function answerOnce(ctx, text, items, run, options = {}) {
1112
1312
  const window = own ? 0 : checkWindow(options.window ?? settings.window);
1113
1313
  const budget = own ? 0 : (options.budget ?? settings.budget);
1114
1314
  const promptId = nextPromptId(ctx);
1115
- await SCHEMA.ensure(ctx.db);
1315
+ // With the tool calls' (calls.ts), which the turn reads as it ends whether
1316
+ // or not a tool ran, and the framework's own (`schemas`): a key's first
1317
+ // turn applies them in one commit, rather than one each.
1318
+ await ensureSchemas(ctx.db, [SCHEMA, CALLS, ...(options.schemas ?? [])]);
1116
1319
  const stored = await answerIn(ctx.db, promptId);
1117
1320
  // Answered (or closed) already: a retry answers, or fails, as the turn ended.
1118
1321
  if (stored !== undefined)
1119
1322
  return storedAnswer(stored.answer, stored.status);
1120
1323
  const conversation = await Conversation.load(ctx.db, items, window, budget);
1324
+ // The turn's final reply commits with its answer; the library's publishes and Restate calls write what the
1325
+ // run holds back first (`flushHeld`). After each write of steps that commits, the run makes what the turn it
1326
+ // runs in asked for, if anything (a `chat` turn's publish, which this does not know of): a turn outside one
1327
+ // stores its steps, and that is all.
1328
+ // Before it, the call records whose results the commit stored are forgotten (calls.ts): once per commit, for
1329
+ // every turn.
1330
+ const afterSteps = afterStepsOf(ctx);
1331
+ conversation.hold(async () => {
1332
+ await settleAnswered(ctx);
1333
+ await afterSteps?.();
1334
+ });
1335
+ holding(ctx, () => conversation.flush());
1121
1336
  const answered = await forPrompt(ctx, promptId, () => answering(ctx,
1122
1337
  // The Restate calls of this invocation are its turn's: the latest, answered
1123
1338
  // or not (its end forgets the calls whose results it stored).
@@ -1191,6 +1406,11 @@ async function answerTurn(ctx, conversation, promptId, text, run, check, reminde
1191
1406
  await close(turn, 'failed', `Error: ${error.message}`);
1192
1407
  throw error;
1193
1408
  }
1409
+ // The attempt fails, and its retry goes on from what is stored: so what
1410
+ // the run made so far is, as when each step was written as it came.
1411
+ // Never in place of the attempt's own error: its session may have ended
1412
+ // with it, and then nothing more is stored.
1413
+ await conversation.flush().catch(() => { });
1194
1414
  throw error;
1195
1415
  }
1196
1416
  await turn.answered(answered);