@restatedev/agents 0.10.3 → 0.11.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 (68) hide show
  1. package/README.md +10 -0
  2. package/dist/agentlib/tools.js +2 -0
  3. package/dist/agentlib/tools.js.map +1 -1
  4. package/dist/calls.d.ts +14 -8
  5. package/dist/calls.d.ts.map +1 -1
  6. package/dist/calls.js +24 -11
  7. package/dist/calls.js.map +1 -1
  8. package/dist/claude/index.d.ts.map +1 -1
  9. package/dist/claude/index.js +33 -4
  10. package/dist/claude/index.js.map +1 -1
  11. package/dist/common.d.ts +12 -0
  12. package/dist/common.d.ts.map +1 -1
  13. package/dist/common.js +30 -0
  14. package/dist/common.js.map +1 -1
  15. package/dist/deepseek/index.d.ts.map +1 -1
  16. package/dist/deepseek/index.js +7 -3
  17. package/dist/deepseek/index.js.map +1 -1
  18. package/dist/langgraph/graph.d.ts.map +1 -1
  19. package/dist/langgraph/graph.js +8 -0
  20. package/dist/langgraph/graph.js.map +1 -1
  21. package/dist/langgraph/index.d.ts.map +1 -1
  22. package/dist/langgraph/index.js +2 -2
  23. package/dist/langgraph/index.js.map +1 -1
  24. package/dist/langgraph/keepalive.d.ts +16 -0
  25. package/dist/langgraph/keepalive.d.ts.map +1 -0
  26. package/dist/langgraph/keepalive.js +51 -0
  27. package/dist/langgraph/keepalive.js.map +1 -0
  28. package/dist/opencode/index.d.ts.map +1 -1
  29. package/dist/opencode/index.js +108 -24
  30. package/dist/opencode/index.js.map +1 -1
  31. package/dist/pi/commits.d.ts +6 -0
  32. package/dist/pi/commits.d.ts.map +1 -0
  33. package/dist/pi/commits.js +3 -0
  34. package/dist/pi/commits.js.map +1 -0
  35. package/dist/pi/index.d.ts +14 -1
  36. package/dist/pi/index.d.ts.map +1 -1
  37. package/dist/pi/index.js +91 -9
  38. package/dist/pi/index.js.map +1 -1
  39. package/dist/pi/keepalive.d.ts +21 -0
  40. package/dist/pi/keepalive.d.ts.map +1 -0
  41. package/dist/pi/keepalive.js +98 -0
  42. package/dist/pi/keepalive.js.map +1 -0
  43. package/dist/pi/storage.d.ts +62 -3
  44. package/dist/pi/storage.d.ts.map +1 -1
  45. package/dist/pi/storage.js +355 -12
  46. package/dist/pi/storage.js.map +1 -1
  47. package/dist/tools.d.ts +9 -0
  48. package/dist/tools.d.ts.map +1 -1
  49. package/dist/tools.js +9 -1
  50. package/dist/tools.js.map +1 -1
  51. package/package.json +3 -3
  52. package/src/agentlib/tools.ts +2 -0
  53. package/src/calls.ts +25 -11
  54. package/src/claude/index.ts +36 -6
  55. package/src/common.ts +32 -0
  56. package/src/deepseek/index.ts +7 -1
  57. package/src/langgraph/README.md +10 -0
  58. package/src/langgraph/graph.ts +7 -0
  59. package/src/langgraph/index.ts +3 -3
  60. package/src/langgraph/keepalive.ts +58 -0
  61. package/src/opencode/README.md +15 -0
  62. package/src/opencode/index.ts +104 -22
  63. package/src/pi/README.md +64 -15
  64. package/src/pi/commits.ts +7 -0
  65. package/src/pi/index.ts +116 -7
  66. package/src/pi/keepalive.ts +121 -0
  67. package/src/pi/storage.ts +382 -10
  68. package/src/tools.ts +12 -1
@@ -71,6 +71,11 @@
71
71
  // `approval`, its tool call waits for a person's approval, through Restate
72
72
  // (`permissionPlugin`).
73
73
  //
74
+ // The attempt is kept alive (`ctx.working`) while OpenCode's turn runs, its
75
+ // own tools (shell, read, edit...) included, but not while a tool of yours
76
+ // executes (it says so itself: `tool({ keepalive })`), nor while an approval
77
+ // is waited for (`gateOf`): OpenCode has no hook at the end of a model's request.
78
+ //
74
79
  // TODO: a change of `model` on an existing session.
75
80
  import * as restate from '@restatedev/sessions';
76
81
  import { database, reset } from '@restatedev/sessions/internal';
@@ -89,6 +94,7 @@ import {
89
94
  configured,
90
95
  fromTool,
91
96
  inboxOf,
97
+ keepAlive,
92
98
  modelOf,
93
99
  providerOf,
94
100
  refusal,
@@ -506,6 +512,58 @@ const active = async (host: Host) => {
506
512
  return turns[SESSION as string] !== undefined;
507
513
  };
508
514
 
515
+ /**
516
+ * Keeps the attempt alive (`ctx.working`) while OpenCode's turn runs, but
517
+ * not while a tool that is not kept alive executes, nor while a wait on
518
+ * Restate is made: OpenCode has no hook at the end of a model's request, so
519
+ * the turn's scope minus those windows is the nearest. The scope is open
520
+ * exactly while a turn is running (`turn`) and nothing is paused (`pause`:
521
+ * a set of ids, since tools may overlap, and a pause is made once per id).
522
+ * `end` closes it for good, whichever way the attempt ends.
523
+ */
524
+ function gateOf(ctx: restate.SessionContext) {
525
+ let turns = 0;
526
+ let closed = false;
527
+ const paused = new Set<string>();
528
+ let release: (() => void) | undefined;
529
+ const sync = () => {
530
+ const open = !closed && turns > 0 && paused.size === 0;
531
+ if (open && !release) release = keepAlive(ctx);
532
+ else if (!open && release) {
533
+ release();
534
+ release = undefined;
535
+ }
536
+ };
537
+ return {
538
+ /** Run `fn` as a turn: the scope is open meanwhile, unless paused. Closed on every way out. */
539
+ async turn<T>(fn: () => Promise<T>): Promise<T> {
540
+ turns++;
541
+ sync();
542
+ try {
543
+ return await fn();
544
+ } finally {
545
+ turns--;
546
+ if (turns === 0) paused.clear();
547
+ sync();
548
+ }
549
+ },
550
+ pause(id: string) {
551
+ paused.add(id);
552
+ sync();
553
+ },
554
+ resume(id: string) {
555
+ paused.delete(id);
556
+ sync();
557
+ },
558
+ end() {
559
+ closed = true;
560
+ paused.clear();
561
+ sync();
562
+ },
563
+ };
564
+ }
565
+ type Gate = ReturnType<typeof gateOf>;
566
+
509
567
  /** How long a prompt's turn may be neither running nor ended: one resumed at boot starts well within it. */
510
568
  const STALLED_MS = 5_000;
511
569
 
@@ -845,6 +903,7 @@ function permissionPlugin(
845
903
  ctx: restate.SessionContext,
846
904
  approval: boolean,
847
905
  fail: (error: unknown) => Promise<never>,
906
+ gate: Gate,
848
907
  ): Plugin.Plugin {
849
908
  return {
850
909
  id: 'restate-agents.permission',
@@ -865,7 +924,12 @@ function permissionPlugin(
865
924
  const call = calls.get(callId);
866
925
  const asked = { ...call, action: event.action, resources: [...event.resources] };
867
926
  // An error of the wait fails the attempt: the ask never settles.
868
- const value = await waitFor(ctx, callId, APPROVAL, asked, { approval: true, rejoin: true }).catch(fail);
927
+ // A wait on Restate is never inside a scope, whatever tool it is of (one kept alive, say).
928
+ const waiting = `approval:${callId}`;
929
+ gate.pause(waiting);
930
+ const value = await waitFor(ctx, callId, APPROVAL, asked, { approval: true, rejoin: true })
931
+ .catch(fail)
932
+ .finally(() => gate.resume(waiting));
869
933
  const decision = decided(value);
870
934
  if (decision.allowed) {
871
935
  event.effect = 'allow';
@@ -898,6 +962,10 @@ export const withOpenCode = async <T>(
898
962
  const workspace = typeof where === 'function' ? await where(ctx) : where;
899
963
  if (workspace) await mkdir(workspace, { recursive: true });
900
964
  const fence: Fence = { closed: false };
965
+ const gate = gateOf(ctx);
966
+ // OpenCode's own tools (shell, read, edit...) work on the machine and keep the turn alive; ours say so
967
+ // themselves (their `run` opens a scope of its own).
968
+ const ours = new Set(tools.map((t) => t.name));
901
969
  const { promise: failure, reject: failed } = Promise.withResolvers<never>();
902
970
  failure.catch(() => {});
903
971
  // A tool's error ends the attempt: nothing more is stored, and the tool
@@ -991,27 +1059,39 @@ export const withOpenCode = async <T>(
991
1059
  const followPlugin: Plugin.Plugin = {
992
1060
  id: 'restate-agents.follow',
993
1061
  async setup(plugin) {
994
- const before = await plugin.tool.hook('execute.before', async () => {
995
- await copy()
996
- .then(() => toolCallStarted(ctx))
997
- .catch(fail);
1062
+ // A tool's window: the hooks run, and the tool executes, with the turn's scope paused (the hooks
1063
+ // copy and publish, which wait on Restate), unless the tool is kept alive: then only the hooks.
1064
+ const before = await plugin.tool.hook('execute.before', async (event) => {
1065
+ gate.pause(event.id);
1066
+ try {
1067
+ await copy()
1068
+ .then(() => toolCallStarted(ctx))
1069
+ .catch(fail);
1070
+ } finally {
1071
+ if (!ours.has(event.tool)) gate.resume(event.id);
1072
+ }
998
1073
  });
999
1074
  const after = await plugin.tool.hook('execute.after', async (event) => {
1000
- if (!inboxOf(ctx)) return;
1001
- const output =
1002
- event.status === 'error'
1003
- ? // As OpenCode stores it: a denied permission's reason, say, not the tool's "Unable to read".
1004
- toSessionError(event.error).message
1005
- : outputOf({ type: 'tool', state: { status: 'completed', ...event.result } as Content['state'] });
1006
- const result: ItemResult = {
1007
- id: event.id,
1008
- name: event.tool,
1009
- output,
1010
- ...(event.status === 'error' ? { error: true } : {}),
1011
- };
1012
- await copy({ result, from: `${event.messageID}/${event.id}` })
1013
- .then(steer)
1014
- .catch(fail);
1075
+ gate.pause(event.id);
1076
+ try {
1077
+ if (!inboxOf(ctx)) return;
1078
+ const output =
1079
+ event.status === 'error'
1080
+ ? // As OpenCode stores it: a denied permission's reason, say, not the tool's "Unable to read".
1081
+ toSessionError(event.error).message
1082
+ : outputOf({ type: 'tool', state: { status: 'completed', ...event.result } as Content['state'] });
1083
+ const result: ItemResult = {
1084
+ id: event.id,
1085
+ name: event.tool,
1086
+ output,
1087
+ ...(event.status === 'error' ? { error: true } : {}),
1088
+ };
1089
+ await copy({ result, from: `${event.messageID}/${event.id}` })
1090
+ .then(steer)
1091
+ .catch(fail);
1092
+ } finally {
1093
+ gate.resume(event.id);
1094
+ }
1015
1095
  });
1016
1096
  return async () => {
1017
1097
  await before.dispose();
@@ -1054,7 +1134,7 @@ export const withOpenCode = async <T>(
1054
1134
  fail,
1055
1135
  workspace !== undefined,
1056
1136
  ),
1057
- permissionPlugin(ctx, approval, fail),
1137
+ permissionPlugin(ctx, approval, fail, gate),
1058
1138
  ...(system ? [systemPlugin(system)] : []),
1059
1139
  // An outage OpenCode would stop retrying fails the attempt, as a tool's error does (never a refusal).
1060
1140
  retryPlugin(retry ?? {}, (error) => void fail(error)),
@@ -1144,7 +1224,8 @@ export const withOpenCode = async <T>(
1144
1224
  }),
1145
1225
  );
1146
1226
  }
1147
- const now = await settled(opened, messageId);
1227
+ // The turn runs from its submit: the scope is open while it does, minus the tools' windows.
1228
+ const now = await gate.turn(() => settled(opened, messageId));
1148
1229
  // A prompt the cancellation's interrupt ended fails with the cancellation.
1149
1230
  if (cancelled) throw cancelled;
1150
1231
  await copy();
@@ -1174,6 +1255,7 @@ export const withOpenCode = async <T>(
1174
1255
  return done;
1175
1256
  } finally {
1176
1257
  stop?.removeEventListener('abort', onStop);
1258
+ gate.end();
1177
1259
  if (turn) live.delete(turn);
1178
1260
  if (booted) {
1179
1261
  const opened = await booted.catch(() => undefined);
package/src/pi/README.md CHANGED
@@ -17,16 +17,17 @@ const assistant = pi.agent({ name: 'assistant', system: 'Answer briefly.', tools
17
17
  await serve(assistant);
18
18
  ```
19
19
 
20
- | Option | What |
21
- | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
22
- | `model` | `provider/model-id`, of any provider pi-ai knows; or else `MODEL`, or else `openai/gpt-6-sol` (`OPENAI_API_KEY`) |
23
- | `models` | A pi-ai model registry, for a provider of your own |
24
- | `system` | The system prompt |
25
- | `tools` | `tool()`s and Restate's tools of `@restatedev/agents`, or pi-durable's `defineTool`s |
26
- | `output` | A zod object: the answer as data, which the agent replies with as JSON, and `chat` answers with (see [Structured answers](../../README.md#structured-answers)) |
27
- | `workspace` | A directory for pi-durable's coding tools (`read`, `write`, `edit`, `bash`), on the local file system; use a sandbox |
28
- | `serviceTier` | OpenAI's service tier for each request: `fast` for its fast mode (priced higher), `flex`, and so on |
29
- | `retry` | How pi asks the model again after a request failed for a reason that passes (an outage, a rate limit): by default without limit, 2 s to a minute apart |
20
+ | Option | What |
21
+ | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
22
+ | `model` | `provider/model-id`, of any provider pi-ai knows; or else `MODEL`, or else `openai/gpt-6-sol` (`OPENAI_API_KEY`) |
23
+ | `models` | A pi-ai model registry, for a provider of your own |
24
+ | `system` | The system prompt |
25
+ | `tools` | `tool()`s and Restate's tools of `@restatedev/agents`, or pi-durable's `defineTool`s |
26
+ | `output` | A zod object: the answer as data, which the agent replies with as JSON, and `chat` answers with (see [Structured answers](../../README.md#structured-answers)) |
27
+ | `workspace` | A directory for pi-durable's coding tools (`read`, `write`, `edit`, `bash`), on the local file system; use a sandbox |
28
+ | `serviceTier` | OpenAI's service tier for each request: `fast` for its fast mode (priced higher), `flex`, and so on |
29
+ | `retry` | How pi asks the model again after a request failed for a reason that passes (an outage, a rate limit): by default without limit, 2 s to a minute apart |
30
+ | `commits` | `'each'` (the default): each pi commit is one write to Restate; `'effects'`: one for all the commits between two effects (see [Through crashes](#through-crashes)) |
30
31
 
31
32
  For a session object of your own, `pi.chat(options)` is the handler and
32
33
  `pi.messages()` the view; `options` may be a function of the invocation's context, such as
@@ -56,9 +57,10 @@ model and persona in the object's database.
56
57
 
57
58
  ## Through crashes
58
59
 
59
- Each pi-durable commit is an SQL transaction in the object's database
60
- ([`storage.ts`](storage.ts)), stored in order with everything else the
61
- handler does. A retried attempt opens the Harness again and carries on:
60
+ By default (`commits: 'each'`), each pi-durable commit is an SQL transaction
61
+ in the object's database ([`storage.ts`](storage.ts)), stored in order with
62
+ everything else the handler does. A retried attempt opens the Harness again
63
+ and carries on:
62
64
 
63
65
  - a prompt is submitted once, by its id (pi-durable's `requestId`, the
64
66
  invocation's id);
@@ -84,16 +86,63 @@ copies its new entries (the model's replies, the tools' results) into the
84
86
  agent's conversation of turns, in the same transaction: what `messages`
85
87
  shows ([docs/conversation.md](../../docs/conversation.md)). A commit that
86
88
  copied a reply with tool calls, or tools' results, is published once it is
87
- done, in a `chat` turn (pi commits each result on its own: one publish each;
88
- a `prompt()` in a handler of your own publishes nothing), and nothing else
89
+ done, in a `chat` turn (with `commits: 'each'`, pi commits each result on its
90
+ own: one publish each; a `prompt()` in a handler of your own publishes nothing), and nothing else
89
91
  is: a tool call's start publishes nothing, so a follower reads the calls
90
92
  once they are stored, and each output once it is. The views show
91
93
  each turn as it was asked and answered, not pi's summaries and handoffs.
92
94
 
95
+ ### One write for each effect
96
+
97
+ A step of a turn makes several pi commits (the preparation, the request, the
98
+ reply, the tool's start, its result), and each costs one round trip to
99
+ Restate: a turn of four model requests and three tool calls makes 30. With
100
+ `commits: 'effects'`, the commits between two effects (a model request, a
101
+ tool call) share one write: the same turn makes 10 (the turn opening, each
102
+ effect's start, the answer, the turn closing); in a `chat` turn that is
103
+ followed, a publish after each round that reads what was steered to it adds
104
+ one for each round. While an effect runs, its own commits (a model's
105
+ progress, a tool's result) are written at once, as with `'each'`; so is
106
+ everything outside a prompt (`work`, a compaction).
107
+
108
+ What `'effects'` keeps: what pi committed before a tool call, or a model call
109
+ that returns a promise, starts is stored before it does, so it never runs
110
+ ahead of its own history (a streamed model request starts while that write is
111
+ in flight, which is harmless: a retry only repeats the request); and what
112
+ anyone else can see (a publish, a Restate call, a send, the
113
+ end of the handler, a `ctx.db` call of your own) comes after a write of all
114
+ of it, never before. A failed pi commit still undoes only itself, and a
115
+ `ctx.db` call from inside one is refused, as with `'each'`.
116
+
117
+ What it gives up: what pi commits in the milliseconds between one effect's
118
+ result and the next effect's start is lost in a crash, and the retried
119
+ attempt does it again from the state that was stored. Tools that start together start
120
+ after one write, and the results of tools that end together are stored in one
121
+ commit, and published once. A `ctx.db` call of yours made while pi has
122
+ commits to write costs one more write (for the commits, which it waits for),
123
+ and no stall. A write of the commits that fails fails the attempt, as a
124
+ failed commit does, though pi was told its commits were done.
125
+
93
126
  The files of a `workspace` are not in the database: they last as long as the
94
127
  disk does, and a coding tool a crash cut off is not run again (the model is
95
128
  told it was interrupted).
96
129
 
130
+ ## Kept alive
131
+
132
+ An attempt of a session object is shut down by Restate after its inactivity
133
+ timeout (a minute), and run again from the start, unless work keeps it alive
134
+ (`ctx.working`). Each request of a model does, wherever pi makes it (a turn's,
135
+ a deferred response's, a compaction's): the agent wraps the model registry (its
136
+ own, or the `models` given), and a request is kept alive from its call until
137
+ its response ends, fails, is abandoned or is aborted. So does each built-in
138
+ coding tool (`read`, `write`, `edit`, `bash`): it works on the machine, and a
139
+ `bash` may run for minutes.
140
+
141
+ A tool of your own is not kept alive: a `tool()` sets `keepalive` if it may
142
+ work for longer than the timeout, or it is cut off, as by a crash (the next
143
+ attempt tells the model it was interrupted, see above). A tool kept alive must
144
+ not wait on Restate (a call, a signal) inside.
145
+
97
146
  ## Run
98
147
 
99
148
  ```sh
@@ -0,0 +1,7 @@
1
+ // The default of the pi option `commits` (index.ts), in one place: the tests
2
+ // of the whole suite set it (test/commits-default.ts) to run the pi suites in
3
+ // both modes.
4
+ import type { Commits } from './storage.ts';
5
+
6
+ /** What `commits` is when an agent does not say. */
7
+ export const commitsDefault: { commits: Commits } = { commits: 'each' };
package/src/pi/index.ts CHANGED
@@ -63,7 +63,9 @@ import {
63
63
  type ConversationRetryPolicy,
64
64
  type ConversationStreamOptions,
65
65
  type ToolRegistration,
66
+ type Wrap,
66
67
  } from '@earendil-works/pi-durable';
68
+ import { keptModels } from './keepalive.ts';
67
69
  import { NodeExecutionEnv } from '@earendil-works/pi-durable/env/node';
68
70
  import { CodingTools } from '@earendil-works/pi-durable/tools';
69
71
  import type { Transaction } from '@restatedev/sessions';
@@ -86,6 +88,7 @@ import {
86
88
  stopSignalOf,
87
89
  toolCallStarted,
88
90
  } from '../common.ts';
91
+ import { holding } from '../calls.ts';
89
92
  import { answerOnce, invocationOf, type Items, type Parsed, type Turn } from '../conversation.ts';
90
93
  import { tookSteers } from '../steering.ts';
91
94
  import { conversationView } from '../messages.ts';
@@ -93,7 +96,8 @@ import { type Answer, withChecked } from '../output.ts';
93
96
  import { type Definition, sessionObject } from '../object.ts';
94
97
  import { isTool, jsonSchemaOf, type Tool as AnyTool } from '../tools.ts';
95
98
  import type { z } from 'zod';
96
- import { openSqlKvStorage, SqlKvDatabase } from './storage.ts';
99
+ import { commitsDefault } from './commits.ts';
100
+ import { type Commits, openSqlKvStorage, SqlKvDatabase } from './storage.ts';
97
101
 
98
102
  /** What `work` gets: `prompt(text)`, the `conversation()`, and the `harness` and chord `context` for anything else. */
99
103
  export interface Pi {
@@ -280,6 +284,17 @@ export interface Options<O extends z.ZodObject | undefined = z.ZodObject | undef
280
284
  * key, an unknown model) is never asked again.
281
285
  */
282
286
  retry?: Partial<ConversationRetryPolicy>;
287
+ /**
288
+ * How pi's commits are written: `'each'` (the default), one write to
289
+ * Restate each, or `'effects'`, one for all the commits between two effects
290
+ * (a model call, a tool call), so that a step of a turn costs about one
291
+ * write, not several. With `'effects'`, what pi commits in the milliseconds
292
+ * between one effect's result and the next effect's start is lost in a
293
+ * crash, and the retry does it again from the same stored state; what
294
+ * others see (a publish, a call, a send, the end of the handler) is
295
+ * written first.
296
+ */
297
+ commits?: Commits;
283
298
  /**
284
299
  * The answer as data: a zod object, whose JSON the agent replies with
285
300
  * (checked), and `chat` and `prompt` answer with (see output.ts).
@@ -287,6 +302,8 @@ export interface Options<O extends z.ZodObject | undefined = z.ZodObject | undef
287
302
  output?: O;
288
303
  }
289
304
 
305
+ export type { Commits };
306
+
290
307
  /** OpenAI's service tiers (its Responses API's `service_tier`). */
291
308
  export type ServiceTier = 'auto' | 'default' | 'fast' | 'flex' | 'priority';
292
309
 
@@ -313,6 +330,9 @@ const native = (t: AnyTool, ctx: restate.SessionContext): ToolRegistration =>
313
330
  }),
314
331
  });
315
332
 
333
+ /** Run an effect (a tool), after what pi committed before it is written, and without batching its own commits. */
334
+ type Effect = <T>(run: () => Promise<T>) => Promise<T>;
335
+
316
336
  /**
317
337
  * The tools of an agent, `system` added to its system prompt, and, with a
318
338
  * `workspace`, pi's coding tools working there, with the environment they
@@ -323,6 +343,8 @@ async function extensions(
323
343
  system: string | undefined,
324
344
  workspace: string | undefined,
325
345
  afterTools: (conversation: ConversationId) => Promise<void>,
346
+ ctx: restate.SessionContext,
347
+ effect: Effect,
326
348
  ) {
327
349
  const registry = createRegistry();
328
350
  registry.install(defineExtension({ name: 'tools', tools }));
@@ -339,6 +361,14 @@ async function extensions(
339
361
  registry.install(CodingTools);
340
362
  // Tell the model where the coding tools work.
341
363
  registry.install(defineExtension({ name: 'workspace', sections: [section('cwd', () => workspace)] }));
364
+ // The coding tools run in `ctx.working`: they work on the machine (a `bash` may run for minutes), and never
365
+ // wait on Restate. Installed after theirs, which they wrap.
366
+ const kept = (t: ToolRegistration): ToolRegistration => ({
367
+ ...t,
368
+ execute: (args, api, context) => effect(() => ctx.working(() => t.execute(args, api, context))),
369
+ });
370
+ const wraps = (CodingTools.tools ?? []).map((t): Wrap => ({ tool: t.name, wrap: kept }));
371
+ registry.install(defineExtension({ name: 'keepalive', wraps }));
342
372
  return { registry, env: () => new NodeExecutionEnv({ cwd: workspace }) };
343
373
  }
344
374
 
@@ -381,7 +411,16 @@ function unanswered(id: string, why: string | null | undefined, detail: unknown,
381
411
  */
382
412
  export const withPi = async <T>(
383
413
  ctx: restate.SessionContext,
384
- { model: named, models, system, tools = [], workspace, serviceTier, retry }: Options,
414
+ {
415
+ model: named,
416
+ models,
417
+ system,
418
+ tools = [],
419
+ workspace,
420
+ serviceTier,
421
+ retry,
422
+ commits = commitsDefault.commits,
423
+ }: Options,
385
424
  work: (pi: Pi) => Promise<T>,
386
425
  ): Promise<T> => {
387
426
  const model = modelOf(named);
@@ -437,10 +476,35 @@ export const withPi = async <T>(
437
476
  // Whether a tool of the round asks to end the run (`terminate`, a handoff): pi then ends the round at its final
438
477
  // boundary, which would start a run of its own for a message submitted there, outside the turn.
439
478
  let ending = false;
479
+ // pi's storage (storage.ts): with `commits: 'effects'` it batches pi's commits, which a failed commit loses
480
+ // (reported to pi as done): that fails the attempt, as a tool's error does.
481
+ const database = new SqlKvDatabase(ctx.db, {
482
+ commits,
483
+ failed: (error) => {
484
+ failed(error);
485
+ cancel(error);
486
+ },
487
+ });
488
+ // With 'each' none of this is there: the code is as it was, without a batch in the way.
489
+ const batching = commits === 'effects';
490
+ const effect: Effect = !batching
491
+ ? (run) => run()
492
+ : async (run) => {
493
+ const ended = database.effectStarted();
494
+ try {
495
+ await database.flush();
496
+ return await run();
497
+ } finally {
498
+ ended();
499
+ }
500
+ };
440
501
  const tracked = (t: ToolRegistration): ToolRegistration => ({
441
502
  ...t,
442
503
  execute: async (args, api, task) => {
504
+ // A tool is an effect: what pi committed before it is written first, and its own commits are not batched.
505
+ const ended = database.effectStarted();
443
506
  try {
507
+ if (batching) await database.flush();
444
508
  await toolCallStarted(ctx);
445
509
  const result = await t.execute(args, api, task);
446
510
  if (result.control?.terminate === true || result.control?.handoff !== undefined) ending = true;
@@ -449,6 +513,8 @@ export const withPi = async <T>(
449
513
  // The tool's error: never taken for the model's provider refusing (a tool may call a model API).
450
514
  fromTool(ctx, error);
451
515
  return stopped(error, task);
516
+ } finally {
517
+ ended();
452
518
  }
453
519
  },
454
520
  });
@@ -460,8 +526,15 @@ export const withPi = async <T>(
460
526
  // A round that may end the run takes no steered message: each waits for the turn's end, then is a turn of its own.
461
527
  const ends = ending;
462
528
  ending = false;
463
- if (!ends) await steering?.(of);
529
+ if (ends) return;
530
+ // The round's results are published before the inbox is read: a message steered while its tools ran is
531
+ // told of by that publish (`INBOX`), and pi places it only if it is submitted now. A turn nobody can
532
+ // steer has nothing to read.
533
+ if (batching && inboxOf(ctx)) await database.flush();
534
+ await steering?.(of);
464
535
  },
536
+ ctx,
537
+ effect,
465
538
  );
466
539
  const settings = {
467
540
  // A task that crashes is run again however often Restate retries the attempt (its retry policy decides):
@@ -475,12 +548,47 @@ export const withPi = async <T>(
475
548
  // pi-durable hands its stream settings to pi-ai's requests as they are: serviceTier is pi-ai's.
476
549
  ...(serviceTier ? { stream: { serviceTier } as ConversationStreamOptions } : {}),
477
550
  };
478
- const database = new SqlKvDatabase(ctx.db);
479
551
  const harness = await Harness.open(
480
552
  await openSqlKvStorage(ctx.db, database),
481
- { models, registry, env, settings },
553
+ // Each request of a model is kept alive, whoever made the registry (see keepalive.ts), and is an effect.
554
+ {
555
+ models: keptModels(
556
+ ctx,
557
+ models,
558
+ batching ? { started: () => database.effectStarted(), flush: () => database.flush() } : undefined,
559
+ ),
560
+ registry,
561
+ env,
562
+ settings,
563
+ },
482
564
  context,
483
565
  );
566
+ if (batching) await database.flush();
567
+
568
+ /**
569
+ * `run`, a prompt's run, with pi's commits batched between effects (`commits: 'effects'`), and written, however
570
+ * it ends, before it returns: what others see of the turn (its close, the next call) comes after.
571
+ */
572
+ const batched = <S, R>(run: (store: S) => Promise<R>): ((store: S) => Promise<R>) =>
573
+ !batching
574
+ ? run
575
+ : async (store: S): Promise<R> => {
576
+ database.armed = true;
577
+ holding(ctx, () => database.flush(), 'pi');
578
+ let ran = false;
579
+ try {
580
+ const result = await run(store);
581
+ ran = true;
582
+ return result;
583
+ } finally {
584
+ database.armed = false;
585
+ holding(ctx, undefined, 'pi');
586
+ // A failed write has failed the attempt already: it never hides the error the run ended with.
587
+ await database.flush().catch((error: unknown) => {
588
+ if (ran) throw error;
589
+ });
590
+ }
591
+ };
484
592
 
485
593
  const prompt = (text: string, check?: Check, reminder?: string) => {
486
594
  // 0.3.0's `prompt(text, id)` took a prompt's id: from JavaScript, it would
@@ -494,7 +602,7 @@ export const withPi = async <T>(
494
602
  ctx,
495
603
  text,
496
604
  items,
497
- async (store) => {
605
+ batched(async (store) => {
498
606
  const current = store.turn;
499
607
  const id = current.id;
500
608
  const root = await conversation();
@@ -565,7 +673,7 @@ export const withPi = async <T>(
565
673
  const reply = entry?.model?.at(-1);
566
674
  if (!reply) throw new restate.TerminalError(`prompt ${id}: no answer entry`);
567
675
  return textOf(reply.content);
568
- },
676
+ }),
569
677
  // pi keeps the model's history: the conversation reads only its latest turns.
570
678
  { check, reminder, ownHistory: true },
571
679
  );
@@ -587,6 +695,7 @@ export const withPi = async <T>(
587
695
  // invocation's own (a retried attempt's) goes on.
588
696
  const working = async () => {
589
697
  await abortLeft((r) => invocationOf(r) === ctx.request.id || r.startsWith('steer:'));
698
+ if (batching) await database.flush();
590
699
  return work({ harness, context, conversation, prompt });
591
700
  };
592
701
  try {