@restatedev/agents 0.11.0 → 0.11.2
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/dist/calls.d.ts +15 -0
- package/dist/calls.d.ts.map +1 -1
- package/dist/calls.js +46 -9
- package/dist/calls.js.map +1 -1
- package/dist/common.d.ts.map +1 -1
- package/dist/common.js +4 -1
- package/dist/common.js.map +1 -1
- package/dist/deepseek/barriers.d.ts +11 -0
- package/dist/deepseek/barriers.d.ts.map +1 -0
- package/dist/deepseek/barriers.js +36 -0
- package/dist/deepseek/barriers.js.map +1 -0
- package/dist/deepseek/index.d.ts.map +1 -1
- package/dist/deepseek/index.js +45 -14
- package/dist/deepseek/index.js.map +1 -1
- package/dist/deepseek/persistence.d.ts +16 -0
- package/dist/deepseek/persistence.d.ts.map +1 -1
- package/dist/deepseek/persistence.js +33 -1
- package/dist/deepseek/persistence.js.map +1 -1
- package/dist/langgraph/checkpointer.d.ts +8 -1
- package/dist/langgraph/checkpointer.d.ts.map +1 -1
- package/dist/langgraph/checkpointer.js +117 -31
- package/dist/langgraph/checkpointer.js.map +1 -1
- package/dist/langgraph/graph.d.ts.map +1 -1
- package/dist/langgraph/graph.js +7 -2
- package/dist/langgraph/graph.js.map +1 -1
- package/dist/opencode/index.d.ts.map +1 -1
- package/dist/opencode/index.js +21 -1
- package/dist/opencode/index.js.map +1 -1
- package/package.json +3 -3
- package/src/calls.ts +65 -11
- package/src/common.ts +4 -1
- package/src/deepseek/README.md +24 -5
- package/src/deepseek/barriers.ts +63 -0
- package/src/deepseek/index.ts +48 -13
- package/src/deepseek/persistence.ts +47 -6
- package/src/langgraph/README.md +9 -0
- package/src/langgraph/checkpointer.ts +134 -35
- package/src/langgraph/graph.ts +7 -2
- package/src/opencode/index.ts +20 -1
package/src/deepseek/index.ts
CHANGED
|
@@ -17,9 +17,13 @@
|
|
|
17
17
|
//
|
|
18
18
|
// The handler is not replayed: a retried attempt (a crash, a lost connection)
|
|
19
19
|
// boots the harness again and resumes the session from the stored log.
|
|
20
|
-
// - The
|
|
21
|
-
//
|
|
22
|
-
//
|
|
20
|
+
// - The log is stored before each model request and before each tool body:
|
|
21
|
+
// a tool runs only once its call is stored. The harness's session
|
|
22
|
+
// checkpoint policy flushes there, but its flushes are soft (persistence.ts)
|
|
23
|
+
// once the adapter's own barriers are in place (barriers.ts): they store
|
|
24
|
+
// what the harness queued right before each of those effects, before each
|
|
25
|
+
// Restate effect and publish, and when the run ends. So back-to-back flushes
|
|
26
|
+
// with no effect between them are one commit.
|
|
23
27
|
// - A crash leaves the turn open. Resuming closes it, and gives each tool
|
|
24
28
|
// call that was stored without a result an error result saying its outcome
|
|
25
29
|
// is unknown; the handler then asks the agent to continue. The model sees
|
|
@@ -85,6 +89,9 @@ import { type Answer, withChecked } from '../output.ts';
|
|
|
85
89
|
import { type Definition, sessionObject } from '../object.ts';
|
|
86
90
|
import { type Approval, isTool, jsonSchemaOf, type Tool as AnyTool, waitFor } from '../tools.ts';
|
|
87
91
|
import type { z } from 'zod';
|
|
92
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
93
|
+
import { holding } from '../calls.ts';
|
|
94
|
+
import { guardModelRequests } from './barriers.ts';
|
|
88
95
|
import { SqlSessionPersistence } from './persistence.ts';
|
|
89
96
|
|
|
90
97
|
export { SqlSessionPersistence };
|
|
@@ -309,7 +316,8 @@ const decided = (value: unknown): ApprovalOutcome => (approves(value) ? 'allowed
|
|
|
309
316
|
* person is asked once. The wait is an approval (`approval`): a stopped
|
|
310
317
|
* turn does not report its call as done because it was approved. An error
|
|
311
318
|
* of the wait fails the attempt (`fail`), and its ask never ends: the
|
|
312
|
-
* harness does not go on without a decision.
|
|
319
|
+
* harness does not go on without a decision. The wait stores nothing queued
|
|
320
|
+
* (the call's reply), unlike other Restate effects (see `UNSTORED`).
|
|
313
321
|
*/
|
|
314
322
|
function approving(agentCtx: Context, ctx: restate.SessionContext, approval: Approval, fail: (error: unknown) => void) {
|
|
315
323
|
const needs = typeof approval === 'function' ? approval : ({ name }: { name: string }) => approval.includes(name);
|
|
@@ -329,8 +337,13 @@ function approving(agentCtx: Context, ctx: restate.SessionContext, approval: App
|
|
|
329
337
|
try {
|
|
330
338
|
// The calls whose results are stored are forgotten first: an earlier
|
|
331
339
|
// attempt's call with the same arguments, approved and done, is not this one.
|
|
332
|
-
|
|
333
|
-
return decided(
|
|
340
|
+
// Forgetting one is a write, which stores nothing queued either (`UNSTORED`).
|
|
341
|
+
return decided(
|
|
342
|
+
await UNSTORED.run(true, async () => {
|
|
343
|
+
await toolCallStarted(ctx);
|
|
344
|
+
return waitFor(ctx, callId, APPROVAL, call, { approval: true, rejoin: true });
|
|
345
|
+
}),
|
|
346
|
+
);
|
|
334
347
|
} catch (error) {
|
|
335
348
|
fromTool(ctx, error);
|
|
336
349
|
fail(error);
|
|
@@ -339,6 +352,14 @@ function approving(agentCtx: Context, ctx: restate.SessionContext, approval: App
|
|
|
339
352
|
});
|
|
340
353
|
}
|
|
341
354
|
|
|
355
|
+
/**
|
|
356
|
+
* Where the writes before a Restate effect (`holding`) are not made: a publish
|
|
357
|
+
* right after a write (`flushed`), which has nothing more to show, and an
|
|
358
|
+
* approval's wait, whose tool call is not stored until the person decides (see
|
|
359
|
+
* {@link approving}).
|
|
360
|
+
*/
|
|
361
|
+
const UNSTORED = new AsyncLocalStorage<true>();
|
|
362
|
+
|
|
342
363
|
/** An agent's options: `chat` and `prompt` take them. */
|
|
343
364
|
export interface Options<O extends z.ZodObject | undefined = z.ZodObject | undefined> {
|
|
344
365
|
/**
|
|
@@ -514,6 +535,8 @@ const runOf =
|
|
|
514
535
|
stop?.addEventListener('abort', onStop, { once: true });
|
|
515
536
|
let agent: Agent | undefined;
|
|
516
537
|
let unlisten: (() => void) | undefined;
|
|
538
|
+
// Whether the tools are registered behind a barrier (`tracked`), once `setup` has.
|
|
539
|
+
let toolsGuarded = false;
|
|
517
540
|
// The turn asked again (its output's check, say): the harness is asked that, and answers it.
|
|
518
541
|
const asked = turn.latestAsk();
|
|
519
542
|
const again = asked !== turn.prompt;
|
|
@@ -522,10 +545,12 @@ const runOf =
|
|
|
522
545
|
let from: number | undefined;
|
|
523
546
|
try {
|
|
524
547
|
const sessionId = SessionId(ctx.key);
|
|
548
|
+
const stored = () => persistence.writeNow(sessionId);
|
|
525
549
|
const options = {
|
|
526
550
|
agentOptions: route,
|
|
527
551
|
setup: (agentCtx: Context) => {
|
|
528
|
-
for (const t of tools) agentCtx.tools.register(tracked(isTool(t) ? native(t, ctx) : t, ctx, fail));
|
|
552
|
+
for (const t of tools) agentCtx.tools.register(tracked(isTool(t) ? native(t, ctx) : t, ctx, fail, stored));
|
|
553
|
+
toolsGuarded = true;
|
|
529
554
|
if (approval !== undefined) approving(agentCtx, ctx, approval, fail);
|
|
530
555
|
},
|
|
531
556
|
};
|
|
@@ -534,6 +559,11 @@ const runOf =
|
|
|
534
559
|
? await harness.agents.resume({ resumeSessionId: sessionId, ...options })
|
|
535
560
|
: await harness.agents.create({ sessionId, ...options });
|
|
536
561
|
agent = started.agent;
|
|
562
|
+
// The harness's flushes are soft only with every barrier in place: the tools' (`tracked`), the model
|
|
563
|
+
// requests' (the innermost `llm/stream` listener), and what is stored before each Restate effect and
|
|
564
|
+
// publish (`holding`). Any one missing, they stay writes.
|
|
565
|
+
holding(ctx, async () => (UNSTORED.getStore() ? undefined : stored()), 'deepseek');
|
|
566
|
+
persistence.barriered = guardModelRequests(harness, persistence) && toolsGuarded;
|
|
537
567
|
const found = agent.session.snapshotEvents().length;
|
|
538
568
|
from = agent.session.snapshotEvents().find((e) => e.type === 'user/message' && e.data.id === id)?.seq;
|
|
539
569
|
// A flush that copied steps (a reply with tool calls, tools' results) is published once it is stored,
|
|
@@ -563,7 +593,7 @@ const runOf =
|
|
|
563
593
|
if (!copiedSteps) return;
|
|
564
594
|
copiedSteps = false;
|
|
565
595
|
// Failing, it fails the attempt, as a tool's error does: never the flush, which is done.
|
|
566
|
-
await turn.stepsCommitted().catch(fail);
|
|
596
|
+
await UNSTORED.run(true, () => turn.stepsCommitted()).catch(fail);
|
|
567
597
|
};
|
|
568
598
|
// The messages steered to the turn, handed to the harness's step inbox as a publish lists them: only
|
|
569
599
|
// once a reply with tool calls or a result is stored, so that a step after them places them, in this turn.
|
|
@@ -593,14 +623,15 @@ const runOf =
|
|
|
593
623
|
const ask = again ? message(id, textOf(asked.item)) : promptOf(turn, before);
|
|
594
624
|
agent.followup(end.asked ? message(`continue:${events.length}`, CONTINUE) : ask);
|
|
595
625
|
await Promise.race([agent.whenIdle(), failed]);
|
|
596
|
-
await
|
|
626
|
+
await stored();
|
|
597
627
|
}
|
|
598
628
|
} catch (e) {
|
|
599
629
|
// A cancelled invocation cancels the agent's turn, which the log keeps.
|
|
600
|
-
if (e instanceof restate.CancelledError && agent) await cancelTurn(
|
|
630
|
+
if (e instanceof restate.CancelledError && agent) await cancelTurn(agent, persistence, SessionId(ctx.key));
|
|
601
631
|
else persistence.abandon();
|
|
602
632
|
throw e;
|
|
603
633
|
} finally {
|
|
634
|
+
holding(ctx, undefined, 'deepseek');
|
|
604
635
|
unlisten?.();
|
|
605
636
|
stop?.removeEventListener('abort', onStop);
|
|
606
637
|
await harness.fiber.dispose();
|
|
@@ -608,25 +639,29 @@ const runOf =
|
|
|
608
639
|
};
|
|
609
640
|
|
|
610
641
|
/** Cancel `agent`'s turn, and store it cancelled. */
|
|
611
|
-
async function cancelTurn(
|
|
642
|
+
async function cancelTurn(agent: Agent, persistence: SqlSessionPersistence, sessionId: SessionId) {
|
|
612
643
|
agent.cancel({ kind: 'user' });
|
|
613
644
|
await agent.whenIdle();
|
|
614
|
-
await
|
|
645
|
+
await persistence.writeNow(sessionId);
|
|
615
646
|
}
|
|
616
647
|
|
|
617
648
|
/**
|
|
618
649
|
* `definition`, the calls whose results are stored forgotten as each of its
|
|
619
650
|
* calls starts (its call and its result are published once a flush stores
|
|
620
|
-
* them, `runOf`); its error failing the attempt.
|
|
651
|
+
* them, `runOf`); its error failing the attempt. What the harness has queued
|
|
652
|
+
* is stored (`barrier`) before its body runs: the harness's flush before it is soft.
|
|
621
653
|
*/
|
|
622
654
|
const tracked = (
|
|
623
655
|
definition: ToolDefinition,
|
|
624
656
|
ctx: restate.SessionContext,
|
|
625
657
|
fail: (error: unknown) => void,
|
|
658
|
+
barrier: () => Promise<void>,
|
|
626
659
|
): ToolDefinition => ({
|
|
627
660
|
...definition,
|
|
628
661
|
execute: async (args, exec) => {
|
|
629
662
|
try {
|
|
663
|
+
// The last thing before the body, nested calls too: what is queued is stored, or the body does not run.
|
|
664
|
+
await barrier();
|
|
630
665
|
await toolCallStarted(ctx);
|
|
631
666
|
return await definition.execute(args, exec);
|
|
632
667
|
} catch (error) {
|
|
@@ -4,13 +4,21 @@
|
|
|
4
4
|
//
|
|
5
5
|
// The harness writes a session through a handle: `append` accepts a batch,
|
|
6
6
|
// and `flush` is the durability barrier. Here an append is kept in memory and
|
|
7
|
-
// a
|
|
8
|
-
// session's header is stored with its first
|
|
7
|
+
// a write stores everything appended before it in one SQL transaction; a new
|
|
8
|
+
// session's header is stored with its first write, so a session that crashed
|
|
9
9
|
// before then never existed. The session checkpoint policy
|
|
10
10
|
// (dsh-session-checkpoint-policy) flushes before each model request, before
|
|
11
|
-
// each tool body, and before each step
|
|
12
|
-
//
|
|
13
|
-
//
|
|
11
|
+
// each tool body, and before each step.
|
|
12
|
+
//
|
|
13
|
+
// A write is a commit to Restate, so the harness's flushes are soft once the
|
|
14
|
+
// adapter has put its own barriers in place (`barriered`, set by index.ts
|
|
15
|
+
// only when it has): a soft flush stores nothing and resolves, leaving the
|
|
16
|
+
// events queued. The adapter's barriers (`writeNow`) store everything queued
|
|
17
|
+
// right before each model request and each tool body, before each Restate
|
|
18
|
+
// effect and publish, and at the end of the run. So the events a tool's call
|
|
19
|
+
// follows from are stored before the tool runs, and a crash loses only
|
|
20
|
+
// events that nothing has acted on. Without the barriers every flush is a
|
|
21
|
+
// write.
|
|
14
22
|
import type { Context } from '@deepseek-ai/cordis';
|
|
15
23
|
import { SessionLogOffset, type SessionEvent, type SessionHeader, type SessionId } from '@deepseek-ai/dsh-session';
|
|
16
24
|
import {
|
|
@@ -58,6 +66,12 @@ export class SqlSessionPersistence extends SessionPersistence {
|
|
|
58
66
|
created = new Map<SessionId, Omit<Stored, 'count'>>();
|
|
59
67
|
handles = new Set<SqlSessionHandle>();
|
|
60
68
|
abandoned = false;
|
|
69
|
+
/**
|
|
70
|
+
* Whether the harness's flushes are soft: set by the code that installs the
|
|
71
|
+
* adapter's barriers (index.ts), once every one of them is in place. Unset,
|
|
72
|
+
* each flush stores what is queued.
|
|
73
|
+
*/
|
|
74
|
+
barriered = false;
|
|
61
75
|
/**
|
|
62
76
|
* What each flush's events are copied into beside the log, in the flush's
|
|
63
77
|
* transaction: the conversation of turns (index.ts), so that the copy and
|
|
@@ -74,7 +88,7 @@ export class SqlSessionPersistence extends SessionPersistence {
|
|
|
74
88
|
// The live session's events go to its write handle; its flushes and its
|
|
75
89
|
// disposal reach the handle too.
|
|
76
90
|
ctx.on('session/event', (session, event) => this.writers.get(session.id)?.enqueue(event));
|
|
77
|
-
ctx.on('session/flush', (session) => this.writers.get(session.id)?.
|
|
91
|
+
ctx.on('session/flush', (session) => this.writers.get(session.id)?.harnessFlush());
|
|
78
92
|
ctx.on('session/disposed', (session) => void this.writers.get(session.id)?.close());
|
|
79
93
|
ctx.effect(
|
|
80
94
|
() => async () => {
|
|
@@ -138,6 +152,11 @@ export class SqlSessionPersistence extends SessionPersistence {
|
|
|
138
152
|
return handle;
|
|
139
153
|
}
|
|
140
154
|
|
|
155
|
+
/** Store everything queued for session `id` now, or throw: the adapter's barrier before an effect (see the top). */
|
|
156
|
+
async writeNow(id: SessionId): Promise<void> {
|
|
157
|
+
await this.writers.get(id)?.writeNow();
|
|
158
|
+
}
|
|
159
|
+
|
|
141
160
|
async flush(): Promise<void> {
|
|
142
161
|
const results = await Promise.allSettled([...this.writers.values()].map((writer) => writer.flush()));
|
|
143
162
|
const errors = results.flatMap((r) => (r.status === 'rejected' ? [r.reason] : []));
|
|
@@ -240,6 +259,28 @@ class SqlSessionHandle implements SessionHandle {
|
|
|
240
259
|
this.#pending.push(...materializeAppendBatch([event]));
|
|
241
260
|
}
|
|
242
261
|
|
|
262
|
+
/**
|
|
263
|
+
* The harness's flush (`session/flush`): a write, unless the adapter's
|
|
264
|
+
* barriers cover the effects (`barriered`), when the events stay queued for
|
|
265
|
+
* the next barrier.
|
|
266
|
+
*/
|
|
267
|
+
harnessFlush(): Promise<void> {
|
|
268
|
+
if (!this.#store.barriered) return this.flush();
|
|
269
|
+
this.#check('flush');
|
|
270
|
+
if (this.access !== 'write') throw new SessionReadOnlyError(this.id, 'flush');
|
|
271
|
+
return Promise.resolve();
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** Store every event appended before the call, or throw if one is not stored. */
|
|
275
|
+
async writeNow(): Promise<void> {
|
|
276
|
+
const end = this.#end;
|
|
277
|
+
await this.flush();
|
|
278
|
+
// Events appended while it stored are for the next write; none before may be left.
|
|
279
|
+
if (this.#stored < end || this.#store.created.has(this.id)) {
|
|
280
|
+
throw new Error(`sql session persistence: the events of session ${this.id} are not stored`);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
243
284
|
/** Store every event appended so far, in one transaction. */
|
|
244
285
|
flush(): Promise<void> {
|
|
245
286
|
this.#check('flush');
|
package/src/langgraph/README.md
CHANGED
|
@@ -151,6 +151,15 @@ writes in three tables; a step stores only the channels it changed. With
|
|
|
151
151
|
ancestors a `DeltaChannel` is rebuilt from; by default it keeps them all,
|
|
152
152
|
for LangGraph's history.
|
|
153
153
|
|
|
154
|
+
A task's pending writes are stored in the transaction of the checkpoint that
|
|
155
|
+
follows them, when that comes in the same macrotask (the step's last task has
|
|
156
|
+
just finished): a step is one commit. While other tasks of the step still run,
|
|
157
|
+
the writes of one that finished are stored on their own at the end of the
|
|
158
|
+
macrotask, so that it does not run again after a crash. A `putWrites` promise
|
|
159
|
+
resolves once its rows are stored (and fails with the error of the commit that
|
|
160
|
+
carried them), so a graph's `invoke` that returns has everything stored, as
|
|
161
|
+
LangGraph awaits them. Reads and `prune` store what is pending first.
|
|
162
|
+
|
|
154
163
|
## Run
|
|
155
164
|
|
|
156
165
|
```sh
|
|
@@ -17,9 +17,26 @@
|
|
|
17
17
|
// a step's writes in. A write without a path (graph input, a `Command`)
|
|
18
18
|
// comes first.
|
|
19
19
|
//
|
|
20
|
-
// Each `put`
|
|
21
|
-
//
|
|
22
|
-
//
|
|
20
|
+
// Each `put` is one SQL transaction, so a step is stored whole, in order with
|
|
21
|
+
// everything else the handler does. Operations run one at a time, in call
|
|
22
|
+
// order: LangGraph writes the results of parallel tasks at once.
|
|
23
|
+
//
|
|
24
|
+
// A task's `putWrites` is kept pending, and its promise resolves once its
|
|
25
|
+
// rows are stored, as LangGraph awaits it (before a run ends, whatever ends
|
|
26
|
+
// it, and before a step's `put` if it carries delta writes), and fails with
|
|
27
|
+
// its error. The `put` of its step, if called before the macrotask ends,
|
|
28
|
+
// which it is when the step's last task has just finished, stores the pending
|
|
29
|
+
// writes and then its checkpoint in one transaction: the writes' promises and
|
|
30
|
+
// the `put`'s settle when it commits, or fail with its error, so a step is
|
|
31
|
+
// stored before any task of the next starts. Else, the step has tasks still
|
|
32
|
+
// running, and the pending writes are stored on their own, in one
|
|
33
|
+
// transaction, at the end of the macrotask: a task that finished has its
|
|
34
|
+
// writes stored while its siblings run, so it does not run again after a
|
|
35
|
+
// crash, and no promise waits for a `put` to be called. Reads (`getTuple`,
|
|
36
|
+
// `list`), `prune` and `deleteThread` store what is pending first. Nothing
|
|
37
|
+
// is remembered of a failure: a failed `put` or store rejects the promises of
|
|
38
|
+
// what it carried, which are not stored again, and the attempt fails and
|
|
39
|
+
// goes on from what is stored.
|
|
23
40
|
//
|
|
24
41
|
// By default a thread keeps every checkpoint (LangGraph's history: `list`,
|
|
25
42
|
// time travel, forks). With `history: 'latest'`, each `put` drops the
|
|
@@ -184,7 +201,29 @@ async function dropEarlier(tx: DatabaseWriter, threadId: string, ns: string, kep
|
|
|
184
201
|
);
|
|
185
202
|
}
|
|
186
203
|
|
|
187
|
-
/**
|
|
204
|
+
/** One `putWrites`: its rows (a serialization in progress), the statement's verb, and how its promise settles. */
|
|
205
|
+
interface PendingWrites {
|
|
206
|
+
verb: string;
|
|
207
|
+
rows: Promise<SqlValue[][]>;
|
|
208
|
+
stored: PromiseWithResolvers<void>;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Settles the promises of `writes`: resolved once stored, or rejected with the `error` of what carried them. */
|
|
212
|
+
function settle(writes: PendingWrites[], error?: { error: unknown }) {
|
|
213
|
+
for (const { stored } of writes) {
|
|
214
|
+
if (error) stored.reject(error.error);
|
|
215
|
+
else stored.resolve();
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* A LangGraph checkpointer whose threads are in the database session `db`:
|
|
221
|
+
* see the top of this file. A task's pending writes are stored with the `put`
|
|
222
|
+
* that follows them in the same macrotask, else at the end of it; a
|
|
223
|
+
* `putWrites` promise resolves once they are stored, so awaiting it, as
|
|
224
|
+
* LangGraph does before a run ends, has them stored. This holds for a user's
|
|
225
|
+
* own use of the saver too.
|
|
226
|
+
*/
|
|
188
227
|
export class SqlCheckpointSaver extends BaseCheckpointSaver {
|
|
189
228
|
#db: Database;
|
|
190
229
|
#latest: boolean;
|
|
@@ -197,6 +236,10 @@ export class SqlCheckpointSaver extends BaseCheckpointSaver {
|
|
|
197
236
|
#needed = new Map<string, Needed[]>();
|
|
198
237
|
#ready: Promise<void> | undefined;
|
|
199
238
|
#tail: Promise<unknown> = Promise.resolve();
|
|
239
|
+
/** The writes of tasks that no operation has taken yet, in the order LangGraph called `putWrites`. */
|
|
240
|
+
#pending: PendingWrites[] = [];
|
|
241
|
+
/** Stores what is pending, when the macrotask ends. */
|
|
242
|
+
#timer: NodeJS.Immediate | undefined;
|
|
200
243
|
|
|
201
244
|
/**
|
|
202
245
|
* `db`: a database session (`ctx.db`). `history`: the checkpoints a thread
|
|
@@ -237,6 +280,42 @@ export class SqlCheckpointSaver extends BaseCheckpointSaver {
|
|
|
237
280
|
return result;
|
|
238
281
|
}
|
|
239
282
|
|
|
283
|
+
/** The writes pending now, which the caller must store, in order; the end of the macrotask has nothing to store then. */
|
|
284
|
+
#take(): PendingWrites[] {
|
|
285
|
+
if (this.#timer) clearImmediate(this.#timer);
|
|
286
|
+
this.#timer = undefined;
|
|
287
|
+
return this.#pending.splice(0);
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** Stores `writes` in `tx`, in order. */
|
|
291
|
+
async #store(tx: DatabaseWriter, writes: PendingWrites[]) {
|
|
292
|
+
for (const { verb, rows } of writes) {
|
|
293
|
+
for (const row of await rows) {
|
|
294
|
+
await tx.execute(
|
|
295
|
+
`${verb} INTO restate_langgraph_writes (thread_id, checkpoint_ns, checkpoint_id, task_id, idx, channel, type, value, task_path) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
296
|
+
row,
|
|
297
|
+
);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* Stores what is pending, on its own, in order with the operations: the
|
|
304
|
+
* ones called after it are after it. Its promises settle with the commit.
|
|
305
|
+
*/
|
|
306
|
+
#storePending(): void {
|
|
307
|
+
const writes = this.#take();
|
|
308
|
+
if (writes.length === 0) return;
|
|
309
|
+
this.#serial(async () => {
|
|
310
|
+
// Serialized before the transaction opens, as a `put`'s values are.
|
|
311
|
+
await Promise.all(writes.map(({ rows }) => rows));
|
|
312
|
+
await this.#db.transaction((tx) => this.#store(tx, writes));
|
|
313
|
+
}).then(
|
|
314
|
+
() => settle(writes),
|
|
315
|
+
(error: unknown) => settle(writes, { error }),
|
|
316
|
+
);
|
|
317
|
+
}
|
|
318
|
+
|
|
240
319
|
/** The values of `checkpoint`'s channels, at its versions. */
|
|
241
320
|
async #channelValues(threadId: string, ns: string, checkpoint: Checkpoint): Promise<Record<string, unknown>> {
|
|
242
321
|
const versions = Object.entries(checkpoint.channel_versions ?? {});
|
|
@@ -346,6 +425,7 @@ export class SqlCheckpointSaver extends BaseCheckpointSaver {
|
|
|
346
425
|
}
|
|
347
426
|
|
|
348
427
|
getTuple(config: RunnableConfig): Promise<CheckpointTuple | undefined> {
|
|
428
|
+
this.#storePending();
|
|
349
429
|
return this.#serial(async () => {
|
|
350
430
|
const { thread_id, checkpoint_ns = '', checkpoint_id } = config.configurable ?? {};
|
|
351
431
|
const rows = checkpoint_id
|
|
@@ -365,6 +445,7 @@ export class SqlCheckpointSaver extends BaseCheckpointSaver {
|
|
|
365
445
|
config: RunnableConfig,
|
|
366
446
|
{ limit, before, filter }: CheckpointListOptions = {},
|
|
367
447
|
): AsyncGenerator<CheckpointTuple> {
|
|
448
|
+
this.#storePending();
|
|
368
449
|
const tuples = await this.#serial(async () => {
|
|
369
450
|
const { thread_id, checkpoint_ns } = config.configurable ?? {};
|
|
370
451
|
const where: string[] = [];
|
|
@@ -401,6 +482,8 @@ export class SqlCheckpointSaver extends BaseCheckpointSaver {
|
|
|
401
482
|
metadata: CheckpointMetadata,
|
|
402
483
|
newVersions: ChannelVersions,
|
|
403
484
|
): Promise<RunnableConfig> {
|
|
485
|
+
// The writes called before it, whose transaction this is.
|
|
486
|
+
const writes = this.#take();
|
|
404
487
|
return this.#serial(async () => {
|
|
405
488
|
const { thread_id, checkpoint_ns = '', checkpoint_id: parentId } = config.configurable ?? {};
|
|
406
489
|
if (!thread_id) throw new Error('Missing "thread_id" field in passed "config.configurable".');
|
|
@@ -415,8 +498,10 @@ export class SqlCheckpointSaver extends BaseCheckpointSaver {
|
|
|
415
498
|
return [channel, String(version), valueType, value];
|
|
416
499
|
}),
|
|
417
500
|
);
|
|
501
|
+
await Promise.all(writes.map(({ rows }) => rows));
|
|
418
502
|
let kept: Needed[] | undefined;
|
|
419
503
|
await this.#db.transaction(async (tx) => {
|
|
504
|
+
await this.#store(tx, writes);
|
|
420
505
|
for (const row of changed) {
|
|
421
506
|
await tx.execute(
|
|
422
507
|
'INSERT OR REPLACE INTO restate_langgraph_channel_values (thread_id, checkpoint_ns, channel, version, type, value) VALUES (?, ?, ?, ?, ?, ?)',
|
|
@@ -435,41 +520,53 @@ export class SqlCheckpointSaver extends BaseCheckpointSaver {
|
|
|
435
520
|
// Once stored: a transaction rolled back keeps the ones before.
|
|
436
521
|
if (kept) this.#needed.set(JSON.stringify([thread_id, checkpoint_ns]), kept);
|
|
437
522
|
return { configurable: { thread_id, checkpoint_ns, checkpoint_id: checkpoint.id } };
|
|
438
|
-
})
|
|
523
|
+
}).then(
|
|
524
|
+
(stored) => {
|
|
525
|
+
settle(writes);
|
|
526
|
+
return stored;
|
|
527
|
+
},
|
|
528
|
+
(error: unknown) => {
|
|
529
|
+
// The writes it carried fail with it, and are not stored again: the attempt fails, and goes on from what is stored.
|
|
530
|
+
settle(writes, { error });
|
|
531
|
+
throw error;
|
|
532
|
+
},
|
|
533
|
+
);
|
|
439
534
|
}
|
|
440
535
|
|
|
441
536
|
putWrites(config: RunnableConfig, writes: PendingWrite[], taskId: string, taskPath?: string): Promise<void> {
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
537
|
+
const { thread_id, checkpoint_ns = '', checkpoint_id } = config.configurable ?? {};
|
|
538
|
+
if (!thread_id) return Promise.reject(new Error('Missing thread_id field in config.configurable.'));
|
|
539
|
+
if (!checkpoint_id) return Promise.reject(new Error('Missing checkpoint_id field in config.configurable.'));
|
|
540
|
+
// Special writes (errors, interrupts) replace; others keep the first.
|
|
541
|
+
const verb = writes.every(([channel]) => channel in WRITES_IDX_MAP) ? 'INSERT OR REPLACE' : 'INSERT OR IGNORE';
|
|
542
|
+
const rows = Promise.all(
|
|
543
|
+
writes.map(async ([channel, value], idx): Promise<SqlValue[]> => {
|
|
544
|
+
const [type, stored] = await this.serde.dumpsTyped(value);
|
|
545
|
+
return [
|
|
546
|
+
thread_id,
|
|
547
|
+
checkpoint_ns,
|
|
548
|
+
checkpoint_id,
|
|
549
|
+
taskId,
|
|
550
|
+
WRITES_IDX_MAP[channel] ?? idx,
|
|
551
|
+
channel,
|
|
552
|
+
type,
|
|
553
|
+
stored,
|
|
554
|
+
taskPath ?? null,
|
|
555
|
+
];
|
|
556
|
+
}),
|
|
557
|
+
);
|
|
558
|
+
// Whoever stores it awaits it, and fails with it; until then it is not an unhandled rejection.
|
|
559
|
+
rows.catch(() => {});
|
|
560
|
+
const stored = Promise.withResolvers<void>();
|
|
561
|
+
// The caller awaits `stored`, as LangGraph does; a rejection is observed either way.
|
|
562
|
+
stored.promise.catch(() => {});
|
|
563
|
+
this.#pending.push({ verb, rows, stored });
|
|
564
|
+
// A `put` in this macrotask takes it, else it is stored on its own when the macrotask ends.
|
|
565
|
+
this.#timer ??= setImmediate(() => {
|
|
566
|
+
this.#timer = undefined;
|
|
567
|
+
this.#storePending();
|
|
472
568
|
});
|
|
569
|
+
return stored.promise;
|
|
473
570
|
}
|
|
474
571
|
|
|
475
572
|
/**
|
|
@@ -482,6 +579,7 @@ export class SqlCheckpointSaver extends BaseCheckpointSaver {
|
|
|
482
579
|
* (`''`) or a subgraph run's, which keeps its latest checkpoint too.
|
|
483
580
|
*/
|
|
484
581
|
prune(threadIds: string[], { strategy = 'keepLatest' }: { strategy?: 'keepLatest' | 'delete' } = {}): Promise<void> {
|
|
582
|
+
this.#storePending();
|
|
485
583
|
return this.#serial(() =>
|
|
486
584
|
this.#db.transaction(async (tx) => {
|
|
487
585
|
for (const threadId of threadIds) {
|
|
@@ -506,6 +604,7 @@ export class SqlCheckpointSaver extends BaseCheckpointSaver {
|
|
|
506
604
|
}
|
|
507
605
|
|
|
508
606
|
deleteThread(threadId: string): Promise<void> {
|
|
607
|
+
this.#storePending();
|
|
509
608
|
return this.#serial(() =>
|
|
510
609
|
this.#db.transaction(async (tx) => {
|
|
511
610
|
for (const table of TABLES) await tx.execute(`DELETE FROM ${table} WHERE thread_id = ?`, [threadId]);
|
package/src/langgraph/graph.ts
CHANGED
|
@@ -7,7 +7,9 @@
|
|
|
7
7
|
// the message as a new `HumanMessage`:
|
|
8
8
|
//
|
|
9
9
|
// - The graph's checkpoints are in the key's database (`SqlCheckpointSaver`),
|
|
10
|
-
// stored before each step runs (`durability: 'sync'
|
|
10
|
+
// stored before each step runs (`durability: 'sync'`; a step's writes
|
|
11
|
+
// with its checkpoint, see checkpointer.ts; LangGraph awaits them all
|
|
12
|
+
// before a run ends, an error or a stop included), and the prebuilt
|
|
11
13
|
// nodes (nodes.ts) and the tools of `tools()` get the handler's context
|
|
12
14
|
// there (context.ts). LangGraph's run context is the graph's own (`context`),
|
|
13
15
|
// else the handler's. A retried attempt resumes the run it cut off. A run
|
|
@@ -368,7 +370,10 @@ async function runGraph(
|
|
|
368
370
|
signal: stopSignalOf(ctx),
|
|
369
371
|
callbacks: [kept],
|
|
370
372
|
};
|
|
371
|
-
|
|
373
|
+
// `next` leaves out the tasks whose writes are stored, so a step whose writes were stored before its checkpoint
|
|
374
|
+
// (a crash between them) has no `next` but still has tasks: that run goes on, from those writes, without running
|
|
375
|
+
// the tasks again. A finished run has no tasks.
|
|
376
|
+
if (asked && snapshot.tasks.length === 0) {
|
|
372
377
|
// The run had finished, but its answer was not stored: that is the answer, rather than run again.
|
|
373
378
|
await copied(turn, known, messages, promptId);
|
|
374
379
|
await saver.prune([THREAD_ID]);
|
package/src/opencode/index.ts
CHANGED
|
@@ -104,6 +104,7 @@ import {
|
|
|
104
104
|
toolCallStarted,
|
|
105
105
|
approves,
|
|
106
106
|
} from '../common.ts';
|
|
107
|
+
import { flushCalls } from '../calls.ts';
|
|
107
108
|
import { answerOnce, invocationOf, type Call, type Items, type Parsed, STEPS, type Turn } from '../conversation.ts';
|
|
108
109
|
import { conversationView } from '../messages.ts';
|
|
109
110
|
import { tookSteers } from '../steering.ts';
|
|
@@ -148,7 +149,25 @@ const native = (t: AnyTool, ctx: restate.SessionContext): OpenCodeTool => {
|
|
|
148
149
|
},
|
|
149
150
|
},
|
|
150
151
|
};
|
|
151
|
-
return {
|
|
152
|
+
return {
|
|
153
|
+
name: t.name,
|
|
154
|
+
description: t.description,
|
|
155
|
+
input,
|
|
156
|
+
execute: async (args, callId) => {
|
|
157
|
+
// OpenCode stores the result (or the error a call answered with) in its own database, which a commit of
|
|
158
|
+
// `ctx.db` does not reach: a call that answered is recorded before it is handed over. The tool's own error
|
|
159
|
+
// is the one thrown, whatever the flush does.
|
|
160
|
+
let result: string;
|
|
161
|
+
try {
|
|
162
|
+
result = await t.run(args, { ctx, callId });
|
|
163
|
+
} catch (error) {
|
|
164
|
+
await flushCalls(ctx).catch(() => {});
|
|
165
|
+
throw error;
|
|
166
|
+
}
|
|
167
|
+
await flushCalls(ctx);
|
|
168
|
+
return result;
|
|
169
|
+
},
|
|
170
|
+
};
|
|
152
171
|
};
|
|
153
172
|
|
|
154
173
|
/** The session every prompt goes to. */
|