@restatedev/agents 0.5.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +79 -24
- 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 +12 -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 +103 -5
- package/dist/conversation.d.ts.map +1 -1
- package/dist/conversation.js +295 -75
- 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 +26 -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 +3 -1
- package/dist/langgraph/checkpointer.d.ts.map +1 -1
- package/dist/langgraph/checkpointer.js +15 -6
- 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 +14 -11
- package/dist/object.js.map +1 -1
- package/dist/opencode/index.d.ts +11 -11
- package/dist/opencode/index.d.ts.map +1 -1
- package/dist/opencode/index.js +25 -27
- package/dist/opencode/index.js.map +1 -1
- package/dist/pi/index.d.ts +13 -13
- package/dist/pi/index.d.ts.map +1 -1
- package/dist/pi/index.js +18 -20
- package/dist/pi/index.js.map +1 -1
- package/dist/pi/storage.d.ts +7 -0
- package/dist/pi/storage.d.ts.map +1 -1
- package/dist/pi/storage.js +12 -0
- package/dist/pi/storage.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 +90 -84
- package/src/calls.ts +52 -11
- package/src/claude/README.md +4 -2
- package/src/claude/index.ts +12 -7
- package/src/client.ts +1 -1
- package/src/common.ts +99 -40
- package/src/companion.ts +674 -0
- package/src/conversation.ts +353 -101
- package/src/deepseek/README.md +7 -1
- package/src/deepseek/index.ts +25 -24
- package/src/index.ts +10 -4
- package/src/langgraph/README.md +8 -5
- package/src/langgraph/checkpointer.ts +26 -15
- 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 +43 -40
- package/src/opencode/README.md +5 -2
- package/src/opencode/index.ts +26 -27
- package/src/pi/README.md +6 -1
- package/src/pi/index.ts +25 -19
- package/src/pi/storage.ts +13 -0
- 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/deepseek/index.ts
CHANGED
|
@@ -50,6 +50,7 @@ import { TokenMeter } from '@deepseek-ai/dsh-token-meter';
|
|
|
50
50
|
import { ToolResultPruner } from '@deepseek-ai/dsh-compaction-tool-result-pruner';
|
|
51
51
|
import { BasicCompactionEngine, type BasicCompactionConfig } from '@deepseek-ai/dsh-compaction-basic';
|
|
52
52
|
import { ApprovalService, type ApprovalOutcome } from '@deepseek-ai/dsh-user-approval';
|
|
53
|
+
import * as nativeExecutor from '@deepseek-ai/dsh-tool-executor-native';
|
|
53
54
|
import { builtinProviders } from '@earendil-works/pi-ai/providers/all';
|
|
54
55
|
import {
|
|
55
56
|
defineTool,
|
|
@@ -73,7 +74,6 @@ import {
|
|
|
73
74
|
providerOf,
|
|
74
75
|
RETURNED_UNRECORDED,
|
|
75
76
|
stopSignalOf,
|
|
76
|
-
toolCallEnded,
|
|
77
77
|
toolCallStarted,
|
|
78
78
|
} from '../common.ts';
|
|
79
79
|
import { answerOnce, type Items, type Parsed, type Run, type Turn } from '../conversation.ts';
|
|
@@ -148,6 +148,8 @@ async function boot(
|
|
|
148
148
|
await harness.plugin(SessionStore);
|
|
149
149
|
await harness.plugin(SystemPrompt, system ? { personaPrefix: system } : {});
|
|
150
150
|
await harness.plugin(ToolRuntime, {});
|
|
151
|
+
// The executor that runs the model's tool calls as the model asks for them.
|
|
152
|
+
await harness.plugin(nativeExecutor);
|
|
151
153
|
// Without it, the harness denies a call that asks for an approval. With it,
|
|
152
154
|
// the model is also told that some calls may ask for one.
|
|
153
155
|
if (approvals) await harness.plugin(ApprovalService, {});
|
|
@@ -455,7 +457,8 @@ const steeredId = (messageId: string) => (messageId.startsWith('steer:') ? messa
|
|
|
455
457
|
* to continue (a step of the run's own), nor anything once the run stopped
|
|
456
458
|
* or `failed()` (the harness's result of a tool that failed the attempt, or
|
|
457
459
|
* was cancelled, is not the call's): the turn's close, or the retry, says
|
|
458
|
-
* how it ended. `
|
|
460
|
+
* how it ended. `steps` is told when it copied a step that a follower waits
|
|
461
|
+
* for: a reply with tool calls, or a tool's result.
|
|
459
462
|
*/
|
|
460
463
|
const copying =
|
|
461
464
|
(
|
|
@@ -463,7 +466,7 @@ const copying =
|
|
|
463
466
|
turn: Turn<Message>,
|
|
464
467
|
from: () => number | undefined,
|
|
465
468
|
failed: () => boolean,
|
|
466
|
-
|
|
469
|
+
steps: () => void,
|
|
467
470
|
) =>
|
|
468
471
|
async (tx: Parameters<NonNullable<SqlSessionPersistence['copy']>>[0], batch: readonly SessionEvent[]) => {
|
|
469
472
|
const start = from();
|
|
@@ -484,9 +487,13 @@ const copying =
|
|
|
484
487
|
tx,
|
|
485
488
|
copied.flatMap(({ steer }) => (steer === undefined ? [] : [steer])),
|
|
486
489
|
);
|
|
487
|
-
|
|
490
|
+
if (copied.some(({ item }) => isStep(item))) steps();
|
|
488
491
|
};
|
|
489
492
|
|
|
493
|
+
/** Whether `m` is a step of a turn that its followers are told of: a reply with tool calls, or a tool's result. */
|
|
494
|
+
const isStep = (m: Message) =>
|
|
495
|
+
m.role === 'tool' || (m.role === 'assistant' && m.content.some((c) => c.type === 'tool-call'));
|
|
496
|
+
|
|
490
497
|
/**
|
|
491
498
|
* The run of the harness of `options`, on the conversation: its turn's
|
|
492
499
|
* latest ask (its prompt, or the message that asked again) asked once, and
|
|
@@ -520,14 +527,12 @@ const runOf =
|
|
|
520
527
|
const id = again ? MessageId(`prompt:${turn.id}:again`) : promptId(turn.id);
|
|
521
528
|
// Where the turn's latest ask is in the log, once it is.
|
|
522
529
|
let from: number | undefined;
|
|
523
|
-
// The tool calls that returned, whose ends are published once a flush stored their results.
|
|
524
|
-
const returned = new Set<string>();
|
|
525
530
|
try {
|
|
526
531
|
const sessionId = SessionId(ctx.key);
|
|
527
532
|
const options = {
|
|
528
533
|
agentOptions: route,
|
|
529
534
|
setup: (agentCtx: Context) => {
|
|
530
|
-
for (const t of tools) agentCtx.tools.register(tracked(isTool(t) ? native(t, ctx) : t, ctx, fail
|
|
535
|
+
for (const t of tools) agentCtx.tools.register(tracked(isTool(t) ? native(t, ctx) : t, ctx, fail));
|
|
531
536
|
if (approval !== undefined) approving(agentCtx, ctx, approval, fail);
|
|
532
537
|
},
|
|
533
538
|
};
|
|
@@ -538,8 +543,9 @@ const runOf =
|
|
|
538
543
|
agent = started.agent;
|
|
539
544
|
const found = agent.session.snapshotEvents().length;
|
|
540
545
|
from = agent.session.snapshotEvents().find((e) => e.type === 'user/message' && e.data.id === id)?.seq;
|
|
541
|
-
// A
|
|
542
|
-
|
|
546
|
+
// A flush that copied steps (a reply with tool calls, tools' results) is published once it is stored,
|
|
547
|
+
// for followers to read them there; its answer lists the messages steered to the turn (below).
|
|
548
|
+
let copiedSteps = false;
|
|
543
549
|
// The harness messages of the steered messages in the log: those before this attempt, and each flush's.
|
|
544
550
|
const placed = new Set(
|
|
545
551
|
agent.session
|
|
@@ -555,19 +561,19 @@ const runOf =
|
|
|
555
561
|
turn,
|
|
556
562
|
() => from,
|
|
557
563
|
() => broken,
|
|
558
|
-
(
|
|
559
|
-
|
|
564
|
+
() => {
|
|
565
|
+
copiedSteps = true;
|
|
560
566
|
},
|
|
561
567
|
)(tx, batch);
|
|
562
568
|
};
|
|
563
569
|
persistence.flushed = async () => {
|
|
564
|
-
if (!
|
|
565
|
-
|
|
570
|
+
if (!copiedSteps) return;
|
|
571
|
+
copiedSteps = false;
|
|
566
572
|
// Failing, it fails the attempt, as a tool's error does: never the flush, which is done.
|
|
567
|
-
await
|
|
573
|
+
await turn.stepsCommitted().catch(fail);
|
|
568
574
|
};
|
|
569
575
|
// The messages steered to the turn, handed to the harness's step inbox as a publish lists them: only
|
|
570
|
-
//
|
|
576
|
+
// once a reply with tool calls or a result is stored, so that a step after them places them, in this turn.
|
|
571
577
|
const harnessAgent = agent;
|
|
572
578
|
const given = new Set<string>();
|
|
573
579
|
unlisten = inboxOf(ctx)?.listen(() => {
|
|
@@ -616,25 +622,20 @@ async function cancelTurn(harness: Context, agent: Agent) {
|
|
|
616
622
|
}
|
|
617
623
|
|
|
618
624
|
/**
|
|
619
|
-
* `definition`,
|
|
620
|
-
*
|
|
621
|
-
*
|
|
622
|
-
* attempt.
|
|
625
|
+
* `definition`, the calls whose results are stored forgotten as each of its
|
|
626
|
+
* calls starts (its call and its result are published once a flush stores
|
|
627
|
+
* them, `runOf`); its error failing the attempt.
|
|
623
628
|
*/
|
|
624
629
|
const tracked = (
|
|
625
630
|
definition: ToolDefinition,
|
|
626
631
|
ctx: restate.SessionContext,
|
|
627
632
|
fail: (error: unknown) => void,
|
|
628
|
-
returned: Set<string>,
|
|
629
633
|
): ToolDefinition => ({
|
|
630
634
|
...definition,
|
|
631
635
|
execute: async (args, exec) => {
|
|
632
636
|
try {
|
|
633
637
|
await toolCallStarted(ctx);
|
|
634
|
-
|
|
635
|
-
// Its end is published once the harness stored its result (`runOf`).
|
|
636
|
-
returned.add(exec.callId);
|
|
637
|
-
return result;
|
|
638
|
+
return await definition.execute(args, exec);
|
|
638
639
|
} catch (error) {
|
|
639
640
|
fromTool(ctx, error);
|
|
640
641
|
fail(error);
|
package/src/index.ts
CHANGED
|
@@ -3,6 +3,8 @@
|
|
|
3
3
|
// any of them, and the tools that are Restate itself.
|
|
4
4
|
|
|
5
5
|
export {
|
|
6
|
+
type AgentContext,
|
|
7
|
+
type AgentViewContext,
|
|
6
8
|
CANCELLED,
|
|
7
9
|
chatHandler,
|
|
8
10
|
type ChatMessage,
|
|
@@ -16,18 +18,22 @@ export {
|
|
|
16
18
|
} from './common.ts';
|
|
17
19
|
export { sessionObject, type Status, type Stopped } from './object.ts';
|
|
18
20
|
export {
|
|
21
|
+
COMPANION_SUFFIX,
|
|
19
22
|
companionOf,
|
|
20
23
|
deliver,
|
|
21
|
-
signals,
|
|
22
24
|
type Companion,
|
|
23
25
|
type Resolved,
|
|
24
26
|
type Signal,
|
|
25
27
|
type Steered,
|
|
26
28
|
type Steering,
|
|
27
29
|
type Waiting,
|
|
28
|
-
} from './
|
|
30
|
+
} from './companion.ts';
|
|
29
31
|
export { call, send, signal, subagent, tool, workflow, type Tool, type ToolCall, type ToolContext } from './tools.ts';
|
|
30
32
|
export { webhook, webhookMessage, type WebhookAuth, type WebhookEvent, type WebhookOptions } from './webhook.ts';
|
|
31
33
|
|
|
32
|
-
/**
|
|
33
|
-
|
|
34
|
+
/**
|
|
35
|
+
* @restatedev/sessions' `serve`: the services on PORT, with what they need
|
|
36
|
+
* beside them (each agent's companion); and `served`, those services, for
|
|
37
|
+
* an endpoint of your own (`restate.endpoint()`).
|
|
38
|
+
*/
|
|
39
|
+
export { serve, served } from '@restatedev/sessions';
|
package/src/langgraph/README.md
CHANGED
|
@@ -50,7 +50,8 @@ const desk = langgraph.agent({ name: 'desk', graph, context: { region: 'eu' } })
|
|
|
50
50
|
a retried attempt resumes the run it cut off, and a step stored is not run
|
|
51
51
|
again. Between turns the thread keeps its latest checkpoint (`prune`).
|
|
52
52
|
- **The `messages` view shows the run as it goes**: after each step, the AI
|
|
53
|
-
and tool messages it added are copied into the conversation, by their ids
|
|
53
|
+
and tool messages it added are copied into the conversation, by their ids
|
|
54
|
+
(a step's tool messages in one write).
|
|
54
55
|
The conversation is a log: a message the graph removes or edits later
|
|
55
56
|
stays as it was copied.
|
|
56
57
|
- **`interrupt()` waits for a signal** named `interrupt`, which the agent's
|
|
@@ -114,10 +115,12 @@ model sees of it (the earlier turns as their prompt and answer, within
|
|
|
114
115
|
`budget`; the latest `window` turns whole). The handler is not replayed: a
|
|
115
116
|
retried attempt runs it again from the start, from what is stored.
|
|
116
117
|
|
|
117
|
-
- **The model node stores its reply before it returns, and
|
|
118
|
-
|
|
119
|
-
a
|
|
120
|
-
|
|
118
|
+
- **The model node stores its reply with tool calls before it returns, and
|
|
119
|
+
the tools node the round's results in one write, once its tools ran.** So
|
|
120
|
+
a crash during the tools runs the round's calls again, those that had
|
|
121
|
+
finished too, with the same tool call ids, without asking the model
|
|
122
|
+
again. The final reply, which no tool waits for, is stored with
|
|
123
|
+
the turn's answer, in one commit: a crash before it asks the model again.
|
|
121
124
|
- **A tool is idempotent by its tool call id** (`callId` of `tool()`'s
|
|
122
125
|
`run`), which it passes on, such as in an idempotency key.
|
|
123
126
|
- **A tool's error fails the attempt**, and Restate retries it (the ToolNode
|
|
@@ -11,7 +11,11 @@
|
|
|
11
11
|
// savers (a count and a random part): a thread forked from an earlier
|
|
12
12
|
// checkpoint takes the same counts again, and its values must not replace
|
|
13
13
|
// those of the branch it forked from.
|
|
14
|
-
// - `restate_langgraph_writes`: the pending writes of each checkpoint's tasks
|
|
14
|
+
// - `restate_langgraph_writes`: the pending writes of each checkpoint's tasks,
|
|
15
|
+
// with each task's path, and read back in LangGraph's order for them
|
|
16
|
+
// (`writesSortKey`: path, task id, index), the order live execution applies
|
|
17
|
+
// a step's writes in. A write without a path (graph input, a `Command`)
|
|
18
|
+
// comes first.
|
|
15
19
|
//
|
|
16
20
|
// Each `put` and `putWrites` is one SQL transaction, so a step is stored whole,
|
|
17
21
|
// in order with everything else the handler does. Operations run one at a
|
|
@@ -36,7 +40,9 @@ import {
|
|
|
36
40
|
copyCheckpoint,
|
|
37
41
|
maxChannelVersion,
|
|
38
42
|
TASKS,
|
|
43
|
+
compareWritesSortKeys,
|
|
39
44
|
WRITES_IDX_MAP,
|
|
45
|
+
writesSortKey,
|
|
40
46
|
type ChannelVersions,
|
|
41
47
|
type Checkpoint,
|
|
42
48
|
type CheckpointListOptions,
|
|
@@ -49,7 +55,7 @@ import {
|
|
|
49
55
|
import type { DatabaseWriter, Database, SqlValue } from '@restatedev/sessions';
|
|
50
56
|
import { Schema } from '@restatedev/sessions/internal';
|
|
51
57
|
|
|
52
|
-
const SCHEMA = new Schema('restate-agents.langgraph', [
|
|
58
|
+
export const SCHEMA = new Schema('restate-agents.langgraph', [
|
|
53
59
|
`CREATE TABLE restate_langgraph_checkpoints (
|
|
54
60
|
thread_id TEXT NOT NULL,
|
|
55
61
|
checkpoint_ns TEXT NOT NULL,
|
|
@@ -78,6 +84,7 @@ const SCHEMA = new Schema('restate-agents.langgraph', [
|
|
|
78
84
|
channel TEXT NOT NULL,
|
|
79
85
|
type TEXT NOT NULL,
|
|
80
86
|
value BLOB NOT NULL,
|
|
87
|
+
task_path TEXT,
|
|
81
88
|
PRIMARY KEY (thread_id, checkpoint_ns, checkpoint_id, task_id, idx)
|
|
82
89
|
)`,
|
|
83
90
|
]);
|
|
@@ -260,10 +267,15 @@ export class SqlCheckpointSaver extends BaseCheckpointSaver {
|
|
|
260
267
|
// A checkpoint of an earlier format (v < 4) keeps its pending sends as
|
|
261
268
|
// writes of its parent.
|
|
262
269
|
if (checkpoint.v < 4 && parentId !== null) await this.#migratePendingSends(checkpoint, threadId, ns, parentId);
|
|
263
|
-
const writes =
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
270
|
+
const writes = (
|
|
271
|
+
(await this.#db.values(
|
|
272
|
+
'SELECT task_id, channel, type, value, task_path, idx FROM restate_langgraph_writes WHERE thread_id = ? AND checkpoint_ns = ? AND checkpoint_id = ?',
|
|
273
|
+
[threadId, ns, checkpointId],
|
|
274
|
+
)) as [string, string, string, Uint8Array, string | null, number][]
|
|
275
|
+
)
|
|
276
|
+
.map((row) => ({ row, key: writesSortKey(row[4] ?? '', row[0], row[5]) }))
|
|
277
|
+
.toSorted((a, b) => compareWritesSortKeys(a.key, b.key))
|
|
278
|
+
.map(({ row }) => row);
|
|
267
279
|
const config = (id: string) => ({ configurable: { thread_id: threadId, checkpoint_ns: ns, checkpoint_id: id } });
|
|
268
280
|
return {
|
|
269
281
|
config: config(checkpointId),
|
|
@@ -271,13 +283,11 @@ export class SqlCheckpointSaver extends BaseCheckpointSaver {
|
|
|
271
283
|
metadata: await this.serde.loadsTyped(type, metadata),
|
|
272
284
|
parentConfig: parentId === null ? undefined : config(parentId),
|
|
273
285
|
pendingWrites: await Promise.all(
|
|
274
|
-
(
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
],
|
|
280
|
-
),
|
|
286
|
+
writes.map(async ([taskId, channel, writeType, value]): Promise<CheckpointPendingWrite> => [
|
|
287
|
+
taskId,
|
|
288
|
+
channel,
|
|
289
|
+
await this.serde.loadsTyped(writeType, value),
|
|
290
|
+
]),
|
|
281
291
|
),
|
|
282
292
|
};
|
|
283
293
|
}
|
|
@@ -428,7 +438,7 @@ export class SqlCheckpointSaver extends BaseCheckpointSaver {
|
|
|
428
438
|
});
|
|
429
439
|
}
|
|
430
440
|
|
|
431
|
-
putWrites(config: RunnableConfig, writes: PendingWrite[], taskId: string): Promise<void> {
|
|
441
|
+
putWrites(config: RunnableConfig, writes: PendingWrite[], taskId: string, taskPath?: string): Promise<void> {
|
|
432
442
|
return this.#serial(async () => {
|
|
433
443
|
const { thread_id, checkpoint_ns = '', checkpoint_id } = config.configurable ?? {};
|
|
434
444
|
if (!thread_id) throw new Error('Missing thread_id field in config.configurable.');
|
|
@@ -447,13 +457,14 @@ export class SqlCheckpointSaver extends BaseCheckpointSaver {
|
|
|
447
457
|
channel,
|
|
448
458
|
type,
|
|
449
459
|
stored,
|
|
460
|
+
taskPath ?? null,
|
|
450
461
|
];
|
|
451
462
|
}),
|
|
452
463
|
);
|
|
453
464
|
await this.#db.transaction(async (tx) => {
|
|
454
465
|
for (const row of rows) {
|
|
455
466
|
await tx.execute(
|
|
456
|
-
`${verb} INTO restate_langgraph_writes (thread_id, checkpoint_ns, checkpoint_id, task_id, idx, channel, type, value) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
467
|
+
`${verb} INTO restate_langgraph_writes (thread_id, checkpoint_ns, checkpoint_id, task_id, idx, channel, type, value, task_path) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
457
468
|
row,
|
|
458
469
|
);
|
|
459
470
|
}
|
package/src/langgraph/graph.ts
CHANGED
|
@@ -59,9 +59,10 @@ import { AIMessage, type BaseMessage, HumanMessage, ToolMessage } from '@langcha
|
|
|
59
59
|
import { mapStoredMessagesToChatMessages } from '@langchain/core/messages';
|
|
60
60
|
import type { RunnableConfig } from '@langchain/core/runnables';
|
|
61
61
|
import { Command, InvalidUpdateError, type Pregel, type StateSnapshot, StateGraph } from '@langchain/langgraph';
|
|
62
|
-
import {
|
|
62
|
+
import { flushHeld } from '../calls.ts';
|
|
63
|
+
import { fromTool, stopSignalOf } from '../common.ts';
|
|
63
64
|
import type { Conversation, Run, Turn } from '../conversation.ts';
|
|
64
|
-
import {
|
|
65
|
+
import { companionHere } from '../companion.ts';
|
|
65
66
|
import { SqlCheckpointSaver } from './checkpointer.ts';
|
|
66
67
|
import { running } from './context.ts';
|
|
67
68
|
import { terminalOf } from './errors.ts';
|
|
@@ -154,15 +155,12 @@ async function answerOf(app: App, turn: Turn<BaseMessage>, state: Record<string,
|
|
|
154
155
|
* `prompt`), as the state holds the earlier turns too; if the graph trimmed
|
|
155
156
|
* the prompt away, those whose ids are not `known`. `known` is the ids the
|
|
156
157
|
* conversation has, which this adds to; the messages the conversation gave
|
|
157
|
-
* the graph are not copied back.
|
|
158
|
+
* the graph are not copied back. Tool messages that follow one another (a
|
|
159
|
+
* step's results) are copied in one write. Each write that commits is
|
|
160
|
+
* published, by the conversation (`Conversation.hold`); an AI message without
|
|
161
|
+
* tool calls is held, and is published with the next.
|
|
158
162
|
*/
|
|
159
|
-
async function copied(
|
|
160
|
-
ctx: restate.SessionContext,
|
|
161
|
-
turn: Turn<BaseMessage>,
|
|
162
|
-
known: Set<string>,
|
|
163
|
-
messages: readonly BaseMessage[],
|
|
164
|
-
prompt: string,
|
|
165
|
-
) {
|
|
163
|
+
async function copied(turn: Turn<BaseMessage>, known: Set<string>, messages: readonly BaseMessage[], prompt: string) {
|
|
166
164
|
const at = messages.findIndex((m) => m.id === prompt);
|
|
167
165
|
const fresh = messages
|
|
168
166
|
.slice(at + 1)
|
|
@@ -173,12 +171,24 @@ async function copied(
|
|
|
173
171
|
!known.has(m.id) &&
|
|
174
172
|
!CARRIED.some((prefix) => m.id!.startsWith(prefix)),
|
|
175
173
|
);
|
|
174
|
+
let results: BaseMessage[] = [];
|
|
175
|
+
// The results of a step in one write: one commit, however many tools ran.
|
|
176
|
+
const stored = async () => {
|
|
177
|
+
if (results.length === 0) return;
|
|
178
|
+
await turn.append(...results);
|
|
179
|
+
for (const result of results) known.add(result.id!);
|
|
180
|
+
results = [];
|
|
181
|
+
};
|
|
176
182
|
for (const message of fresh) {
|
|
177
|
-
if (AIMessage.isInstance(message))
|
|
178
|
-
|
|
183
|
+
if (!AIMessage.isInstance(message)) {
|
|
184
|
+
results.push(message);
|
|
185
|
+
continue;
|
|
186
|
+
}
|
|
187
|
+
await stored();
|
|
188
|
+
await turn.appendReply([message]);
|
|
179
189
|
known.add(message.id!);
|
|
180
190
|
}
|
|
181
|
-
|
|
191
|
+
await stored();
|
|
182
192
|
}
|
|
183
193
|
|
|
184
194
|
/** The id of a turn's prompt, as a `HumanMessage` in the graph: the conversation's id of the turn. */
|
|
@@ -276,6 +286,10 @@ async function resumesOf(ctx: restate.SessionContext, saver: SqlCheckpointSaver)
|
|
|
276
286
|
async function resumed(ctx: restate.SessionContext, saver: SqlCheckpointSaver, snapshot: StateSnapshot) {
|
|
277
287
|
const pending = interruptsOf(snapshot);
|
|
278
288
|
if (pending.length === 0) return undefined;
|
|
289
|
+
// Checked before anything is stored: an object without a companion has no one to wait with.
|
|
290
|
+
const companion = companionHere(ctx, 'a wait for an interrupt');
|
|
291
|
+
// What the turn holds back is written before it waits: the waits outlive the attempt.
|
|
292
|
+
await flushHeld(ctx);
|
|
279
293
|
const resumes = await resumesOf(ctx, saver);
|
|
280
294
|
const values = await Promise.all(
|
|
281
295
|
pending.map(({ id, value }) => {
|
|
@@ -283,7 +297,7 @@ async function resumed(ctx: restate.SessionContext, saver: SqlCheckpointSaver, s
|
|
|
283
297
|
// As JSON, which the companion stores: the state may hold class instances.
|
|
284
298
|
const input = value === undefined ? undefined : (JSON.parse(JSON.stringify(value)) as unknown);
|
|
285
299
|
return ctx
|
|
286
|
-
.rpc(
|
|
300
|
+
.rpc(companion, ctx.key, { idempotencyKey: waitId })
|
|
287
301
|
.wait({ id: waitId, name: INTERRUPT, ...(input === undefined ? {} : { input }) });
|
|
288
302
|
}),
|
|
289
303
|
);
|
|
@@ -352,7 +366,7 @@ async function runGraph(
|
|
|
352
366
|
};
|
|
353
367
|
if (asked && snapshot.next.length === 0) {
|
|
354
368
|
// The run had finished, but its answer was not stored: that is the answer, rather than run again.
|
|
355
|
-
await copied(
|
|
369
|
+
await copied(turn, known, messages, promptId);
|
|
356
370
|
await saver.prune([THREAD_ID]);
|
|
357
371
|
return answerOf(run, turn, values, before);
|
|
358
372
|
}
|
|
@@ -371,7 +385,7 @@ async function runGraph(
|
|
|
371
385
|
try {
|
|
372
386
|
for await (const state of await run.stream(start, options)) {
|
|
373
387
|
values = state;
|
|
374
|
-
await copied(
|
|
388
|
+
await copied(turn, known, (state.messages ?? []) as BaseMessage[], promptId);
|
|
375
389
|
}
|
|
376
390
|
} catch (error) {
|
|
377
391
|
// LangGraph's own error, which a retry would meet again: a run past its recursion limit, say.
|
package/src/langgraph/index.ts
CHANGED
|
@@ -19,10 +19,11 @@
|
|
|
19
19
|
// of the conversation (`history()`: the earlier turns as their prompts and
|
|
20
20
|
// answers, the latest whole):
|
|
21
21
|
// - The model node stores its reply before it returns, and the tools node
|
|
22
|
-
//
|
|
23
|
-
//
|
|
24
|
-
//
|
|
25
|
-
// asking the model again.
|
|
22
|
+
// the round's results in one write, once its tools have run. So a crash
|
|
23
|
+
// during the tools runs the round's calls again (those that had finished
|
|
24
|
+
// too), with the same tool call ids, which a tool passes on to stay
|
|
25
|
+
// idempotent, without asking the model again. The final reply is stored
|
|
26
|
+
// with the turn's answer.
|
|
26
27
|
// - A tool's error fails the attempt, which Restate retries (the ToolNode
|
|
27
28
|
// would hand it to the model as the tool's result); a call of a tool the
|
|
28
29
|
// agent lacks, or with arguments that do not fit, is the model's to fix.
|
|
@@ -52,10 +53,9 @@ import {
|
|
|
52
53
|
modelOf,
|
|
53
54
|
providerOf,
|
|
54
55
|
RETURNED_UNRECORDED,
|
|
56
|
+
toolCallStarted,
|
|
55
57
|
stopSignalOf,
|
|
56
58
|
type Summarize,
|
|
57
|
-
toolCallEnded,
|
|
58
|
-
toolCallStarted,
|
|
59
59
|
NO_ANSWER,
|
|
60
60
|
} from '../common.ts';
|
|
61
61
|
import { answerOnce, type Conversation, type Items, type Run, type Turn } from '../conversation.ts';
|
|
@@ -66,7 +66,7 @@ import { type Definition, sessionObject } from '../object.ts';
|
|
|
66
66
|
import { takeSteers } from '../steering.ts';
|
|
67
67
|
import { isTool, jsonSchemaOf, type Tool as AnyTool } from '../tools.ts';
|
|
68
68
|
|
|
69
|
-
import { SqlCheckpointSaver } from './checkpointer.ts';
|
|
69
|
+
import { SCHEMA as CHECKPOINTS, SqlCheckpointSaver } from './checkpointer.ts';
|
|
70
70
|
import { handlerContext } from './context.ts';
|
|
71
71
|
import { terminalOf } from './errors.ts';
|
|
72
72
|
import { type AnyGraph, check as checkGraph, graphRun } from './graph.ts';
|
|
@@ -154,11 +154,14 @@ const failing = (
|
|
|
154
154
|
* The tools node: each tool call of the turn without a result run by a
|
|
155
155
|
* ToolNode, which answers the model with what is wrong when a call names a
|
|
156
156
|
* tool the agent does not have, or arguments that do not fit (the model's to
|
|
157
|
-
* fix: failing the attempt, every retry would meet the same call again).
|
|
158
|
-
*
|
|
159
|
-
*
|
|
160
|
-
*
|
|
161
|
-
*
|
|
157
|
+
* fix: failing the attempt, every retry would meet the same call again). The
|
|
158
|
+
* round's results are stored in one write, once its tools have run: one
|
|
159
|
+
* commit per round, however many tools ran (a crash before it runs the
|
|
160
|
+
* round's calls again, as tools are idempotent by their call ids). Any other
|
|
161
|
+
* error of a tool fails the attempt, at once (the ToolNode would hand it to
|
|
162
|
+
* the model too). The conversation publishes the round's reply as it
|
|
163
|
+
* commits, before the tools run, and their results as they commit, for the
|
|
164
|
+
* clients that follow it.
|
|
162
165
|
*/
|
|
163
166
|
function toolsNode(ctx: restate.SessionContext, turn: Turn<BaseMessage>, tools: StructuredToolInterface[]) {
|
|
164
167
|
return async (_state: typeof MessagesAnnotation.State, config: RunnableConfig) => {
|
|
@@ -180,13 +183,12 @@ function toolsNode(ctx: restate.SessionContext, turn: Turn<BaseMessage>, tools:
|
|
|
180
183
|
messages: BaseMessage[];
|
|
181
184
|
};
|
|
182
185
|
// A tool's error fails the attempt: the ToolNode's answer to the model of it is not the call's result.
|
|
183
|
-
|
|
184
|
-
await turn.append(...ran.messages);
|
|
185
|
-
return ran.messages;
|
|
186
|
+
return broken ? [] : ran.messages;
|
|
186
187
|
};
|
|
187
188
|
const calls = turn.openCalls().map((c) => ({ id: c.id, name: c.name, args: c.input as Record<string, unknown> }));
|
|
188
189
|
const ran = await Promise.race([Promise.all(calls.map(one)), failure]);
|
|
189
|
-
|
|
190
|
+
// The round's results in one write, in the order of their calls: published as it commits.
|
|
191
|
+
await turn.append(...ran.flat());
|
|
190
192
|
return { messages: ran.flat() };
|
|
191
193
|
};
|
|
192
194
|
}
|
|
@@ -403,7 +405,12 @@ export const prompt = <O extends z.ZodObject | undefined = undefined>(
|
|
|
403
405
|
if (graph !== undefined) {
|
|
404
406
|
// The graph keeps its own history: the conversation loads the previous turn whole, for what closed it.
|
|
405
407
|
return withChecked(text, options, (t, _options, check) =>
|
|
406
|
-
answerOnce(ctx, t, items, graphRun(ctx, graph, context), {
|
|
408
|
+
answerOnce(ctx, t, items, graphRun(ctx, graph, context), {
|
|
409
|
+
check,
|
|
410
|
+
window: 1,
|
|
411
|
+
budget: 0,
|
|
412
|
+
schemas: [CHECKPOINTS],
|
|
413
|
+
}),
|
|
407
414
|
) as Promise<Answer<O>>;
|
|
408
415
|
}
|
|
409
416
|
return withChecked(text, options, async (t, { model, system, tools: given = [], recursionLimit }, check, reminder) =>
|
package/src/langgraph/nodes.ts
CHANGED
|
@@ -25,7 +25,9 @@
|
|
|
25
25
|
// and its `signal` view resolves it.
|
|
26
26
|
import type * as restate from '@restatedev/sessions';
|
|
27
27
|
import type { LangGraphRunnableConfig } from '@langchain/langgraph';
|
|
28
|
-
import {
|
|
28
|
+
import { flushHeld } from '../calls.ts';
|
|
29
|
+
import { companionHere } from '../companion.ts';
|
|
30
|
+
import { runWorkflow } from '../tools.ts';
|
|
29
31
|
import { handlerContext } from './context.ts';
|
|
30
32
|
|
|
31
33
|
/** A LangGraph node: it takes the state and the run's config, and returns the state's update. */
|
|
@@ -53,8 +55,12 @@ const CHECKPOINTER = '__pregel_checkpointer';
|
|
|
53
55
|
const DURABILITY = '__pregel_durability';
|
|
54
56
|
const TASK_ID = '__pregel_task_id';
|
|
55
57
|
|
|
56
|
-
/**
|
|
57
|
-
|
|
58
|
+
/**
|
|
59
|
+
* The run of a node of `kind`, from LangGraph's config. The rows the turn
|
|
60
|
+
* holds back are written first (`flushHeld`): the node's call, send or wait
|
|
61
|
+
* outlives the attempt.
|
|
62
|
+
*/
|
|
63
|
+
async function stepOf(config: LangGraphRunnableConfig, kind: string): Promise<Step> {
|
|
58
64
|
const ctx = handlerContext(config.context);
|
|
59
65
|
if (!ctx) {
|
|
60
66
|
throw new TypeError(
|
|
@@ -82,6 +88,7 @@ function stepOf(config: LangGraphRunnableConfig, kind: string): Step {
|
|
|
82
88
|
// run again from that checkpoint gets the same one. It holds the subgraph's path too.
|
|
83
89
|
const namespace = String(configurable.checkpoint_ns || configurable[TASK_ID]);
|
|
84
90
|
const node = namespace.split('|').at(-1)!.split(':')[0]!;
|
|
91
|
+
await flushHeld(ctx);
|
|
85
92
|
return { ctx, node, idempotencyKey: `langgraph:${ctx.key}:${namespace}` };
|
|
86
93
|
}
|
|
87
94
|
|
|
@@ -104,14 +111,14 @@ export const waitForSignal =
|
|
|
104
111
|
// oxlint-disable-next-line typescript/no-explicit-any -- any graph's state
|
|
105
112
|
(name: string, { output, input }: { output?: string; input?: (state: any) => unknown } = {}): Node =>
|
|
106
113
|
async (state, config) => {
|
|
107
|
-
const step = stepOf(config, 'waitForSignal');
|
|
114
|
+
const step = await stepOf(config, 'waitForSignal');
|
|
108
115
|
// The wait's id starts with the invocation's (the same in each attempt), as the waits of tools do, so that a
|
|
109
116
|
// turn that ends without it (killed, say) has it closed: the companion closes the waits whose ids start with
|
|
110
117
|
// the turn's.
|
|
111
118
|
const id = `${step.ctx.request.id}:${step.idempotencyKey}`;
|
|
112
119
|
const shown = input === undefined ? {} : { input: plain(input(state)) };
|
|
113
120
|
const value = await step.ctx
|
|
114
|
-
.rpc(
|
|
121
|
+
.rpc(companionHere(step.ctx, 'a wait for a signal'), step.ctx.key, { idempotencyKey: id })
|
|
115
122
|
.wait({ id, name, ...shown });
|
|
116
123
|
return update(output, value);
|
|
117
124
|
};
|
|
@@ -146,14 +153,12 @@ function checkKey(target: Target, key: unknown) {
|
|
|
146
153
|
export const call = <M>(target: Target<M>, handler: keyof M & string, options: CallOptions = {}): Node => {
|
|
147
154
|
checkKey(target, options.key);
|
|
148
155
|
return async (state, config) => {
|
|
149
|
-
const { ctx, idempotencyKey } = stepOf(config, 'call');
|
|
150
|
-
const
|
|
151
|
-
|
|
152
|
-
handler
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
idempotencyKey,
|
|
156
|
-
});
|
|
156
|
+
const { ctx, idempotencyKey } = await stepOf(config, 'call');
|
|
157
|
+
const parameters = { service: target.name, key: options.key?.(state), input: plain(options.input?.(state)) };
|
|
158
|
+
const result =
|
|
159
|
+
'workflow' in target && handler === 'run'
|
|
160
|
+
? await runWorkflow(ctx, { ...parameters, key: parameters.key! })
|
|
161
|
+
: await ctx.rpc({ ...parameters, handler, idempotencyKey });
|
|
157
162
|
return update(options.output, result);
|
|
158
163
|
};
|
|
159
164
|
};
|
|
@@ -171,7 +176,7 @@ export const send = <M>(
|
|
|
171
176
|
): Node => {
|
|
172
177
|
checkKey(target, options.key);
|
|
173
178
|
return async (state, config) => {
|
|
174
|
-
const { ctx, idempotencyKey } = stepOf(config, 'send');
|
|
179
|
+
const { ctx, idempotencyKey } = await stepOf(config, 'send');
|
|
175
180
|
ctx.send({
|
|
176
181
|
service: target.name,
|
|
177
182
|
handler,
|
|
@@ -187,20 +192,19 @@ export const send = <M>(
|
|
|
187
192
|
/**
|
|
188
193
|
* A node that runs the workflow `target` (its `run` handler) to the end, and
|
|
189
194
|
* writes its result to `output`. The workflow's id is `key`'s, or one of the
|
|
190
|
-
* node's own, made of the agent's key and the node's task
|
|
195
|
+
* node's own, made of the agent's key and the node's task. Run again, the
|
|
196
|
+
* node waits for the run it started (see `runWorkflow` in tools.ts):
|
|
191
197
|
*
|
|
192
198
|
* graph.addNode('ship', nodes.workflow(shipping, { input: (s) => s.order, output: 'receipt' }))
|
|
193
199
|
*/
|
|
194
200
|
export const workflow =
|
|
195
201
|
(target: restate.WorkflowDefinition<string, { run: unknown }>, { output, input, key }: CallOptions = {}): Node =>
|
|
196
202
|
async (state, config) => {
|
|
197
|
-
const { ctx, idempotencyKey } = stepOf(config, 'workflow');
|
|
198
|
-
const result = await ctx
|
|
203
|
+
const { ctx, idempotencyKey } = await stepOf(config, 'workflow');
|
|
204
|
+
const result = await runWorkflow(ctx, {
|
|
199
205
|
service: target.name,
|
|
200
|
-
handler: 'run',
|
|
201
206
|
key: key?.(state) ?? idempotencyKey,
|
|
202
207
|
input: plain(input?.(state)),
|
|
203
|
-
idempotencyKey,
|
|
204
208
|
});
|
|
205
209
|
return update(output, result);
|
|
206
210
|
};
|
|
@@ -231,7 +235,7 @@ export const subagent =
|
|
|
231
235
|
},
|
|
232
236
|
): Node =>
|
|
233
237
|
async (state, config) => {
|
|
234
|
-
const { ctx, node, idempotencyKey } = stepOf(config, 'subagent');
|
|
238
|
+
const { ctx, node, idempotencyKey } = await stepOf(config, 'subagent');
|
|
235
239
|
const answer = await ctx.rpc({
|
|
236
240
|
service: agent.name,
|
|
237
241
|
handler,
|