@restatedev/agents 0.4.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.
- package/README.md +104 -38
- package/dist/calls.d.ts +20 -1
- package/dist/calls.d.ts.map +1 -1
- package/dist/calls.js +46 -7
- package/dist/calls.js.map +1 -1
- package/dist/claude/index.d.ts +11 -11
- package/dist/claude/index.d.ts.map +1 -1
- package/dist/claude/index.js +9 -6
- package/dist/claude/index.js.map +1 -1
- package/dist/client.d.ts +1 -1
- package/dist/client.d.ts.map +1 -1
- package/dist/common.d.ts +62 -23
- package/dist/common.d.ts.map +1 -1
- package/dist/common.js +67 -38
- package/dist/common.js.map +1 -1
- package/dist/{signals.d.ts → companion.d.ts} +106 -43
- package/dist/companion.d.ts.map +1 -0
- package/dist/companion.js +463 -0
- package/dist/companion.js.map +1 -0
- package/dist/conversation.d.ts +115 -5
- package/dist/conversation.d.ts.map +1 -1
- package/dist/conversation.js +308 -79
- package/dist/conversation.js.map +1 -1
- package/dist/deepseek/index.d.ts +11 -11
- package/dist/deepseek/index.d.ts.map +1 -1
- package/dist/deepseek/index.js +23 -26
- package/dist/deepseek/index.js.map +1 -1
- package/dist/index.d.ts +8 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -3
- package/dist/index.js.map +1 -1
- package/dist/langgraph/checkpointer.d.ts +2 -0
- package/dist/langgraph/checkpointer.d.ts.map +1 -1
- package/dist/langgraph/checkpointer.js +1 -1
- package/dist/langgraph/checkpointer.js.map +1 -1
- package/dist/langgraph/graph.d.ts.map +1 -1
- package/dist/langgraph/graph.js +32 -13
- package/dist/langgraph/graph.js.map +1 -1
- package/dist/langgraph/index.d.ts +11 -11
- package/dist/langgraph/index.d.ts.map +1 -1
- package/dist/langgraph/index.js +19 -13
- package/dist/langgraph/index.js.map +1 -1
- package/dist/langgraph/nodes.d.ts +2 -1
- package/dist/langgraph/nodes.d.ts.map +1 -1
- package/dist/langgraph/nodes.js +23 -20
- package/dist/langgraph/nodes.js.map +1 -1
- package/dist/object.d.ts +24 -22
- package/dist/object.d.ts.map +1 -1
- package/dist/object.js +16 -11
- package/dist/object.js.map +1 -1
- package/dist/opencode/db.d.ts +81 -0
- package/dist/opencode/db.d.ts.map +1 -0
- package/dist/opencode/db.js +249 -0
- package/dist/opencode/db.js.map +1 -0
- package/dist/opencode/index.d.ts +184 -0
- package/dist/opencode/index.d.ts.map +1 -0
- package/dist/opencode/index.js +982 -0
- package/dist/opencode/index.js.map +1 -0
- package/dist/pi/index.d.ts +11 -11
- package/dist/pi/index.d.ts.map +1 -1
- package/dist/pi/index.js +16 -17
- package/dist/pi/index.js.map +1 -1
- package/dist/steering.d.ts +2 -1
- package/dist/steering.d.ts.map +1 -1
- package/dist/steering.js +2 -2
- package/dist/steering.js.map +1 -1
- package/dist/tools.d.ts +21 -0
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +54 -14
- package/dist/tools.js.map +1 -1
- package/dist/webhook.js +1 -1
- package/dist/webhook.js.map +1 -1
- package/package.json +37 -4
- package/src/calls.ts +52 -11
- package/src/claude/README.md +4 -2
- package/src/claude/index.ts +9 -7
- package/src/client.ts +1 -1
- package/src/common.ts +99 -40
- package/src/companion.ts +674 -0
- package/src/conversation.ts +377 -105
- package/src/deepseek/README.md +7 -1
- package/src/deepseek/index.ts +22 -24
- package/src/index.ts +10 -4
- package/src/langgraph/README.md +8 -5
- package/src/langgraph/checkpointer.ts +1 -1
- package/src/langgraph/graph.ts +30 -16
- package/src/langgraph/index.ts +24 -17
- package/src/langgraph/nodes.ts +24 -20
- package/src/object.ts +45 -40
- package/src/opencode/README.md +234 -0
- package/src/opencode/db.ts +387 -0
- package/src/opencode/index.ts +1243 -0
- package/src/pi/README.md +6 -1
- package/src/pi/index.ts +16 -15
- package/src/steering.ts +8 -7
- package/src/tools.ts +60 -18
- package/src/webhook.ts +1 -1
- package/dist/signals.d.ts.map +0 -1
- package/dist/signals.js +0 -383
- package/dist/signals.js.map +0 -1
- package/src/signals.ts +0 -590
package/src/conversation.ts
CHANGED
|
@@ -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
|
|
28
|
-
//
|
|
29
|
-
//
|
|
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,
|
|
@@ -185,6 +188,18 @@ export interface Items<I> {
|
|
|
185
188
|
* the id `steer:<steerId>`); by default, a prompt's item.
|
|
186
189
|
*/
|
|
187
190
|
steered?(text: string, steerId: string): I;
|
|
191
|
+
/**
|
|
192
|
+
* For a framework whose history is in a store of its own that the turn is
|
|
193
|
+
* copied from after the fact (OpenCode's): bring that store to the turn's
|
|
194
|
+
* end, and copy what it has of the turn into it, before the turn is
|
|
195
|
+
* closed with `status`. `answerOnce` and `settle` call it before each
|
|
196
|
+
* close, so that the framework's store is closed first, then the copy,
|
|
197
|
+
* then the turn. A framework whose copy is in its own transaction (pi,
|
|
198
|
+
* DeepSeek) has none.
|
|
199
|
+
*/
|
|
200
|
+
settleOwn?(ctx: restate.SessionContext, turn: Turn<I>, status: Status): Promise<void>;
|
|
201
|
+
/** For a framework with a database of its own beside `ctx.db`: forget it, as `clear` empties the key's. */
|
|
202
|
+
erase?(ctx: restate.SessionContext): Promise<void>;
|
|
188
203
|
}
|
|
189
204
|
|
|
190
205
|
/** What the user's message with the summary of the earliest turns starts with. */
|
|
@@ -355,7 +370,24 @@ class Lock {
|
|
|
355
370
|
}
|
|
356
371
|
}
|
|
357
372
|
|
|
358
|
-
/**
|
|
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
|
+
*/
|
|
359
391
|
class Ledger<I> {
|
|
360
392
|
/** The latest turn, if loaded whole: the only one that may be written. */
|
|
361
393
|
latest: Turn<I> | undefined;
|
|
@@ -376,6 +408,16 @@ class Ledger<I> {
|
|
|
376
408
|
next: number;
|
|
377
409
|
/** The last `seq` given. */
|
|
378
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;
|
|
379
421
|
|
|
380
422
|
constructor(db: Database, items: Items<I>, start: Start, transcript: Entry<I>[], next: number, seq: number) {
|
|
381
423
|
this.db = db;
|
|
@@ -401,6 +443,60 @@ class Ledger<I> {
|
|
|
401
443
|
if (this.closed) throw new Error('the run was stopped: it stores nothing more');
|
|
402
444
|
}
|
|
403
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
|
+
|
|
404
500
|
/** The agent and the framework's state that the latest answered turn left. */
|
|
405
501
|
carried(): [agent: string | undefined, carried: string | undefined] {
|
|
406
502
|
const latest = this.transcript.findLast((turn) => turn.answer !== undefined);
|
|
@@ -408,6 +504,19 @@ class Ledger<I> {
|
|
|
408
504
|
}
|
|
409
505
|
}
|
|
410
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
|
+
|
|
411
520
|
/** The index of the first of `entries` (by position) at `n` or after. */
|
|
412
521
|
const bisect = <I>(entries: readonly Entry<I>[], n: number) => {
|
|
413
522
|
let low = 0;
|
|
@@ -492,7 +601,7 @@ export class Turn<I> {
|
|
|
492
601
|
|
|
493
602
|
#add(entries: Entry<I>[]) {
|
|
494
603
|
for (const entry of entries) {
|
|
495
|
-
|
|
604
|
+
parsedOf(this.#ledger.items, entry);
|
|
496
605
|
entry.turn = this.n;
|
|
497
606
|
this.#index(entry);
|
|
498
607
|
}
|
|
@@ -583,14 +692,39 @@ export class Turn<I> {
|
|
|
583
692
|
|
|
584
693
|
// Writing: only the latest turn, while it has no answer.
|
|
585
694
|
|
|
586
|
-
/**
|
|
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
|
+
*/
|
|
587
701
|
async append(...items: I[]): Promise<void> {
|
|
588
|
-
await this.#
|
|
702
|
+
await this.#stored((n) => items.map((item, i) => ({ n: n + i, item })));
|
|
589
703
|
}
|
|
590
704
|
|
|
591
|
-
/**
|
|
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
|
+
*/
|
|
592
711
|
appendReply(items: I[], agent?: string): Promise<number> {
|
|
593
|
-
return this.#
|
|
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?.();
|
|
594
728
|
}
|
|
595
729
|
|
|
596
730
|
/**
|
|
@@ -638,23 +772,27 @@ export class Turn<I> {
|
|
|
638
772
|
if (fresh.length === 0) return [];
|
|
639
773
|
let added: Entry<I>[] = [];
|
|
640
774
|
// The positions and seqs taken as the write runs, as `#insert` takes them.
|
|
641
|
-
await ledger.
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
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
|
+
);
|
|
658
796
|
return added.map((e) => e.item);
|
|
659
797
|
});
|
|
660
798
|
}
|
|
@@ -685,24 +823,30 @@ export class Turn<I> {
|
|
|
685
823
|
await ledger.lock.run(async () => {
|
|
686
824
|
this.#checkWritable();
|
|
687
825
|
const start = { ...ledger.start, seq: ledger.seq };
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
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
|
+
);
|
|
706
850
|
});
|
|
707
851
|
}
|
|
708
852
|
|
|
@@ -711,6 +855,9 @@ export class Turn<I> {
|
|
|
711
855
|
* in one update of its row. The answer's message is the assistant's
|
|
712
856
|
* message the turn ends with; a turn that ends otherwise gets `answer` as
|
|
713
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.
|
|
714
861
|
*/
|
|
715
862
|
async answered(answer: string, status: Status = 'answered') {
|
|
716
863
|
let at = this.#answerMessage();
|
|
@@ -725,12 +872,14 @@ export class Turn<I> {
|
|
|
725
872
|
const carried = 'carried' in this.#carried ? this.#carried.carried : ledger.carried()[1];
|
|
726
873
|
let seq = ledger.seq + 1;
|
|
727
874
|
// Its seq taken as the write runs, as `#insert` takes its own.
|
|
728
|
-
await ledger.
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
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
|
+
);
|
|
734
883
|
});
|
|
735
884
|
}
|
|
736
885
|
|
|
@@ -796,16 +945,20 @@ export class Turn<I> {
|
|
|
796
945
|
const answeredSeq = seq + added.length + 1;
|
|
797
946
|
const agent = this.#agent();
|
|
798
947
|
const carried = 'carried' in this.#carried ? this.#carried.carried : ledger.carried()[1];
|
|
799
|
-
await ledger.
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
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
|
+
);
|
|
809
962
|
});
|
|
810
963
|
}
|
|
811
964
|
|
|
@@ -841,12 +994,16 @@ export class Turn<I> {
|
|
|
841
994
|
...(reply ? { reply: n + i, agent } : {}),
|
|
842
995
|
...(steer === undefined ? {} : { steer }),
|
|
843
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 = [];
|
|
844
1000
|
// A rolled back transaction fails its attempt, whose state goes with it.
|
|
845
1001
|
ledger.next = n + added.length;
|
|
846
1002
|
ledger.seq += added.length;
|
|
847
1003
|
this.#add(added);
|
|
848
1004
|
const steered = added.filter((e) => e.steer !== undefined);
|
|
849
1005
|
if (steered.length > 0) (this.prompt.steers ??= []).push(...steered);
|
|
1006
|
+
await writeHeld(tx, held);
|
|
850
1007
|
for (const [i, e] of added.entries()) {
|
|
851
1008
|
await tx.execute(INSERT_STEP, [
|
|
852
1009
|
e.n,
|
|
@@ -874,35 +1031,62 @@ export class Turn<I> {
|
|
|
874
1031
|
}
|
|
875
1032
|
}
|
|
876
1033
|
|
|
877
|
-
/**
|
|
878
|
-
|
|
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]> {
|
|
879
1059
|
const ledger = this.#ledger;
|
|
880
1060
|
return ledger.lock.run(async () => {
|
|
881
1061
|
this.#checkWritable();
|
|
882
|
-
|
|
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;
|
|
883
1073
|
let added: Entry<I>[] = [];
|
|
884
1074
|
// The positions and seqs taken as the write runs: a framework's copy
|
|
885
1075
|
// into the turn (`copyIn`, in a transaction of its own, which this one
|
|
886
1076
|
// may wait for) takes those after them, so that they go in the order
|
|
887
1077
|
// the rows commit in, as a follower's cursor needs.
|
|
888
|
-
await ledger.
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
}
|
|
901
|
-
ledger.seq += added.length;
|
|
902
|
-
ledger.next = n + added.length;
|
|
903
|
-
});
|
|
904
|
-
this.#add(added);
|
|
905
|
-
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];
|
|
906
1090
|
});
|
|
907
1091
|
}
|
|
908
1092
|
}
|
|
@@ -1046,6 +1230,16 @@ async function transcriptOf<I>(
|
|
|
1046
1230
|
/** Store a step of a turn: its position, its turn's, its `seq`, its item, and the reply and agent it is of. */
|
|
1047
1231
|
const INSERT_STEP = `INSERT INTO ${STEPS} (n, turn, seq, item, reply, agent) VALUES (?, ?, ?, ?, ?, ?)`;
|
|
1048
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
|
+
|
|
1049
1243
|
/** Mark the step at a position a message steered to its turn: the position, its turn's, and the message's id. */
|
|
1050
1244
|
const INSERT_STEERED = `INSERT INTO ${STEERED} (n, turn, id) VALUES (?, ?, ?)`;
|
|
1051
1245
|
|
|
@@ -1307,20 +1501,62 @@ export class Conversation<I> {
|
|
|
1307
1501
|
if (running) throw new Error(`turn ${running.id} has no answer yet: turns never overlap`);
|
|
1308
1502
|
const n = ledger.next;
|
|
1309
1503
|
const entry: Entry<I> = { n, item: this.items.prompt(text), prompt: promptId, askedAt: Date.now() };
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
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 () => {});
|
|
1324
1560
|
});
|
|
1325
1561
|
}
|
|
1326
1562
|
|
|
@@ -1362,14 +1598,22 @@ export const invocationOf = (promptId: string) => promptId.split(':', 1)[0]!;
|
|
|
1362
1598
|
* answer is checked: a message it returns asks the model again with it,
|
|
1363
1599
|
* once, as a step of the turn ({@link Turn.askAgain}), and the turn's answer
|
|
1364
1600
|
* is the reply to that. With `reminder`, the model is told it after the
|
|
1365
|
-
* 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.
|
|
1366
1603
|
*/
|
|
1367
1604
|
export async function answerOnce<I>(
|
|
1368
1605
|
ctx: restate.SessionContext,
|
|
1369
1606
|
text: string,
|
|
1370
1607
|
items: Items<I>,
|
|
1371
1608
|
run: Run<I>,
|
|
1372
|
-
options: {
|
|
1609
|
+
options: {
|
|
1610
|
+
window?: Window;
|
|
1611
|
+
budget?: number;
|
|
1612
|
+
check?: Check;
|
|
1613
|
+
reminder?: string;
|
|
1614
|
+
ownHistory?: boolean;
|
|
1615
|
+
schemas?: readonly Schema[];
|
|
1616
|
+
} = {},
|
|
1373
1617
|
): Promise<string> {
|
|
1374
1618
|
const settings = settingsOf(ctx);
|
|
1375
1619
|
// One framework per agent (D7): its conversation holds its `messages` view's items, which another can't read.
|
|
@@ -1385,11 +1629,26 @@ export async function answerOnce<I>(
|
|
|
1385
1629
|
const window = own ? 0 : checkWindow(options.window ?? settings.window);
|
|
1386
1630
|
const budget = own ? 0 : (options.budget ?? settings.budget);
|
|
1387
1631
|
const promptId = nextPromptId(ctx);
|
|
1388
|
-
|
|
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 ?? [])]);
|
|
1389
1636
|
const stored = await answerIn(ctx.db, promptId);
|
|
1390
1637
|
// Answered (or closed) already: a retry answers, or fails, as the turn ended.
|
|
1391
1638
|
if (stored !== undefined) return storedAnswer(stored.answer, stored.status);
|
|
1392
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());
|
|
1393
1652
|
const answered = await forPrompt(ctx, promptId, () =>
|
|
1394
1653
|
answering(
|
|
1395
1654
|
ctx,
|
|
@@ -1420,10 +1679,17 @@ async function answerTurn<I>(
|
|
|
1420
1679
|
check: Check | undefined,
|
|
1421
1680
|
reminder: string | undefined,
|
|
1422
1681
|
): Promise<string> {
|
|
1682
|
+
const { items } = conversation;
|
|
1683
|
+
/** Close `closed` with `status` and `note`: the framework's own store first, if it has one. */
|
|
1684
|
+
const close = async (closed: Turn<I>, status: Status, note: string) => {
|
|
1685
|
+
if (closed.status !== undefined) return;
|
|
1686
|
+
await items.settleOwn?.(ctx, closed, status);
|
|
1687
|
+
await closed.close(ctx, status, note);
|
|
1688
|
+
};
|
|
1423
1689
|
let running = conversation.running();
|
|
1424
1690
|
if (running && running.id !== promptId) {
|
|
1425
1691
|
// Turns never overlap, so the invocation of this one is gone: it ends unanswered.
|
|
1426
|
-
await
|
|
1692
|
+
await close(running, 'ended', ENDED);
|
|
1427
1693
|
running = undefined;
|
|
1428
1694
|
}
|
|
1429
1695
|
const turn = running ?? (await conversation.ask(promptId, text));
|
|
@@ -1449,7 +1715,7 @@ async function answerTurn<I>(
|
|
|
1449
1715
|
if (error instanceof AttemptEnded) throw error; // the next attempt goes on with the run
|
|
1450
1716
|
if (error instanceof restate.CancelledError) {
|
|
1451
1717
|
// Cancelled: close the turn, so that the next prompt starts afresh.
|
|
1452
|
-
await
|
|
1718
|
+
await close(turn, 'cancelled', CANCELLED);
|
|
1453
1719
|
await conversation.seal();
|
|
1454
1720
|
throw error;
|
|
1455
1721
|
}
|
|
@@ -1459,14 +1725,19 @@ async function answerTurn<I>(
|
|
|
1459
1725
|
const refused =
|
|
1460
1726
|
error instanceof restate.TerminalError ? (error.code === REFUSED ? error : undefined) : refusalOf(ctx, error);
|
|
1461
1727
|
if (refused) {
|
|
1462
|
-
await
|
|
1728
|
+
await close(turn, 'refused', UNANSWERED);
|
|
1463
1729
|
throw refused;
|
|
1464
1730
|
}
|
|
1465
1731
|
if (error instanceof restate.TerminalError) {
|
|
1466
1732
|
// Failed for good: closed with the error, so that the next prompt does not run into it again.
|
|
1467
|
-
await
|
|
1733
|
+
await close(turn, 'failed', `Error: ${error.message}`);
|
|
1468
1734
|
throw error;
|
|
1469
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(() => {});
|
|
1470
1741
|
throw error;
|
|
1471
1742
|
}
|
|
1472
1743
|
await turn.answered(answered);
|
|
@@ -1485,6 +1756,7 @@ export async function settle<I>(ctx: restate.SessionContext, items: Items<I>, in
|
|
|
1485
1756
|
if (!row || row.status !== null || invocationOf(String(row.prompt)) !== invocationId) return false;
|
|
1486
1757
|
const running = (await Conversation.load(ctx.db, items, 0)).running();
|
|
1487
1758
|
if (!running) return false;
|
|
1759
|
+
await items.settleOwn?.(ctx, running, 'ended');
|
|
1488
1760
|
await running.close(ctx, 'ended', ENDED);
|
|
1489
1761
|
return true;
|
|
1490
1762
|
}
|