@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.
Files changed (101) hide show
  1. package/README.md +104 -38
  2. package/dist/calls.d.ts +20 -1
  3. package/dist/calls.d.ts.map +1 -1
  4. package/dist/calls.js +46 -7
  5. package/dist/calls.js.map +1 -1
  6. package/dist/claude/index.d.ts +11 -11
  7. package/dist/claude/index.d.ts.map +1 -1
  8. package/dist/claude/index.js +9 -6
  9. package/dist/claude/index.js.map +1 -1
  10. package/dist/client.d.ts +1 -1
  11. package/dist/client.d.ts.map +1 -1
  12. package/dist/common.d.ts +62 -23
  13. package/dist/common.d.ts.map +1 -1
  14. package/dist/common.js +67 -38
  15. package/dist/common.js.map +1 -1
  16. package/dist/{signals.d.ts → companion.d.ts} +106 -43
  17. package/dist/companion.d.ts.map +1 -0
  18. package/dist/companion.js +463 -0
  19. package/dist/companion.js.map +1 -0
  20. package/dist/conversation.d.ts +115 -5
  21. package/dist/conversation.d.ts.map +1 -1
  22. package/dist/conversation.js +308 -79
  23. package/dist/conversation.js.map +1 -1
  24. package/dist/deepseek/index.d.ts +11 -11
  25. package/dist/deepseek/index.d.ts.map +1 -1
  26. package/dist/deepseek/index.js +23 -26
  27. package/dist/deepseek/index.js.map +1 -1
  28. package/dist/index.d.ts +8 -4
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +7 -3
  31. package/dist/index.js.map +1 -1
  32. package/dist/langgraph/checkpointer.d.ts +2 -0
  33. package/dist/langgraph/checkpointer.d.ts.map +1 -1
  34. package/dist/langgraph/checkpointer.js +1 -1
  35. package/dist/langgraph/checkpointer.js.map +1 -1
  36. package/dist/langgraph/graph.d.ts.map +1 -1
  37. package/dist/langgraph/graph.js +32 -13
  38. package/dist/langgraph/graph.js.map +1 -1
  39. package/dist/langgraph/index.d.ts +11 -11
  40. package/dist/langgraph/index.d.ts.map +1 -1
  41. package/dist/langgraph/index.js +19 -13
  42. package/dist/langgraph/index.js.map +1 -1
  43. package/dist/langgraph/nodes.d.ts +2 -1
  44. package/dist/langgraph/nodes.d.ts.map +1 -1
  45. package/dist/langgraph/nodes.js +23 -20
  46. package/dist/langgraph/nodes.js.map +1 -1
  47. package/dist/object.d.ts +24 -22
  48. package/dist/object.d.ts.map +1 -1
  49. package/dist/object.js +16 -11
  50. package/dist/object.js.map +1 -1
  51. package/dist/opencode/db.d.ts +81 -0
  52. package/dist/opencode/db.d.ts.map +1 -0
  53. package/dist/opencode/db.js +249 -0
  54. package/dist/opencode/db.js.map +1 -0
  55. package/dist/opencode/index.d.ts +184 -0
  56. package/dist/opencode/index.d.ts.map +1 -0
  57. package/dist/opencode/index.js +982 -0
  58. package/dist/opencode/index.js.map +1 -0
  59. package/dist/pi/index.d.ts +11 -11
  60. package/dist/pi/index.d.ts.map +1 -1
  61. package/dist/pi/index.js +16 -17
  62. package/dist/pi/index.js.map +1 -1
  63. package/dist/steering.d.ts +2 -1
  64. package/dist/steering.d.ts.map +1 -1
  65. package/dist/steering.js +2 -2
  66. package/dist/steering.js.map +1 -1
  67. package/dist/tools.d.ts +21 -0
  68. package/dist/tools.d.ts.map +1 -1
  69. package/dist/tools.js +54 -14
  70. package/dist/tools.js.map +1 -1
  71. package/dist/webhook.js +1 -1
  72. package/dist/webhook.js.map +1 -1
  73. package/package.json +37 -4
  74. package/src/calls.ts +52 -11
  75. package/src/claude/README.md +4 -2
  76. package/src/claude/index.ts +9 -7
  77. package/src/client.ts +1 -1
  78. package/src/common.ts +99 -40
  79. package/src/companion.ts +674 -0
  80. package/src/conversation.ts +377 -105
  81. package/src/deepseek/README.md +7 -1
  82. package/src/deepseek/index.ts +22 -24
  83. package/src/index.ts +10 -4
  84. package/src/langgraph/README.md +8 -5
  85. package/src/langgraph/checkpointer.ts +1 -1
  86. package/src/langgraph/graph.ts +30 -16
  87. package/src/langgraph/index.ts +24 -17
  88. package/src/langgraph/nodes.ts +24 -20
  89. package/src/object.ts +45 -40
  90. package/src/opencode/README.md +234 -0
  91. package/src/opencode/db.ts +387 -0
  92. package/src/opencode/index.ts +1243 -0
  93. package/src/pi/README.md +6 -1
  94. package/src/pi/index.ts +16 -15
  95. package/src/steering.ts +8 -7
  96. package/src/tools.ts +60 -18
  97. package/src/webhook.ts +1 -1
  98. package/dist/signals.d.ts.map +0 -1
  99. package/dist/signals.js +0 -383
  100. package/dist/signals.js.map +0 -1
  101. package/src/signals.ts +0 -590
@@ -141,7 +141,13 @@ The harness keeps its own event log, and its model's input is the harness's;
141
141
  each flush of the log copies the turn's new messages (the model's replies,
142
142
  the tools' results) into the agent's conversation of turns, in the same
143
143
  transaction: what `messages` shows
144
- ([docs/conversation.md](../../docs/conversation.md)). The harness's input
144
+ ([docs/conversation.md](../../docs/conversation.md)). A flush that copied a
145
+ reply with tool calls, or tools' results, is published once it is stored,
146
+ in a `chat` turn (a `prompt()` in a handler of your own publishes nothing),
147
+ and nothing else is: a tool call's start publishes nothing. The tools of a
148
+ reply run one after another, and each result is flushed with the next call,
149
+ before its tool runs (the checkpoint policy's barrier): one commit, and one
150
+ publish, per tool call. The harness's input
145
151
  stays within the model's context window: as it nears the window (or
146
152
  overflows it), the harness condenses the oldest history into a summary, one
147
153
  more model request, after trimming tool results that are too long
@@ -73,7 +73,6 @@ import {
73
73
  providerOf,
74
74
  RETURNED_UNRECORDED,
75
75
  stopSignalOf,
76
- toolCallEnded,
77
76
  toolCallStarted,
78
77
  } from '../common.ts';
79
78
  import { answerOnce, type Items, type Parsed, type Run, type Turn } from '../conversation.ts';
@@ -455,7 +454,8 @@ const steeredId = (messageId: string) => (messageId.startsWith('steer:') ? messa
455
454
  * to continue (a step of the run's own), nor anything once the run stopped
456
455
  * or `failed()` (the harness's result of a tool that failed the attempt, or
457
456
  * was cancelled, is not the call's): the turn's close, or the retry, says
458
- * how it ended. `resulted` gets the calls whose results it copied.
457
+ * how it ended. `steps` is told when it copied a step that a follower waits
458
+ * for: a reply with tool calls, or a tool's result.
459
459
  */
460
460
  const copying =
461
461
  (
@@ -463,7 +463,7 @@ const copying =
463
463
  turn: Turn<Message>,
464
464
  from: () => number | undefined,
465
465
  failed: () => boolean,
466
- resulted: (calls: string[]) => void,
466
+ steps: () => void,
467
467
  ) =>
468
468
  async (tx: Parameters<NonNullable<SqlSessionPersistence['copy']>>[0], batch: readonly SessionEvent[]) => {
469
469
  const start = from();
@@ -484,9 +484,13 @@ const copying =
484
484
  tx,
485
485
  copied.flatMap(({ steer }) => (steer === undefined ? [] : [steer])),
486
486
  );
487
- resulted(batch.flatMap((e) => (e.seq > start && e.type === 'tool/result' ? [e.data.message.toolCallId] : [])));
487
+ if (copied.some(({ item }) => isStep(item))) steps();
488
488
  };
489
489
 
490
+ /** Whether `m` is a step of a turn that its followers are told of: a reply with tool calls, or a tool's result. */
491
+ const isStep = (m: Message) =>
492
+ m.role === 'tool' || (m.role === 'assistant' && m.content.some((c) => c.type === 'tool-call'));
493
+
490
494
  /**
491
495
  * The run of the harness of `options`, on the conversation: its turn's
492
496
  * latest ask (its prompt, or the message that asked again) asked once, and
@@ -520,14 +524,12 @@ const runOf =
520
524
  const id = again ? MessageId(`prompt:${turn.id}:again`) : promptId(turn.id);
521
525
  // Where the turn's latest ask is in the log, once it is.
522
526
  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
527
  try {
526
528
  const sessionId = SessionId(ctx.key);
527
529
  const options = {
528
530
  agentOptions: route,
529
531
  setup: (agentCtx: Context) => {
530
- for (const t of tools) agentCtx.tools.register(tracked(isTool(t) ? native(t, ctx) : t, ctx, fail, returned));
532
+ for (const t of tools) agentCtx.tools.register(tracked(isTool(t) ? native(t, ctx) : t, ctx, fail));
531
533
  if (approval !== undefined) approving(agentCtx, ctx, approval, fail);
532
534
  },
533
535
  };
@@ -538,8 +540,9 @@ const runOf =
538
540
  agent = started.agent;
539
541
  const found = agent.session.snapshotEvents().length;
540
542
  from = agent.session.snapshotEvents().find((e) => e.type === 'user/message' && e.data.id === id)?.seq;
541
- // A tool call's end is published once a flush stored its result, for followers to read it there.
542
- let ended = false;
543
+ // A flush that copied steps (a reply with tool calls, tools' results) is published once it is stored,
544
+ // for followers to read them there; its answer lists the messages steered to the turn (below).
545
+ let copiedSteps = false;
543
546
  // The harness messages of the steered messages in the log: those before this attempt, and each flush's.
544
547
  const placed = new Set(
545
548
  agent.session
@@ -555,19 +558,19 @@ const runOf =
555
558
  turn,
556
559
  () => from,
557
560
  () => broken,
558
- (calls) => {
559
- for (const call of calls) if (returned.delete(call)) ended = true;
561
+ () => {
562
+ copiedSteps = true;
560
563
  },
561
564
  )(tx, batch);
562
565
  };
563
566
  persistence.flushed = async () => {
564
- if (!ended) return;
565
- ended = false;
567
+ if (!copiedSteps) return;
568
+ copiedSteps = false;
566
569
  // Failing, it fails the attempt, as a tool's error does: never the flush, which is done.
567
- await toolCallEnded(ctx).catch(fail);
570
+ await turn.stepsCommitted().catch(fail);
568
571
  };
569
572
  // The messages steered to the turn, handed to the harness's step inbox as a publish lists them: only
570
- // while a tool call runs or its result is stored, so that a step after them places them, in this turn.
573
+ // once a reply with tool calls or a result is stored, so that a step after them places them, in this turn.
571
574
  const harnessAgent = agent;
572
575
  const given = new Set<string>();
573
576
  unlisten = inboxOf(ctx)?.listen(() => {
@@ -616,25 +619,20 @@ async function cancelTurn(harness: Context, agent: Agent) {
616
619
  }
617
620
 
618
621
  /**
619
- * `definition`, its calls published as they start, and as they end once
620
- * their results are stored (each call that returned is put in `returned`),
621
- * for the clients that follow the conversation; its error failing the
622
- * attempt.
622
+ * `definition`, the calls whose results are stored forgotten as each of its
623
+ * calls starts (its call and its result are published once a flush stores
624
+ * them, `runOf`); its error failing the attempt.
623
625
  */
624
626
  const tracked = (
625
627
  definition: ToolDefinition,
626
628
  ctx: restate.SessionContext,
627
629
  fail: (error: unknown) => void,
628
- returned: Set<string>,
629
630
  ): ToolDefinition => ({
630
631
  ...definition,
631
632
  execute: async (args, exec) => {
632
633
  try {
633
634
  await toolCallStarted(ctx);
634
- const result = await definition.execute(args, exec);
635
- // Its end is published once the harness stored its result (`runOf`).
636
- returned.add(exec.callId);
637
- return result;
635
+ return await definition.execute(args, exec);
638
636
  } catch (error) {
639
637
  fromTool(ctx, error);
640
638
  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 './signals.ts';
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
- /** @restatedev/sessions' `serve`: the services on PORT, with what they need beside them (an agent's `signals`). */
33
- export { serve } from '@restatedev/sessions';
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';
@@ -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 the tools node
118
- each result as it lands.** So a crash during the tools runs those without
119
- a result again, with the same tool call ids, without asking the model
120
- again; and a stored final reply is the answer.
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
@@ -49,7 +49,7 @@ import {
49
49
  import type { DatabaseWriter, Database, SqlValue } from '@restatedev/sessions';
50
50
  import { Schema } from '@restatedev/sessions/internal';
51
51
 
52
- const SCHEMA = new Schema('restate-agents.langgraph', [
52
+ export const SCHEMA = new Schema('restate-agents.langgraph', [
53
53
  `CREATE TABLE restate_langgraph_checkpoints (
54
54
  thread_id TEXT NOT NULL,
55
55
  checkpoint_ns TEXT NOT NULL,
@@ -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 { fromTool, stepped, stopSignalOf } from '../common.ts';
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 { signals, signalsOf } from '../signals.ts';
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. Then publish.
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)) await turn.appendReply([message]);
178
- else await turn.append(message);
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
- if (fresh.length > 0) await stepped(ctx);
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(signals, signalsOf(ctx), { idempotencyKey: waitId })
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(ctx, turn, known, messages, promptId);
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(ctx, turn, known, (state.messages ?? []) as BaseMessage[], promptId);
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.
@@ -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
- // each tool's result as it lands. So a crash during the tools resumes
23
- // those without a result, with the same tool call ids, which a tool passes
24
- // on to stay idempotent; and a stored final reply is the answer, without
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). Each
158
- * result is stored as it lands. Any other error of a tool fails the attempt,
159
- * at once (the ToolNode would hand it to the model too). The round is
160
- * published as it starts and ends, for the clients that follow the
161
- * conversation.
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
- if (broken) return [];
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
- await toolCallEnded(ctx);
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), { check, window: 1, budget: 0 }),
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) =>
@@ -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 { signals, signalsOf } from '../signals.ts';
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
- /** The run of a node of `kind`, from LangGraph's config. */
57
- function stepOf(config: LangGraphRunnableConfig, kind: string): Step {
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(signals, signalsOf(step.ctx), { idempotencyKey: id })
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 result = await ctx.rpc({
151
- service: target.name,
152
- handler,
153
- key: options.key?.(state),
154
- input: plain(options.input?.(state)),
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.rpc({
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,