@restatedev/agents 0.5.0 → 0.6.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 (96) hide show
  1. package/README.md +69 -17
  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 +9 -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 +23 -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 +2 -0
  33. package/dist/langgraph/checkpointer.d.ts.map +1 -1
  34. package/dist/langgraph/checkpointer.js +1 -1
  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 +11 -11
  56. package/dist/pi/index.d.ts.map +1 -1
  57. package/dist/pi/index.js +16 -17
  58. package/dist/pi/index.js.map +1 -1
  59. package/dist/steering.d.ts +2 -1
  60. package/dist/steering.d.ts.map +1 -1
  61. package/dist/steering.js +2 -2
  62. package/dist/steering.js.map +1 -1
  63. package/dist/tools.d.ts +21 -0
  64. package/dist/tools.d.ts.map +1 -1
  65. package/dist/tools.js +54 -14
  66. package/dist/tools.js.map +1 -1
  67. package/dist/webhook.js +1 -1
  68. package/dist/webhook.js.map +1 -1
  69. package/package.json +3 -3
  70. package/src/calls.ts +52 -11
  71. package/src/claude/README.md +4 -2
  72. package/src/claude/index.ts +9 -7
  73. package/src/client.ts +1 -1
  74. package/src/common.ts +99 -40
  75. package/src/companion.ts +674 -0
  76. package/src/conversation.ts +353 -101
  77. package/src/deepseek/README.md +7 -1
  78. package/src/deepseek/index.ts +22 -24
  79. package/src/index.ts +10 -4
  80. package/src/langgraph/README.md +8 -5
  81. package/src/langgraph/checkpointer.ts +1 -1
  82. package/src/langgraph/graph.ts +30 -16
  83. package/src/langgraph/index.ts +24 -17
  84. package/src/langgraph/nodes.ts +24 -20
  85. package/src/object.ts +43 -40
  86. package/src/opencode/README.md +5 -2
  87. package/src/opencode/index.ts +26 -27
  88. package/src/pi/README.md +6 -1
  89. package/src/pi/index.ts +16 -15
  90. package/src/steering.ts +8 -7
  91. package/src/tools.ts +60 -18
  92. package/src/webhook.ts +1 -1
  93. package/dist/signals.d.ts.map +0 -1
  94. package/dist/signals.js +0 -383
  95. package/dist/signals.js.map +0 -1
  96. 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,12 +43,14 @@
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 type { Database, DatabaseReader, DatabaseWriter, Transaction } from '@restatedev/sessions';
46
- import { definitionOf, Schema } from '@restatedev/sessions/internal';
47
- import { forPrompt, outcomes } from './calls.ts';
46
+ import type { Database, DatabaseReader, DatabaseWriter, SqlParam, Transaction } from '@restatedev/sessions';
47
+ import { definitionOf, ensureSchemas, Schema } from '@restatedev/sessions/internal';
48
+ import { forPrompt, holding, outcomes, SCHEMA as CALLS } from './calls.ts';
48
49
  import {
50
+ afterStepsOf,
49
51
  answering,
50
52
  AttemptEnded,
53
+ settleAnswered,
51
54
  aborted,
52
55
  BUDGET,
53
56
  CANCELLED,
@@ -367,7 +370,24 @@ class Lock {
367
370
  }
368
371
  }
369
372
 
370
- /** What a conversation and its turns share: the database, the next position and `seq`, and the writes' lock. */
373
+ /**
374
+ * What a conversation and its turns share: the database, the next position
375
+ * and `seq`, and the writes' lock.
376
+ *
377
+ * In `answerOnce`'s run ({@link Conversation.hold}), a step that no tool
378
+ * waits for (a reply without tool calls, say) is held rather than written
379
+ * (`held`): every write writes the held rows first, in its own transaction,
380
+ * so that a turn's final reply commits with its answer, in one flush rather
381
+ * than two. A held row is in memory only: lost in a crash, it is made again
382
+ * by the retried attempt, which runs from what the database holds. So the
383
+ * run writes them ({@link Conversation.flush}) before anything another party
384
+ * sees or that outlives the attempt: a publish, a Restate call of the
385
+ * library, the attempt failing.
386
+ *
387
+ * After each write of steps that commits, the run makes what it was given
388
+ * to make then (`afterCommit`), if anything; not after held rows: they are
389
+ * no step that anyone waits for.
390
+ */
371
391
  class Ledger<I> {
372
392
  /** The latest turn, if loaded whole: the only one that may be written. */
373
393
  latest: Turn<I> | undefined;
@@ -388,6 +408,16 @@ class Ledger<I> {
388
408
  next: number;
389
409
  /** The last `seq` given. */
390
410
  seq: number;
411
+ /** Whether steps that no tool waits for are held ({@link Conversation.hold}), rather than written at once. */
412
+ holds = false;
413
+ /**
414
+ * The rows of the trajectories given positions but not written yet, in
415
+ * order of position ({@link INSERT_STEP}'s parameters): the next write
416
+ * writes them first.
417
+ */
418
+ held: SqlParam[][] = [];
419
+ /** What the run makes after each write of steps that commits ({@link Conversation.hold}), if anything. */
420
+ afterCommit: (() => Promise<void>) | undefined;
391
421
 
392
422
  constructor(db: Database, items: Items<I>, start: Start, transcript: Entry<I>[], next: number, seq: number) {
393
423
  this.db = db;
@@ -413,6 +443,60 @@ class Ledger<I> {
413
443
  if (this.closed) throw new Error('the run was stopped: it stores nothing more');
414
444
  }
415
445
 
446
+ /**
447
+ * Run `body`, a write of the conversation, in one transaction; then
448
+ * `done`, its bookkeeping (the entries it added, an answer's assignment);
449
+ * hold the lock. `body` takes the next position and `seq` as it runs, and
450
+ * sets them past its rows (a framework's copy into the turn, `copyIn`,
451
+ * waits for it, and takes those after).
452
+ *
453
+ * A write and its bookkeeping happen together, or not at all. A commit is
454
+ * stored once it is handed to Restate, before it waits for Restate's
455
+ * acknowledgment: a wait that fails then (one the SDK cancels, say) leaves
456
+ * the rows stored, so `done` runs, and the error is thrown after it.
457
+ * Without it, the ledger would lack what the database holds: a close would
458
+ * give a stored result again, miss a stored call, or close an answered
459
+ * turn. Only a `body` that fails, or a commit the engine refused (SQL: it
460
+ * rolled back), writes nothing, and changes nothing.
461
+ */
462
+ async write(body: (tx: Transaction) => Promise<void>, done: () => void = () => {}): Promise<void> {
463
+ let handed: [next: number, seq: number] | undefined;
464
+ let before: [next: number, seq: number] = [this.next, this.seq];
465
+ // The held rows first, as the write runs (a framework's copy, which it may wait for, writes those it finds):
466
+ // they are no longer held once the write is stored, and still are if it rolls back.
467
+ let held: readonly SqlParam[][] = [];
468
+ const stored = () => {
469
+ this.held = this.held.filter((row) => !held.includes(row));
470
+ done();
471
+ };
472
+ try {
473
+ await this.db.transaction(async (tx) => {
474
+ before = [this.next, this.seq];
475
+ held = this.held;
476
+ await writeHeld(tx, held);
477
+ await body(tx);
478
+ handed = [this.next, this.seq];
479
+ });
480
+ } catch (error) {
481
+ if (handed === undefined) throw error;
482
+ if (rolledBack(error)) {
483
+ // The positions it took are given again, unless a copy took those after them meanwhile.
484
+ if (this.next === handed[0] && this.seq === handed[1]) [this.next, this.seq] = before;
485
+ throw error;
486
+ }
487
+ stored();
488
+ throw error;
489
+ }
490
+ stored();
491
+ }
492
+
493
+ /** Whether `entries`, which are read, are held rather than written: no tool call nor result, in a run that holds. */
494
+ holdsBack(entries: readonly Entry<I>[]) {
495
+ return (
496
+ this.holds && !entries.some((e) => (e.parsed?.calls ?? []).length > 0 || (e.parsed?.results ?? []).length > 0)
497
+ );
498
+ }
499
+
416
500
  /** The agent and the framework's state that the latest answered turn left. */
417
501
  carried(): [agent: string | undefined, carried: string | undefined] {
418
502
  const latest = this.transcript.findLast((turn) => turn.answer !== undefined);
@@ -420,6 +504,19 @@ class Ledger<I> {
420
504
  }
421
505
  }
422
506
 
507
+ /** Write the held rows `held` in `tx`, the same statement for each: the database prepares it once. */
508
+ async function writeHeld(tx: DatabaseWriter, held: readonly SqlParam[][]) {
509
+ for (const row of held) await tx.execute(INSERT_STEP, row);
510
+ }
511
+
512
+ /**
513
+ * Whether a commit that failed was rolled back: the engine refused its SQL
514
+ * (an `SqlError`, which the handler gets as a terminal error). Any other
515
+ * failure of a commit is of its wait for Restate, once its rows were stored.
516
+ */
517
+ const rolledBack = (error: unknown) =>
518
+ error instanceof restate.TerminalError && (error.cause as { name?: unknown } | undefined)?.name === 'SqlError';
519
+
423
520
  /** The index of the first of `entries` (by position) at `n` or after. */
424
521
  const bisect = <I>(entries: readonly Entry<I>[], n: number) => {
425
522
  let low = 0;
@@ -504,7 +601,7 @@ export class Turn<I> {
504
601
 
505
602
  #add(entries: Entry<I>[]) {
506
603
  for (const entry of entries) {
507
- entry.parsed = this.#ledger.items.read(entry.item);
604
+ parsedOf(this.#ledger.items, entry);
508
605
  entry.turn = this.n;
509
606
  this.#index(entry);
510
607
  }
@@ -595,14 +692,39 @@ export class Turn<I> {
595
692
 
596
693
  // Writing: only the latest turn, while it has no answer.
597
694
 
598
- /** Append `items` (a tool's results, say) to the turn, in one transaction; appends at once are each stored after the ones before. */
695
+ /**
696
+ * Append `items` (a tool's results, say) to the turn, in one transaction;
697
+ * appends at once are each stored after the ones before. In
698
+ * `answerOnce`'s run, a write that commits makes what the run makes after
699
+ * a commit ({@link Conversation.hold}).
700
+ */
599
701
  async append(...items: I[]): Promise<void> {
600
- await this.#insert((n) => items.map((item, i) => ({ n: n + i, item })));
702
+ await this.#stored((n) => items.map((item, i) => ({ n: n + i, item })));
601
703
  }
602
704
 
603
- /** Append the model's reply, of `items` (given by `agent`), to the turn, and return its id. */
705
+ /**
706
+ * Append the model's reply, of `items` (given by `agent`), to the turn,
707
+ * and return its id. In `answerOnce`'s run, a reply with tool calls
708
+ * commits, and makes what the run makes after a commit; one without is
709
+ * held, and commits with the next write (the answer, for the final reply).
710
+ */
604
711
  appendReply(items: I[], agent?: string): Promise<number> {
605
- return this.#insert((n) => items.map((item, i) => ({ n: n + i, item, reply: n, agent })));
712
+ return this.#stored((n) => items.map((item, i) => ({ n: n + i, item, reply: n, agent })));
713
+ }
714
+
715
+ /**
716
+ * Make what the turn's run makes after each write of its steps that
717
+ * commits ({@link Conversation.hold}), if anything, for a framework that
718
+ * copies steps into the turn in a transaction of its own ({@link copyIn}):
719
+ * call it once that transaction has committed with steps that a tool
720
+ * waits for (a reply with tool calls, the tools' results), and await it
721
+ * before the framework's next step. `append` and `appendReply` make it
722
+ * themselves. What it makes is the business of whoever runs the turn
723
+ * (`answerOnce` takes it from the `chat` turn it runs in, if any, which
724
+ * publishes there); the conversation only calls it.
725
+ */
726
+ async stepsCommitted(): Promise<void> {
727
+ await this.#ledger.afterCommit?.();
606
728
  }
607
729
 
608
730
  /**
@@ -650,23 +772,27 @@ export class Turn<I> {
650
772
  if (fresh.length === 0) return [];
651
773
  let added: Entry<I>[] = [];
652
774
  // The positions and seqs taken as the write runs, as `#insert` takes them.
653
- await ledger.db.transaction(async (tx) => {
654
- const n = ledger.next;
655
- added = fresh.map((m, i) => ({ n: n + i, item: steeredItem(ledger.items, m.text, m.id), steer: m.id }));
656
- for (const [i, e] of added.entries()) {
657
- await tx.execute(INSERT_STEP, [e.n, this.n, ledger.seq + i + 1, ledger.items.dump(e.item), null, null]);
658
- await tx.execute(INSERT_STEERED, [e.n, this.n, e.steer!]);
659
- }
660
- taken(
661
- tx,
662
- fresh.map((m) => m.id),
663
- );
664
- ledger.seq += added.length;
665
- ledger.next = n + added.length;
666
- });
667
- this.#add(added);
668
- // The transcript's entry of the turn has them too, as the next turn loads it: for its size, say.
669
- (this.prompt.steers ??= []).push(...added);
775
+ await ledger.write(
776
+ async (tx) => {
777
+ const n = ledger.next;
778
+ added = fresh.map((m, i) => ({ n: n + i, item: steeredItem(ledger.items, m.text, m.id), steer: m.id }));
779
+ for (const [i, e] of added.entries()) {
780
+ await tx.execute(INSERT_STEP, [e.n, this.n, ledger.seq + i + 1, ledger.items.dump(e.item), null, null]);
781
+ await tx.execute(INSERT_STEERED, [e.n, this.n, e.steer!]);
782
+ }
783
+ taken(
784
+ tx,
785
+ fresh.map((m) => m.id),
786
+ );
787
+ ledger.seq += added.length;
788
+ ledger.next = n + added.length;
789
+ },
790
+ () => {
791
+ this.#add(added);
792
+ // The transcript's entry of the turn has them too, as the next turn loads it: for its size, say.
793
+ (this.prompt.steers ??= []).push(...added);
794
+ },
795
+ );
670
796
  return added.map((e) => e.item);
671
797
  });
672
798
  }
@@ -697,24 +823,30 @@ export class Turn<I> {
697
823
  await ledger.lock.run(async () => {
698
824
  this.#checkWritable();
699
825
  const start = { ...ledger.start, seq: ledger.seq };
700
- await ledger.db.transaction(async (tx) => {
701
- await tx.execute(`DELETE FROM ${STEPS} WHERE n >= ?`, [reply]);
702
- await tx.execute(`DELETE FROM ${STEERED} WHERE n >= ?`, [reply]);
703
- await restart(tx, start);
704
- });
705
- ledger.start = start;
706
- ledger.next = Math.min(ledger.next, reply);
707
- if (this.prompt.steers) this.prompt.steers = this.prompt.steers.filter((e) => e.n < reply);
708
- const cut = bisect(this.#entries, reply);
709
- const kept = this.#entries.slice(0, cut);
710
- // The dropped calls are not made: their ids may be made again, by the reply that replaces them.
711
- for (const entry of this.#entries.slice(cut))
712
- for (const call of entry.parsed?.calls ?? []) ledger.ids.delete(call.id);
713
- for (const entry of kept) for (const call of entry.parsed?.calls ?? []) ledger.ids.add(call.id);
714
- this.#entries = kept;
715
- this.#results = new Map();
716
- this.#open = [];
717
- for (const entry of kept) this.#index(entry, false);
826
+ // The held rows it drops are never written; those before it are, with the deletes.
827
+ ledger.held = ledger.held.filter((row) => Number(row[0]) < reply);
828
+ await ledger.write(
829
+ async (tx) => {
830
+ await tx.execute(`DELETE FROM ${STEPS} WHERE n >= ?`, [reply]);
831
+ await tx.execute(`DELETE FROM ${STEERED} WHERE n >= ?`, [reply]);
832
+ await restart(tx, start);
833
+ },
834
+ () => {
835
+ ledger.start = start;
836
+ ledger.next = Math.min(ledger.next, reply);
837
+ if (this.prompt.steers) this.prompt.steers = this.prompt.steers.filter((e) => e.n < reply);
838
+ const cut = bisect(this.#entries, reply);
839
+ const kept = this.#entries.slice(0, cut);
840
+ // The dropped calls are not made: their ids may be made again, by the reply that replaces them.
841
+ for (const entry of this.#entries.slice(cut))
842
+ for (const call of entry.parsed?.calls ?? []) ledger.ids.delete(call.id);
843
+ for (const entry of kept) for (const call of entry.parsed?.calls ?? []) ledger.ids.add(call.id);
844
+ this.#entries = kept;
845
+ this.#results = new Map();
846
+ this.#open = [];
847
+ for (const entry of kept) this.#index(entry, false);
848
+ },
849
+ );
718
850
  });
719
851
  }
720
852
 
@@ -723,6 +855,9 @@ export class Turn<I> {
723
855
  * in one update of its row. The answer's message is the assistant's
724
856
  * message the turn ends with; a turn that ends otherwise gets `answer` as
725
857
  * its reply first, and an empty answer gets none.
858
+ *
859
+ * The final reply, which is held (see {@link Ledger}), commits with the
860
+ * update: in one transaction.
726
861
  */
727
862
  async answered(answer: string, status: Status = 'answered') {
728
863
  let at = this.#answerMessage();
@@ -737,12 +872,14 @@ export class Turn<I> {
737
872
  const carried = 'carried' in this.#carried ? this.#carried.carried : ledger.carried()[1];
738
873
  let seq = ledger.seq + 1;
739
874
  // Its seq taken as the write runs, as `#insert` takes its own.
740
- await ledger.db.transaction(async (tx) => {
741
- seq = ledger.seq + 1;
742
- await tx.execute(ANSWER, [status, answer, agent ?? null, carried ?? null, at ?? null, seq, this.n]);
743
- ledger.seq = seq;
744
- });
745
- Object.assign(this.prompt, { status, answer, agent, carried, answeredAt: at, answeredSeq: seq });
875
+ await ledger.write(
876
+ async (tx) => {
877
+ seq = ledger.seq + 1;
878
+ await tx.execute(ANSWER, [status, answer, agent ?? null, carried ?? null, at ?? null, seq, this.n]);
879
+ ledger.seq = seq;
880
+ },
881
+ () => Object.assign(this.prompt, { status, answer, agent, carried, answeredAt: at, answeredSeq: seq }),
882
+ );
746
883
  });
747
884
  }
748
885
 
@@ -808,16 +945,20 @@ export class Turn<I> {
808
945
  const answeredSeq = seq + added.length + 1;
809
946
  const agent = this.#agent();
810
947
  const carried = 'carried' in this.#carried ? this.#carried.carried : ledger.carried()[1];
811
- await ledger.db.transaction(async (tx) => {
812
- for (const [i, e] of added.entries()) {
813
- await tx.execute(INSERT_STEP, [e.n, this.n, seq + i + 1, items.dump(e.item), null, null]);
814
- }
815
- await tx.execute(ANSWER, [status, note, agent ?? null, carried ?? null, at, answeredSeq, this.n]);
816
- });
817
- ledger.next = n + added.length;
818
- ledger.seq = answeredSeq;
819
- this.#add(added);
820
- Object.assign(this.prompt, { status, answer: note, agent, carried, answeredAt: at, answeredSeq });
948
+ await ledger.write(
949
+ async (tx) => {
950
+ for (const [i, e] of added.entries()) {
951
+ await tx.execute(INSERT_STEP, [e.n, this.n, seq + i + 1, items.dump(e.item), null, null]);
952
+ }
953
+ await tx.execute(ANSWER, [status, note, agent ?? null, carried ?? null, at, answeredSeq, this.n]);
954
+ ledger.next = n + added.length;
955
+ ledger.seq = answeredSeq;
956
+ },
957
+ () => {
958
+ this.#add(added);
959
+ Object.assign(this.prompt, { status, answer: note, agent, carried, answeredAt: at, answeredSeq });
960
+ },
961
+ );
821
962
  });
822
963
  }
823
964
 
@@ -853,12 +994,16 @@ export class Turn<I> {
853
994
  ...(reply ? { reply: n + i, agent } : {}),
854
995
  ...(steer === undefined ? {} : { steer }),
855
996
  }));
997
+ // The rows held before it first, in its transaction: they go in the order of their seqs.
998
+ const held = ledger.held;
999
+ ledger.held = [];
856
1000
  // A rolled back transaction fails its attempt, whose state goes with it.
857
1001
  ledger.next = n + added.length;
858
1002
  ledger.seq += added.length;
859
1003
  this.#add(added);
860
1004
  const steered = added.filter((e) => e.steer !== undefined);
861
1005
  if (steered.length > 0) (this.prompt.steers ??= []).push(...steered);
1006
+ await writeHeld(tx, held);
862
1007
  for (const [i, e] of added.entries()) {
863
1008
  await tx.execute(INSERT_STEP, [
864
1009
  e.n,
@@ -886,35 +1031,62 @@ export class Turn<I> {
886
1031
  }
887
1032
  }
888
1033
 
889
- /** Store the entries `made` makes from the next position, and return that position. */
890
- #insert(made: (n: number) => Entry<I>[]): Promise<number> {
1034
+ /**
1035
+ * Store the entries `made` makes ({@link #insert}), and return their
1036
+ * position; then, if they committed (they are not held), make what the run
1037
+ * makes after a commit ({@link stepsCommitted}), outside the lock,
1038
+ * awaited before the caller goes on (a `chat` turn's publish, whose answer
1039
+ * the caller's next step may take). Writes that run at once each make
1040
+ * their own.
1041
+ */
1042
+ async #stored(made: (n: number) => Entry<I>[]): Promise<number> {
1043
+ const [n, held] = await this.#insert(made);
1044
+ if (!held) await this.stepsCommitted();
1045
+ return n;
1046
+ }
1047
+
1048
+ /**
1049
+ * Store the entries `made` makes from the next position, and return that
1050
+ * position, and whether they are held.
1051
+ *
1052
+ * Entries that hold no tool call nor result (a reply that ends the run,
1053
+ * say) are held, not written, in a conversation that holds them (see
1054
+ * {@link Ledger}): no tool waits for them, and the next write writes them.
1055
+ * Tool calls are written before their tools run, and results before the
1056
+ * model is asked again, with the rows held before them.
1057
+ */
1058
+ #insert(made: (n: number) => Entry<I>[]): Promise<[n: number, held: boolean]> {
891
1059
  const ledger = this.#ledger;
892
1060
  return ledger.lock.run(async () => {
893
1061
  this.#checkWritable();
894
- let n = ledger.next;
1062
+ const first = ledger.next;
1063
+ const making = made(first);
1064
+ for (const entry of making) parsedOf(ledger.items, entry);
1065
+ if (ledger.holdsBack(making)) {
1066
+ ledger.held.push(...making.map((e, i) => stepRow(this.n, ledger.seq + i + 1, ledger.items, e)));
1067
+ ledger.seq += making.length;
1068
+ ledger.next = first + making.length;
1069
+ this.#add(making);
1070
+ return [first, true];
1071
+ }
1072
+ let n = first;
895
1073
  let added: Entry<I>[] = [];
896
1074
  // The positions and seqs taken as the write runs: a framework's copy
897
1075
  // into the turn (`copyIn`, in a transaction of its own, which this one
898
1076
  // may wait for) takes those after them, so that they go in the order
899
1077
  // the rows commit in, as a follower's cursor needs.
900
- await ledger.db.transaction(async (tx) => {
901
- n = ledger.next;
902
- added = made(n);
903
- for (const [i, e] of added.entries()) {
904
- await tx.execute(INSERT_STEP, [
905
- e.n,
906
- this.n,
907
- ledger.seq + i + 1,
908
- ledger.items.dump(e.item),
909
- e.reply ?? null,
910
- e.agent ?? null,
911
- ]);
912
- }
913
- ledger.seq += added.length;
914
- ledger.next = n + added.length;
915
- });
916
- this.#add(added);
917
- return n;
1078
+ await ledger.write(
1079
+ async (tx) => {
1080
+ n = ledger.next;
1081
+ added = n === first ? making : made(n);
1082
+ for (const [i, e] of added.entries())
1083
+ await tx.execute(INSERT_STEP, stepRow(this.n, ledger.seq + i + 1, ledger.items, e));
1084
+ ledger.seq += added.length;
1085
+ ledger.next = n + added.length;
1086
+ },
1087
+ () => this.#add(added),
1088
+ );
1089
+ return [n, false];
918
1090
  });
919
1091
  }
920
1092
  }
@@ -1058,6 +1230,16 @@ async function transcriptOf<I>(
1058
1230
  /** Store a step of a turn: its position, its turn's, its `seq`, its item, and the reply and agent it is of. */
1059
1231
  const INSERT_STEP = `INSERT INTO ${STEPS} (n, turn, seq, item, reply, agent) VALUES (?, ?, ?, ?, ?, ?)`;
1060
1232
 
1233
+ /** {@link INSERT_STEP}'s parameters for `entry`, a step of turn `turn` with `seq` `seq`. */
1234
+ const stepRow = <I>(turn: number, seq: number, items: Items<I>, entry: Entry<I>): SqlParam[] => [
1235
+ entry.n,
1236
+ turn,
1237
+ seq,
1238
+ items.dump(entry.item),
1239
+ entry.reply ?? null,
1240
+ entry.agent ?? null,
1241
+ ];
1242
+
1061
1243
  /** Mark the step at a position a message steered to its turn: the position, its turn's, and the message's id. */
1062
1244
  const INSERT_STEERED = `INSERT INTO ${STEERED} (n, turn, id) VALUES (?, ?, ?)`;
1063
1245
 
@@ -1319,20 +1501,62 @@ export class Conversation<I> {
1319
1501
  if (running) throw new Error(`turn ${running.id} has no answer yet: turns never overlap`);
1320
1502
  const n = ledger.next;
1321
1503
  const entry: Entry<I> = { n, item: this.items.prompt(text), prompt: promptId, askedAt: Date.now() };
1322
- await this.db.execute(`INSERT INTO ${TURNS} (n, seq, prompt, item, asked_at) VALUES (?, ?, ?, ?, ?)`, [
1323
- n,
1324
- ledger.seq + 1,
1325
- promptId,
1326
- this.items.dump(entry.item),
1327
- entry.askedAt!,
1328
- ]);
1329
- ledger.seq += 1;
1330
- ledger.next = n + 1;
1331
- ledger.transcript.push(entry);
1332
- const turn = new Turn(ledger, entry);
1333
- this.#turns.push(turn);
1334
- ledger.latest = turn;
1335
- return turn;
1504
+ let turn: Turn<I> | undefined;
1505
+ await ledger.write(
1506
+ async (tx) => {
1507
+ await tx.execute(`INSERT INTO ${TURNS} (n, seq, prompt, item, asked_at) VALUES (?, ?, ?, ?, ?)`, [
1508
+ n,
1509
+ ledger.seq + 1,
1510
+ promptId,
1511
+ this.items.dump(entry.item),
1512
+ entry.askedAt!,
1513
+ ]);
1514
+ ledger.seq += 1;
1515
+ ledger.next = n + 1;
1516
+ },
1517
+ () => {
1518
+ ledger.transcript.push(entry);
1519
+ turn = new Turn(ledger, entry);
1520
+ this.#turns.push(turn);
1521
+ ledger.latest = turn;
1522
+ },
1523
+ );
1524
+ return turn!;
1525
+ });
1526
+ }
1527
+
1528
+ /**
1529
+ * Hold the steps that no tool waits for, rather than write each at once:
1530
+ * the next write writes them (see {@link Ledger}). For a run that writes
1531
+ * them ({@link flush}) before each publish and Restate call of the
1532
+ * library, and before its attempt fails: `answerOnce`'s. A conversation
1533
+ * that is written otherwise (step by step, from handlers of its own)
1534
+ * writes each step as it comes.
1535
+ *
1536
+ * `afterCommit`, if given, is awaited after each write of steps that
1537
+ * commits (a reply with tool calls, the tools' results, with the rows held
1538
+ * before them), outside the lock. The conversation does not know what it
1539
+ * does: `answerOnce` passes what the turn it runs in asked for, if
1540
+ * anything (a followed `chat` turn's publish), so that a framework's
1541
+ * integration publishes nothing by hand. Held rows make none, nor does
1542
+ * `flush`. A framework that copies its steps in a transaction of its own
1543
+ * makes it with {@link Turn.stepsCommitted}.
1544
+ */
1545
+ hold(afterCommit?: () => Promise<void>) {
1546
+ this.#ledger.holds = true;
1547
+ this.#ledger.afterCommit = afterCommit;
1548
+ }
1549
+
1550
+ /**
1551
+ * Write the rows the turn's run holds (see {@link Ledger}), if any: before
1552
+ * whatever another party sees, or outlives the attempt. A publish tells
1553
+ * the clients to read them, and a Restate call is made once, while a held
1554
+ * row would be lost in a crash.
1555
+ */
1556
+ async flush() {
1557
+ const ledger = this.#ledger;
1558
+ await ledger.lock.run(async () => {
1559
+ if (ledger.held.length > 0) await ledger.write(async () => {});
1336
1560
  });
1337
1561
  }
1338
1562
 
@@ -1374,14 +1598,22 @@ export const invocationOf = (promptId: string) => promptId.split(':', 1)[0]!;
1374
1598
  * answer is checked: a message it returns asks the model again with it,
1375
1599
  * once, as a step of the turn ({@link Turn.askAgain}), and the turn's answer
1376
1600
  * is the reply to that. With `reminder`, the model is told it after the
1377
- * prompt ({@link Turn.reminder}), which is stored as it was asked.
1601
+ * prompt ({@link Turn.reminder}), which is stored as it was asked. With
1602
+ * `schemas`, the framework's own tables are applied with the conversation's.
1378
1603
  */
1379
1604
  export async function answerOnce<I>(
1380
1605
  ctx: restate.SessionContext,
1381
1606
  text: string,
1382
1607
  items: Items<I>,
1383
1608
  run: Run<I>,
1384
- options: { window?: Window; budget?: number; check?: Check; reminder?: string; ownHistory?: boolean } = {},
1609
+ options: {
1610
+ window?: Window;
1611
+ budget?: number;
1612
+ check?: Check;
1613
+ reminder?: string;
1614
+ ownHistory?: boolean;
1615
+ schemas?: readonly Schema[];
1616
+ } = {},
1385
1617
  ): Promise<string> {
1386
1618
  const settings = settingsOf(ctx);
1387
1619
  // One framework per agent (D7): its conversation holds its `messages` view's items, which another can't read.
@@ -1397,11 +1629,26 @@ export async function answerOnce<I>(
1397
1629
  const window = own ? 0 : checkWindow(options.window ?? settings.window);
1398
1630
  const budget = own ? 0 : (options.budget ?? settings.budget);
1399
1631
  const promptId = nextPromptId(ctx);
1400
- await SCHEMA.ensure(ctx.db);
1632
+ // With the tool calls' (calls.ts), which the turn reads as it ends whether
1633
+ // or not a tool ran, and the framework's own (`schemas`): a key's first
1634
+ // turn applies them in one commit, rather than one each.
1635
+ await ensureSchemas(ctx.db, [SCHEMA, CALLS, ...(options.schemas ?? [])]);
1401
1636
  const stored = await answerIn(ctx.db, promptId);
1402
1637
  // Answered (or closed) already: a retry answers, or fails, as the turn ended.
1403
1638
  if (stored !== undefined) return storedAnswer(stored.answer, stored.status);
1404
1639
  const conversation = await Conversation.load(ctx.db, items, window, budget);
1640
+ // The turn's final reply commits with its answer; the library's publishes and Restate calls write what the
1641
+ // run holds back first (`flushHeld`). After each write of steps that commits, the run makes what the turn it
1642
+ // runs in asked for, if anything (a `chat` turn's publish, which this does not know of): a turn outside one
1643
+ // stores its steps, and that is all.
1644
+ // Before it, the call records whose results the commit stored are forgotten (calls.ts): once per commit, for
1645
+ // every turn.
1646
+ const afterSteps = afterStepsOf(ctx);
1647
+ conversation.hold(async () => {
1648
+ await settleAnswered(ctx);
1649
+ await afterSteps?.();
1650
+ });
1651
+ holding(ctx, () => conversation.flush());
1405
1652
  const answered = await forPrompt(ctx, promptId, () =>
1406
1653
  answering(
1407
1654
  ctx,
@@ -1486,6 +1733,11 @@ async function answerTurn<I>(
1486
1733
  await close(turn, 'failed', `Error: ${error.message}`);
1487
1734
  throw error;
1488
1735
  }
1736
+ // The attempt fails, and its retry goes on from what is stored: so what
1737
+ // the run made so far is, as when each step was written as it came.
1738
+ // Never in place of the attempt's own error: its session may have ended
1739
+ // with it, and then nothing more is stored.
1740
+ await conversation.flush().catch(() => {});
1489
1741
  throw error;
1490
1742
  }
1491
1743
  await turn.answered(answered);
@@ -141,7 +141,13 @@ The harness keeps its own event log, and its model's input is the harness's;
141
141
  each flush of the log copies the turn's new messages (the model's replies,
142
142
  the tools' results) into the agent's conversation of turns, in the same
143
143
  transaction: what `messages` shows
144
- ([docs/conversation.md](../../docs/conversation.md)). The harness's input
144
+ ([docs/conversation.md](../../docs/conversation.md)). A flush that copied a
145
+ reply with tool calls, or tools' results, is published once it is stored,
146
+ in a `chat` turn (a `prompt()` in a handler of your own publishes nothing),
147
+ 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
150
+ publish, per tool call. The harness's input
145
151
  stays within the model's context window: as it nears the window (or
146
152
  overflows it), the harness condenses the oldest history into a summary, one
147
153
  more model request, after trimming tool results that are too long