@restatedev/agents 0.10.2 → 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 (77) hide show
  1. package/README.md +11 -1
  2. package/dist/agentlib/agent.js +3 -1
  3. package/dist/agentlib/agent.js.map +1 -1
  4. package/dist/agentlib/model.d.ts +3 -1
  5. package/dist/agentlib/model.d.ts.map +1 -1
  6. package/dist/agentlib/model.js +13 -4
  7. package/dist/agentlib/model.js.map +1 -1
  8. package/dist/agentlib/tools.js +2 -0
  9. package/dist/agentlib/tools.js.map +1 -1
  10. package/dist/calls.d.ts +14 -8
  11. package/dist/calls.d.ts.map +1 -1
  12. package/dist/calls.js +24 -11
  13. package/dist/calls.js.map +1 -1
  14. package/dist/claude/index.d.ts.map +1 -1
  15. package/dist/claude/index.js +33 -4
  16. package/dist/claude/index.js.map +1 -1
  17. package/dist/common.d.ts +12 -0
  18. package/dist/common.d.ts.map +1 -1
  19. package/dist/common.js +30 -0
  20. package/dist/common.js.map +1 -1
  21. package/dist/deepseek/index.d.ts.map +1 -1
  22. package/dist/deepseek/index.js +7 -3
  23. package/dist/deepseek/index.js.map +1 -1
  24. package/dist/langgraph/graph.d.ts.map +1 -1
  25. package/dist/langgraph/graph.js +8 -0
  26. package/dist/langgraph/graph.js.map +1 -1
  27. package/dist/langgraph/index.d.ts.map +1 -1
  28. package/dist/langgraph/index.js +2 -2
  29. package/dist/langgraph/index.js.map +1 -1
  30. package/dist/langgraph/keepalive.d.ts +16 -0
  31. package/dist/langgraph/keepalive.d.ts.map +1 -0
  32. package/dist/langgraph/keepalive.js +51 -0
  33. package/dist/langgraph/keepalive.js.map +1 -0
  34. package/dist/opencode/index.d.ts.map +1 -1
  35. package/dist/opencode/index.js +108 -24
  36. package/dist/opencode/index.js.map +1 -1
  37. package/dist/pi/commits.d.ts +6 -0
  38. package/dist/pi/commits.d.ts.map +1 -0
  39. package/dist/pi/commits.js +3 -0
  40. package/dist/pi/commits.js.map +1 -0
  41. package/dist/pi/index.d.ts +14 -1
  42. package/dist/pi/index.d.ts.map +1 -1
  43. package/dist/pi/index.js +91 -9
  44. package/dist/pi/index.js.map +1 -1
  45. package/dist/pi/keepalive.d.ts +21 -0
  46. package/dist/pi/keepalive.d.ts.map +1 -0
  47. package/dist/pi/keepalive.js +98 -0
  48. package/dist/pi/keepalive.js.map +1 -0
  49. package/dist/pi/storage.d.ts +62 -3
  50. package/dist/pi/storage.d.ts.map +1 -1
  51. package/dist/pi/storage.js +355 -12
  52. package/dist/pi/storage.js.map +1 -1
  53. package/dist/tools.d.ts +9 -0
  54. package/dist/tools.d.ts.map +1 -1
  55. package/dist/tools.js +9 -1
  56. package/dist/tools.js.map +1 -1
  57. package/package.json +5 -5
  58. package/src/agentlib/README.md +5 -5
  59. package/src/agentlib/agent.ts +3 -1
  60. package/src/agentlib/model.ts +10 -4
  61. package/src/agentlib/tools.ts +2 -0
  62. package/src/calls.ts +25 -11
  63. package/src/claude/index.ts +36 -6
  64. package/src/common.ts +32 -0
  65. package/src/deepseek/index.ts +7 -1
  66. package/src/langgraph/README.md +10 -0
  67. package/src/langgraph/graph.ts +7 -0
  68. package/src/langgraph/index.ts +3 -3
  69. package/src/langgraph/keepalive.ts +58 -0
  70. package/src/opencode/README.md +15 -0
  71. package/src/opencode/index.ts +104 -22
  72. package/src/pi/README.md +64 -15
  73. package/src/pi/commits.ts +7 -0
  74. package/src/pi/index.ts +116 -7
  75. package/src/pi/keepalive.ts +121 -0
  76. package/src/pi/storage.ts +382 -10
  77. package/src/tools.ts +12 -1
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 {
@@ -0,0 +1,121 @@
1
+ // pi-durable makes a model's request in this process, through the model
2
+ // registry (`runtime.models`): `streamSimple` for a turn's request, `fetchDeferred`
3
+ // for one a provider answers later, `completeSimple` for a compaction's. A
4
+ // request keeps the attempt alive (`ctx.working`) from its call to its end.
5
+ // `Harness.open({ models })` takes the registry, so each of its requests is
6
+ // covered by wrapping it, with nothing of pi-durable's own patched.
7
+ import type { Models } from '@earendil-works/pi-ai';
8
+ import type { AssistantMessageEventStream } from '@earendil-works/pi-ai';
9
+ import type * as restate from '@restatedev/sessions';
10
+ import { keepAlive } from '../common.ts';
11
+
12
+ /** `Models`' methods that return an event stream: the request is out as it is called, and ends with the stream. */
13
+ const STREAMS = new Set<PropertyKey>(['stream', 'streamSimple', 'streamDeferred']);
14
+
15
+ /** `Models`' methods that return a promise of the request's result: the request is out until it settles. */
16
+ const REQUESTS = new Set<PropertyKey>([
17
+ 'complete',
18
+ 'completeSimple',
19
+ 'fetchDeferred',
20
+ 'cancelDeferred',
21
+ 'generateImages',
22
+ 'classify',
23
+ ]);
24
+
25
+ /**
26
+ * What a request of the model does with pi's batched commits (storage.ts): it
27
+ * is an effect, so what pi committed before it is written, and its own
28
+ * commits are not batched until it is over.
29
+ */
30
+ export interface Effects {
31
+ /** The request starts: commits are written at once until the returned function is called (once at most). */
32
+ started(): () => void;
33
+ /** Write what is batched. */
34
+ flush(): Promise<void>;
35
+ }
36
+
37
+ /**
38
+ * `stream`, kept alive until its response is over: it ends or fails (its
39
+ * `result()` settles: pi-ai ends a stream that is aborted with an error
40
+ * event), its consumer leaves it early, or `signal` aborts. Then `ended`
41
+ * is called too: the same events, and no more, so a stream that none of
42
+ * them reaches never ends its effect, and the batching stays off.
43
+ */
44
+ function keptStream(
45
+ ctx: restate.SessionContext,
46
+ stream: AssistantMessageEventStream,
47
+ signal: AbortSignal | undefined,
48
+ ended: () => void,
49
+ ): AssistantMessageEventStream {
50
+ const alive = keepAlive(ctx);
51
+ const release = () => {
52
+ alive();
53
+ ended();
54
+ };
55
+ stream.result().then(release, release);
56
+ signal?.addEventListener('abort', release, { once: true });
57
+ if (signal?.aborted) release();
58
+ const iterate = stream[Symbol.asyncIterator].bind(stream);
59
+ // A consumer that stops iterating (a `break`, a throw) abandons the stream: the response is not waited for.
60
+ stream[Symbol.asyncIterator] = () => {
61
+ const iterator = iterate();
62
+ return {
63
+ next: (...args) => iterator.next(...args),
64
+ return: (value) => {
65
+ release();
66
+ return iterator.return?.(value) ?? Promise.resolve({ done: true as const, value });
67
+ },
68
+ throw: async (error) => {
69
+ release();
70
+ if (iterator.throw) return iterator.throw(error);
71
+ throw error;
72
+ },
73
+ };
74
+ };
75
+ return stream;
76
+ }
77
+
78
+ /**
79
+ * `models`, each request of whose methods keeps the attempt of `ctx` alive as
80
+ * long as it is out. With `effects`, each is also an effect: a stream's flush
81
+ * is started as the stream is made and not waited for (the request has no
82
+ * effect that must not repeat), a promise-returning method's is waited for.
83
+ */
84
+ export function keptModels<M extends Models>(ctx: restate.SessionContext, models: M, effects?: Effects): M {
85
+ return new Proxy(models, {
86
+ get(target, property) {
87
+ const member: unknown = Reflect.get(target, property, target);
88
+ if (typeof member !== 'function') return member;
89
+ const method = member.bind(target) as (...args: unknown[]) => unknown;
90
+ if (STREAMS.has(property)) {
91
+ return (...args: unknown[]) => {
92
+ const options = args.at(-1) as { signal?: AbortSignal } | undefined;
93
+ const ended = effects?.started() ?? (() => {});
94
+ // A failed flush fails the attempt itself (storage.ts), and is never this request's error.
95
+ void effects?.flush().catch(() => {});
96
+ let stream: AssistantMessageEventStream;
97
+ try {
98
+ stream = method(...args) as AssistantMessageEventStream;
99
+ } catch (error) {
100
+ ended();
101
+ throw error;
102
+ }
103
+ return keptStream(ctx, stream, options?.signal, ended);
104
+ };
105
+ }
106
+ if (REQUESTS.has(property)) {
107
+ if (!effects) return (...args: unknown[]) => ctx.working(() => method(...args) as Promise<unknown>);
108
+ return async (...args: unknown[]) => {
109
+ const ended = effects.started();
110
+ try {
111
+ await effects.flush();
112
+ return await ctx.working(() => method(...args) as Promise<unknown>);
113
+ } finally {
114
+ ended();
115
+ }
116
+ };
117
+ }
118
+ return method;
119
+ },
120
+ });
121
+ }