@restatedev/agents 0.0.0 → 0.1.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 (108) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +688 -2
  3. package/dist/calls.d.ts +29 -0
  4. package/dist/calls.d.ts.map +1 -0
  5. package/dist/calls.js +91 -0
  6. package/dist/calls.js.map +1 -0
  7. package/dist/claude/conversation.d.ts +33 -0
  8. package/dist/claude/conversation.d.ts.map +1 -0
  9. package/dist/claude/conversation.js +95 -0
  10. package/dist/claude/conversation.js.map +1 -0
  11. package/dist/claude/index.d.ts +78 -0
  12. package/dist/claude/index.d.ts.map +1 -0
  13. package/dist/claude/index.js +269 -0
  14. package/dist/claude/index.js.map +1 -0
  15. package/dist/client.d.ts +83 -0
  16. package/dist/client.d.ts.map +1 -0
  17. package/dist/client.js +88 -0
  18. package/dist/client.js.map +1 -0
  19. package/dist/common.d.ts +284 -0
  20. package/dist/common.d.ts.map +1 -0
  21. package/dist/common.js +475 -0
  22. package/dist/common.js.map +1 -0
  23. package/dist/deepseek/index.d.ts +69 -0
  24. package/dist/deepseek/index.d.ts.map +1 -0
  25. package/dist/deepseek/index.js +381 -0
  26. package/dist/deepseek/index.js.map +1 -0
  27. package/dist/deepseek/persistence.d.ts +61 -0
  28. package/dist/deepseek/persistence.d.ts.map +1 -0
  29. package/dist/deepseek/persistence.js +224 -0
  30. package/dist/deepseek/persistence.js.map +1 -0
  31. package/dist/index.d.ts +15 -0
  32. package/dist/index.d.ts.map +1 -0
  33. package/dist/index.js +37 -0
  34. package/dist/index.js.map +1 -0
  35. package/dist/langgraph/checkpointer.d.ts +29 -0
  36. package/dist/langgraph/checkpointer.d.ts.map +1 -0
  37. package/dist/langgraph/checkpointer.js +275 -0
  38. package/dist/langgraph/checkpointer.js.map +1 -0
  39. package/dist/langgraph/index.d.ts +67 -0
  40. package/dist/langgraph/index.d.ts.map +1 -0
  41. package/dist/langgraph/index.js +265 -0
  42. package/dist/langgraph/index.js.map +1 -0
  43. package/dist/log.d.ts +29 -0
  44. package/dist/log.d.ts.map +1 -0
  45. package/dist/log.js +145 -0
  46. package/dist/log.js.map +1 -0
  47. package/dist/object.d.ts +181 -0
  48. package/dist/object.d.ts.map +1 -0
  49. package/dist/object.js +232 -0
  50. package/dist/object.js.map +1 -0
  51. package/dist/opencode/db.d.ts +40 -0
  52. package/dist/opencode/db.d.ts.map +1 -0
  53. package/dist/opencode/db.js +161 -0
  54. package/dist/opencode/db.js.map +1 -0
  55. package/dist/opencode/index.d.ts +101 -0
  56. package/dist/opencode/index.d.ts.map +1 -0
  57. package/dist/opencode/index.js +464 -0
  58. package/dist/opencode/index.js.map +1 -0
  59. package/dist/output.d.ts +17 -0
  60. package/dist/output.d.ts.map +1 -0
  61. package/dist/output.js +81 -0
  62. package/dist/output.js.map +1 -0
  63. package/dist/pi/index.d.ts +90 -0
  64. package/dist/pi/index.d.ts.map +1 -0
  65. package/dist/pi/index.js +313 -0
  66. package/dist/pi/index.js.map +1 -0
  67. package/dist/pi/storage.d.ts +5 -0
  68. package/dist/pi/storage.d.ts.map +1 -0
  69. package/dist/pi/storage.js +41 -0
  70. package/dist/pi/storage.js.map +1 -0
  71. package/dist/signals.d.ts +195 -0
  72. package/dist/signals.d.ts.map +1 -0
  73. package/dist/signals.js +258 -0
  74. package/dist/signals.js.map +1 -0
  75. package/dist/tools.d.ts +158 -0
  76. package/dist/tools.d.ts.map +1 -0
  77. package/dist/tools.js +211 -0
  78. package/dist/tools.js.map +1 -0
  79. package/dist/webhook.d.ts +73 -0
  80. package/dist/webhook.d.ts.map +1 -0
  81. package/dist/webhook.js +104 -0
  82. package/dist/webhook.js.map +1 -0
  83. package/package.json +218 -5
  84. package/src/calls.ts +138 -0
  85. package/src/claude/README.md +84 -0
  86. package/src/claude/conversation.ts +114 -0
  87. package/src/claude/index.ts +364 -0
  88. package/src/client.ts +179 -0
  89. package/src/common.ts +593 -0
  90. package/src/deepseek/README.md +110 -0
  91. package/src/deepseek/index.ts +487 -0
  92. package/src/deepseek/persistence.ts +293 -0
  93. package/src/index.ts +60 -0
  94. package/src/langgraph/README.md +87 -0
  95. package/src/langgraph/checkpointer.ts +364 -0
  96. package/src/langgraph/index.ts +349 -0
  97. package/src/log.ts +193 -0
  98. package/src/object.ts +343 -0
  99. package/src/opencode/README.md +125 -0
  100. package/src/opencode/db.ts +223 -0
  101. package/src/opencode/index.ts +595 -0
  102. package/src/output.ts +95 -0
  103. package/src/pi/README.md +105 -0
  104. package/src/pi/index.ts +402 -0
  105. package/src/pi/storage.ts +65 -0
  106. package/src/signals.ts +426 -0
  107. package/src/tools.ts +343 -0
  108. package/src/webhook.ts +163 -0
@@ -0,0 +1,105 @@
1
+ # pi
2
+
3
+ [pi-durable](https://www.npmjs.com/package/@earendil-works/pi-durable) is a
4
+ durable agent harness: it commits conversations, model turns and tool calls
5
+ to storage, and resumes unfinished work when the storage is opened again.
6
+ Here its storage is the agent's SQL database, in the Restate virtual object
7
+ ([SQL in Restate virtual objects](../../../sessions/README.md)).
8
+
9
+ ## Use
10
+
11
+ ```ts
12
+ import { serve } from '@restatedev/agents';
13
+ import * as pi from '@restatedev/agents/pi';
14
+ import { weather } from './weather.ts';
15
+
16
+ const assistant = pi.agent({ name: 'assistant', system: 'Answer briefly.', tools: [weather] });
17
+ await serve(assistant);
18
+ ```
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
+
30
+ For a session object of your own, `pi.chat(options)` is the handler and
31
+ `pi.messages()` the view; `options` may be a function of the invocation's context, such as
32
+ each user's model from the object's database. `pi.prompt(ctx, text,
33
+ options)` answers a prompt in a handler of your own. For more than a prompt,
34
+ `withPi(ctx, options, work)` runs `work` with the Harness: `prompt(text)`
35
+ answers a prompt once, and `conversation()` is the object's conversation, on
36
+ the model, for pi-durable's own API (`reset`, `compact`, `entries`...):
37
+
38
+ ```ts
39
+ const options = async (ctx: restate.SessionContext): Promise<pi.Options> => ({
40
+ model: (await settingsOf(ctx)).model,
41
+ tools: [clock],
42
+ });
43
+
44
+ handlers: {
45
+ chat: pi.chat(options),
46
+ reset: async (ctx, handoff: string) =>
47
+ pi.withPi(ctx, await options(ctx), async ({ conversation, context }) => (await conversation()).reset(handoff, context)),
48
+ },
49
+ ```
50
+
51
+ A conversation goes on with the model of each invocation: a `model` (or
52
+ MODEL) changed since it started is the model of its next turn.
53
+ [`examples/intermediate/harness.ts`](../../../examples/intermediate/harness.ts) keeps each user's
54
+ model and persona in the object's database.
55
+
56
+ ## Through crashes
57
+
58
+ Each pi-durable commit is an SQL transaction in the object's database
59
+ ([`storage.ts`](storage.ts)), stored in order with everything else the
60
+ handler does. A retried attempt opens the Harness again and carries on:
61
+
62
+ - a prompt is submitted once, by its id (pi-durable's `requestId`, the
63
+ invocation's id);
64
+ - an answered prompt returns its answer;
65
+ - unfinished work resumes: a model call is made again, and a tool call runs
66
+ again with the same call id, which a tool passes on to stay idempotent,
67
+ however often a crash cut it off (pi-durable's `restartLimit` is
68
+ `Infinity`: Restate's retry policy decides);
69
+ - a tool's error fails the attempt, and Restate retries it (pi-durable would
70
+ hand it to the model); a `restate.TerminalError` of a `@restatedev/agents`
71
+ tool is its answer to the model.
72
+
73
+ The files of a `workspace` are not in the database: they last as long as the
74
+ disk does, and a coding tool a crash cut off is not run again (the model is
75
+ told it was interrupted).
76
+
77
+ ## Run
78
+
79
+ ```sh
80
+ cd packages/examples && OPENAI_API_KEY=… node basic/chat.ts
81
+ ```
82
+
83
+ With a Restate server, and the agent registered with it: see
84
+ [Run an example](../../../examples/README.md#run-an-example).
85
+ [`examples/basic/chat.ts`](../../../examples/basic/chat.ts) is a chat agent with a
86
+ tool, and [`examples/intermediate/coding.ts`](../../../examples/intermediate/coding.ts) a pi
87
+ coordinator that hands coding tasks to OpenCode coders.
88
+
89
+ ## Tests
90
+
91
+ The tests run on a scripted model, [`test/fakes/pi.ts`](../../test/fakes/pi.ts),
92
+ which needs no key (`pnpm --filter @restatedev/agents test pi`, from the repository root):
93
+
94
+ - [`test/storage/pi.test.ts`](../../test/storage/pi.test.ts):
95
+ pi-durable's storage conformance suite on the object's database;
96
+ [`pi-workspace.test.ts`](../../test/storage/pi-workspace.test.ts),
97
+ `withPi` with a workspace.
98
+ - [`test/pi-bank.test.ts`](../../test/pi-bank.test.ts):
99
+ the bank agent, with crashes at any of a message's state requests.
100
+ - [`test/pi.test.ts`](../../test/pi.test.ts): the chat,
101
+ its system prompt, `messages`, and sub-agents.
102
+ - [`test/pi.ts`](../../test/pi.ts): the bank agent,
103
+ whose tools move money in the [ledger](../../../sessions/test/ledger.ts)
104
+ with the tool call id as the transfer id, through crashes in
105
+ [the crash test](../../../e2e/crash.ts) (`pnpm --filter e2e crash`).
@@ -0,0 +1,402 @@
1
+ // pi agents in Restate virtual objects: a pi-durable Harness for each
2
+ // invocation, with its storage in the object's database.
3
+ //
4
+ // const assistant = pi.agent({ name: 'assistant', tools: [weather] });
5
+ // const lead = pi.agent({ name: 'lead', tools: [subagent(coder)] });
6
+ //
7
+ // or a handler of an object of your own: `handlers: { chat: pi.chat() }`,
8
+ // with options for each invocation: `pi.chat(async (ctx) => ({ model }))`
9
+ //
10
+ // or, for more than a prompt:
11
+ //
12
+ // compact: (ctx) => withPi(ctx, { tools }, async ({ conversation, context }) => ...),
13
+ //
14
+ // The model is `model`, MODEL, or else openai/gpt-6-sol, with the
15
+ // provider's API key (such as OPENAI_API_KEY).
16
+ //
17
+ // It runs `work` over `ctx.db`: pi-durable's storage is the object's
18
+ // database (storage.ts), and each pi-durable commit is an SQL transaction
19
+ // in it, stored in order with everything else the handler does. The Harness
20
+ // is opened with `tools` (made with pi-durable's `defineTool`) and closed at
21
+ // the end. A retried attempt (a crash, a lost connection) opens it again and
22
+ // carries on: a prompt is submitted once, by its id (pi-durable's requestId),
23
+ // an answered prompt returns its answer, and unfinished work resumes: a model
24
+ // call is made again, and a tool call declared `replay: 'safe'` runs again
25
+ // with the same call id, which a tool passes on to stay idempotent. A tool's
26
+ // error fails the attempt, which Restate retries (pi-durable would hand it to
27
+ // the model as the tool's result).
28
+ //
29
+ // With a `workspace` directory, the agent also gets pi-durable's coding
30
+ // tools (`read`, `write`, `edit`, `bash`) over it, on the local file system.
31
+ // The files are not in the database: they last as long as the disk does,
32
+ // and a coding tool cut off by a crash is not run again (the model is told
33
+ // it was interrupted).
34
+ import * as restate from '@restatedev/sessions';
35
+ import type { Database } from '@restatedev/sessions';
36
+ import type { Context } from '@earendil-works/chord';
37
+ import { awaitWithContext, BACKGROUND_CONTEXT, withCancel, withoutAbortSignal } from '@earendil-works/chord/context';
38
+ import { mkdir } from 'node:fs/promises';
39
+ import { type Message, type MutableModels, Type } from '@earendil-works/pi-ai';
40
+ import { createModels } from '@earendil-works/pi-ai/models';
41
+ import { builtinProviders } from '@earendil-works/pi-ai/providers/all';
42
+ import {
43
+ AssistantEntry,
44
+ createRegistry,
45
+ defineExtension,
46
+ defineTool,
47
+ Harness,
48
+ section,
49
+ type Conversation,
50
+ type ConversationStreamOptions,
51
+ type EntryId,
52
+ type ToolRegistration,
53
+ } from '@earendil-works/pi-durable';
54
+ import { NodeExecutionEnv } from '@earendil-works/pi-durable/env/node';
55
+ import { CodingTools } from '@earendil-works/pi-durable/tools';
56
+ import {
57
+ AttemptEnded,
58
+ chatHandler,
59
+ CHECK_MODEL,
60
+ checkModelName,
61
+ type Configure,
62
+ configured,
63
+ messagesHandler,
64
+ ModelError,
65
+ modelOf,
66
+ nextPromptId,
67
+ providerOf,
68
+ refusal,
69
+ REFUSED,
70
+ settleSteering,
71
+ type Steerable,
72
+ stopSignalOf,
73
+ toolCallEnded,
74
+ toolCallStarted,
75
+ transcribing,
76
+ Transcript,
77
+ } from '../common.ts';
78
+ import { type Answer, withOutput } from '../output.ts';
79
+ import { type Definition, sessionObject } from '../object.ts';
80
+ import { isTool, jsonSchemaOf, type Tool as AnyTool } from '../tools.ts';
81
+ import type { z } from 'zod';
82
+ import { openSqlKvStorage } from './storage.ts';
83
+
84
+ /** What `work` gets: `prompt(text)`, the `conversation()`, and the `harness` and chord `context` for anything else. */
85
+ export interface Pi {
86
+ harness: Harness;
87
+ context: Context;
88
+ /** Answer `text`, once per prompt `id`, with the answer's text. By default, each prompt of an invocation has an id of its own, the same on every attempt. */
89
+ prompt: (text: string, id?: string) => Promise<string>;
90
+ /** The object's conversation, on the model: for `reset`, `compact`, `entries` and the like. */
91
+ conversation: () => Promise<Conversation>;
92
+ }
93
+
94
+ /** The text of a message's content. */
95
+ const textOf = (content: Message['content']): string =>
96
+ typeof content === 'string' ? content : content.flatMap((c) => (c.type === 'text' ? [c.text] : [])).join('');
97
+
98
+ /** An agent's options: `chat`, `prompt` and `withPi` take them. */
99
+ export interface Options<O extends z.ZodObject | undefined = z.ZodObject | undefined> {
100
+ /** The model, as `provider/model-id`: MODEL, or else openai/gpt-6-sol. */
101
+ model?: string;
102
+ /** A pi-ai model registry; by default, one of the model's provider. */
103
+ models?: MutableModels;
104
+ /** The system prompt: who the agent is, and how it answers. */
105
+ system?: string;
106
+ /** The agent's tools: `tool()`s, Restate's (`call`, `signal`...), or pi-durable's `defineTool`s. */
107
+ tools?: (ToolRegistration | AnyTool)[];
108
+ /** A directory for the coding tools, made if missing; without one, the agent has no file system. */
109
+ workspace?: string;
110
+ /** OpenAI's service tier for each request: `fast` for its fast mode (priced higher), `flex`, and so on. */
111
+ serviceTier?: ServiceTier;
112
+ /**
113
+ * The answer as data: a zod object, whose JSON the agent replies with
114
+ * (checked), and `chat` and `prompt` answer with (see output.ts).
115
+ */
116
+ output?: O;
117
+ }
118
+
119
+ /** OpenAI's service tiers (its Responses API's `service_tier`). */
120
+ export type ServiceTier = 'auto' | 'default' | 'fast' | 'flex' | 'priority';
121
+
122
+ /** A registry of `provider`'s models, such as anthropicProvider() of @earendil-works/pi-ai/providers/anthropic. */
123
+ function modelsOf(provider: string): MutableModels {
124
+ // All of pi-ai's providers, imported as they are named: one a bundler sees.
125
+ const known = builtinProviders().find((p) => p.id === provider);
126
+ if (!known) throw new ModelError(`pi knows no model provider "${provider}": ${CHECK_MODEL}`);
127
+ const models = createModels();
128
+ models.setProvider(known);
129
+ return models;
130
+ }
131
+
132
+ /** `t` as a pi-durable tool. */
133
+ const native = (t: AnyTool, ctx: restate.SessionContext): ToolRegistration =>
134
+ defineTool({
135
+ name: t.name,
136
+ description: t.description,
137
+ parameters: Type.Unsafe<Record<string, unknown>>(jsonSchemaOf(t)),
138
+ replay: 'safe', // a crash runs it again, with the same call id
139
+ // Aborted (the conversation's work, on a cancellation), it waits no more.
140
+ execute: async (args, { callId }, task) => ({
141
+ output: [{ type: 'text', text: await awaitWithContext(t.run(args, { ctx, callId }), task) }],
142
+ }),
143
+ });
144
+
145
+ /**
146
+ * The tools of an agent, `system` added to its system prompt, and, with a
147
+ * `workspace`, pi's coding tools working there, with the environment they
148
+ * run in.
149
+ */
150
+ async function extensions(tools: ToolRegistration[], system: string | undefined, workspace: string | undefined) {
151
+ const registry = createRegistry();
152
+ registry.install(defineExtension({ name: 'tools', tools }));
153
+ if (system) registry.install(defineExtension({ name: 'system', sections: [section('system', () => system)] }));
154
+ if (!workspace) return { registry, env: undefined };
155
+ await mkdir(workspace, { recursive: true });
156
+ registry.install(CodingTools);
157
+ // Tell the model where the coding tools work.
158
+ registry.install(defineExtension({ name: 'workspace', sections: [section('cwd', () => workspace)] }));
159
+ return { registry, env: () => new NodeExecutionEnv({ cwd: workspace }) };
160
+ }
161
+
162
+ /**
163
+ * The root conversation of `harness`, on `model`. It keeps the model it was
164
+ * created with: on another one now (`model` or MODEL changed), it moves to
165
+ * this one.
166
+ */
167
+ async function rootOn(harness: Harness, context: Context, model: string): Promise<Conversation> {
168
+ const [provider, modelId] = providerOf(model);
169
+ const root = await harness.root(context, { agent: { model: { provider, modelId } } });
170
+ const { model: current } = await root.agent(context);
171
+ if (current?.provider !== provider || current.modelId !== modelId) {
172
+ await root.configure({ model: { provider, modelId } }, context);
173
+ }
174
+ return root;
175
+ }
176
+
177
+ /**
178
+ * The error of prompt `id`, which ended unanswered for `reason` (and
179
+ * `detail`, pi-durable's): {@link REFUSED} if there is no model, or its
180
+ * provider refused it, as for the other frameworks.
181
+ */
182
+ function unanswered(id: string, why: string | null | undefined, detail: unknown, model: string) {
183
+ const reason = why ?? 'unknown';
184
+ const text =
185
+ detail === undefined || detail === null ? '' : typeof detail === 'string' ? detail : JSON.stringify(detail);
186
+ const message = `prompt ${id} unanswered: ${reason}${text ? `: ${text}` : ''}`;
187
+ if (reason === 'no_model' || (reason === 'model_error' && refusal(new Error(text)))) {
188
+ return new restate.TerminalError(`${message} (the model ${model}: ${CHECK_MODEL})`, { errorCode: REFUSED });
189
+ }
190
+ return new restate.TerminalError(message);
191
+ }
192
+
193
+ /**
194
+ * Run `work(pi)` with a Harness over the object's database: `model` is the
195
+ * model to use as `provider/model-id`, and `tools` the agent's tools. `pi`
196
+ * has `prompt(text)`, and the `harness` and chord `context` for anything
197
+ * else.
198
+ */
199
+ export const withPi = async <T>(
200
+ ctx: restate.SessionContext,
201
+ { model: named, models, system, tools = [], workspace, serviceTier }: Options,
202
+ work: (pi: Pi) => Promise<T>,
203
+ ): Promise<T> => {
204
+ const model = modelOf(named);
205
+ models ??= modelsOf(providerOf(model)[0]);
206
+ // A tool's error fails the attempt, which Restate retries (pi-durable would
207
+ // hand it to the model): the work is cancelled, so the tool call stores no
208
+ // result, and the retry runs it again with the same call id.
209
+ const { context, cancel } = withCancel(BACKGROUND_CONTEXT);
210
+ const { promise: failure, reject: failed } = Promise.withResolvers<never>();
211
+ failure.catch(() => {});
212
+ // A cancelled invocation, whenever it comes, aborts the conversation's
213
+ // work instead (abortOn): pi-durable ends the turn, and the tool call with
214
+ // it. An attempt that ends first cancels the work, as a tool's error does:
215
+ // the next attempt goes on with it.
216
+ let cancelled: restate.CancelledError | undefined;
217
+ const turn = stopSignalOf(ctx);
218
+ const onStop = () => {
219
+ const reason: unknown = turn!.reason;
220
+ failed(reason);
221
+ if (reason instanceof AttemptEnded) cancel(reason);
222
+ else cancelled = reason as restate.CancelledError;
223
+ };
224
+ turn?.addEventListener('abort', onStop, { once: true });
225
+ // The root conversation, once the Harness is open (below).
226
+ const conversation = () => rootOn(harness, context, model);
227
+ // Messages steered to the turn: given as pi-durable's steering input (by
228
+ // its id, once), which the run takes once the round's tools are done.
229
+ const steerable: Steerable = {
230
+ steer: async ({ id, text }) => {
231
+ await (await conversation()).submit({ type: 'input', content: text, requestId: id, whenBusy: 'steer' }, context);
232
+ },
233
+ has: async (id) => {
234
+ const root = await conversation();
235
+ return (await root.commit((tx) => tx.submissionByRequest(root.id, id), context)) !== undefined;
236
+ },
237
+ };
238
+ // A tool call's error: the attempt fails, and the call never returns.
239
+ const stopped = (error: unknown, task: Context): Promise<never> => {
240
+ // The turn was cancelled, and the abort ended the call: pi-durable records it.
241
+ if (cancelled) throw error;
242
+ failed(error);
243
+ if (error instanceof restate.CancelledError) {
244
+ cancelled = error;
245
+ return awaitWithContext(new Promise<never>(() => {}), task);
246
+ }
247
+ cancel(error);
248
+ return awaitWithContext(new Promise<never>(() => {}), context);
249
+ };
250
+ const tracked = (t: ToolRegistration): ToolRegistration => ({
251
+ ...t,
252
+ execute: async (args, api, task) => {
253
+ try {
254
+ await toolCallStarted(ctx);
255
+ const result = await t.execute(args, api, task);
256
+ await toolCallEnded(ctx, steerable);
257
+ return result;
258
+ } catch (error) {
259
+ return stopped(error, task);
260
+ }
261
+ },
262
+ });
263
+ const { registry, env } = await extensions(
264
+ tools.map((t) => tracked(isTool(t) ? native(t, ctx) : t)),
265
+ system,
266
+ workspace,
267
+ );
268
+ const settings = {
269
+ // A task that crashes is run again however often Restate retries the attempt (its retry policy decides):
270
+ // pi-durable would park it after 5 crashes in a row, and the prompt would never be answered.
271
+ restartLimit: Infinity,
272
+ // pi-durable hands its stream settings to pi-ai's requests as they are: serviceTier is pi-ai's.
273
+ ...(serviceTier ? { stream: { serviceTier } as ConversationStreamOptions } : {}),
274
+ };
275
+ const harness = await Harness.open(await openSqlKvStorage(ctx.db), { models, registry, env, settings }, context);
276
+
277
+ const prompt = async (text: string, id = nextPromptId(ctx)) => {
278
+ const root = await conversation();
279
+ const submission = await root.submit({ type: 'input', content: text, requestId: id }, context);
280
+ const settled = await submission.wait(context);
281
+ // A prompt the cancellation's abort ended fails with the cancellation.
282
+ if (settled.status !== 'done' || settled.answer === undefined)
283
+ throw cancelled ?? unanswered(id, settled.reason, settled.detail, model);
284
+ const { answer } = settled;
285
+ const entry = await root.commit((tx) => tx.entry(AssistantEntry, answer), context);
286
+ const reply = entry?.model?.at(-1);
287
+ if (!reply) throw new restate.TerminalError(`prompt ${id}: no answer entry`);
288
+ await settleSteering(ctx, steerable);
289
+ return textOf(reply.content);
290
+ };
291
+ // `failure`, once it comes; a cancellation first aborts the conversation's work.
292
+ const abortOn = async (): Promise<never> => {
293
+ try {
294
+ return await failure;
295
+ } catch (error) {
296
+ if (error instanceof restate.CancelledError) await (await conversation()).abort(context);
297
+ throw error;
298
+ }
299
+ };
300
+
301
+ try {
302
+ // The log reads the root conversation through this Harness, while it is open.
303
+ const read = async () => transcribe(ctx.db, await harness.root(context), context);
304
+ return await transcribing(ctx, read, () =>
305
+ Promise.race([abortOn(), work({ harness, context, conversation, prompt })]),
306
+ );
307
+ } catch (error) {
308
+ // A turn that ends unanswered (cancelled, refused) counts the messages
309
+ // steered to it that the conversation has, given in an earlier attempt
310
+ // too: its close answers only the others. An attempt that ended closes nothing.
311
+ if (!(error instanceof AttemptEnded)) await settleSteering(ctx, steerable).catch(() => {});
312
+ throw error;
313
+ } finally {
314
+ turn?.removeEventListener('abort', onStop);
315
+ await harness.close(withoutAbortSignal(context));
316
+ }
317
+ };
318
+
319
+ /** {@link prompt}, answering with the agent's text. */
320
+ const promptText = (ctx: restate.SessionContext, text: string, options: Options): Promise<string> =>
321
+ withPi(ctx, options, (session) => session.prompt(text));
322
+
323
+ /**
324
+ * Answer `text`, once: a retried attempt resumes the same prompt. Each prompt
325
+ * of an invocation is a prompt of its own.
326
+ * With `output`, it answers with the value the agent replies with (see
327
+ * output.ts), not its text.
328
+ */
329
+ export const prompt = <O extends z.ZodObject | undefined = undefined>(
330
+ ctx: restate.SessionContext,
331
+ text: string,
332
+ options: Options<O> = {},
333
+ ): Promise<Answer<O>> => withOutput(text, options, (t, o) => promptText(ctx, t, o)) as Promise<Answer<O>>;
334
+
335
+ /**
336
+ * A chat handler: each message an invocation, the conversation in the
337
+ * object's database, with `options`, or the options a function of the
338
+ * invocation's context gives (each user's model, say). It takes the message
339
+ * as plain text (`curl -d 'Hi'`) or as a JSON string (`curl --json '"Hi"'`).
340
+ */
341
+ export const chat = <O extends z.ZodObject | undefined = undefined>(options: Configure<Options<O>> = {}) => {
342
+ if (typeof options === 'object') checkModelName('pi', options.model);
343
+ return chatHandler(async (ctx, message) => prompt(ctx, message, await configured(options, ctx)));
344
+ };
345
+
346
+ /**
347
+ * A handler of the conversation as clients read it: a page at a time, or
348
+ * what is new or changed since a cursor, from the log each change writes
349
+ * (log.ts). It answers while a message is answered.
350
+ */
351
+ export const messages = () => messagesHandler();
352
+
353
+ /**
354
+ * The transcript of each session's root conversation (`ctx.db`, one per
355
+ * attempt), as far as it was read, to its last entry. pi-durable's entries
356
+ * never change, and a new one takes a greater id than any before it (they
357
+ * are committed one at a time), so each read adds the entries after it.
358
+ */
359
+ const transcripts = new WeakMap<Database, { last?: EntryId; transcript: Transcript }>();
360
+
361
+ /** The root conversation in `db`, `root` of a Harness on it, from pi-durable's entries, as `messages` gives it. */
362
+ const transcribe = async (db: Database, root: Conversation, context: Context) => {
363
+ const read = transcripts.get(db) ?? { transcript: new Transcript() };
364
+ transcripts.set(db, read);
365
+ const { transcript } = read;
366
+ // From the last entry read (the bound is inclusive), or the first.
367
+ const query = { order: 'ascending' as const, ...(read.last === undefined ? {} : { minEntryId: read.last }) };
368
+ for (let cursor: Parameters<typeof root.entries>[2]; ;) {
369
+ const page = await root.entries(query, 100, cursor, context);
370
+ for (const entry of page.items) {
371
+ if (entry.id === read.last) continue;
372
+ read.last = entry.id;
373
+ for (const m of entry.model ?? []) {
374
+ if (m.role === 'user') transcript.say('user', textOf(m.content));
375
+ if (m.role === 'assistant') {
376
+ transcript.say('assistant', textOf(m.content));
377
+ for (const c of m.content) if (c.type === 'toolCall') transcript.call(c.id, c.name, c.arguments);
378
+ }
379
+ if (m.role === 'toolResult') transcript.result(m.toolCallId, textOf(m.content), m.isError);
380
+ }
381
+ }
382
+ cursor = page.next;
383
+ if (cursor === undefined) return transcript;
384
+ }
385
+ };
386
+
387
+ /** An agent: a virtual object `name`, one per key, whose `chat` handler is {@link chat}, and `messages` {@link messages}. */
388
+ export const agent = <P extends string, O extends z.ZodObject | undefined = undefined>({
389
+ name,
390
+ description,
391
+ schema,
392
+ background,
393
+ ...options
394
+ }: Options<O> & Definition<P>) =>
395
+ sessionObject({
396
+ name,
397
+ description,
398
+ schema,
399
+ background,
400
+ handlers: { chat: chat(options) },
401
+ views: { messages: messages() },
402
+ });
@@ -0,0 +1,65 @@
1
+ // pi-durable storage on an SQL database: the `SqliteDatabase` facade of
2
+ // @earendil-works/chord/sqlite, over a database session `db` (in Restate,
3
+ // `ctx.db`), which has `query`, `get`, `execute` and
4
+ // `transaction(body)`.
5
+ //
6
+ // The facade's operations must run one at a time, a transaction excluding
7
+ // every other: the session does that, and a transaction's handle is invalid
8
+ // once its body settles. A statement outside a transaction is its own
9
+ // transaction.
10
+ //
11
+ // pi-durable's tables and indexes are named `restate_pi_<name>` (its
12
+ // storage's `prefix`), apart from the tables of yours in the same database.
13
+ import type { DatabaseWriter, Database } from '@restatedev/sessions';
14
+ import {
15
+ SqliteStorage,
16
+ type SqliteDatabase,
17
+ type SqliteExecutor,
18
+ type SqliteValue,
19
+ } from '@earendil-works/pi-durable/storage/sqlite';
20
+
21
+ /** The prefix of pi-durable's tables and indexes. */
22
+ const PREFIX = 'restate_pi_';
23
+
24
+ /** SQL through `db`: the session, or one transaction's. */
25
+ class Executor implements SqliteExecutor {
26
+ readonly db: DatabaseWriter;
27
+ constructor(db: DatabaseWriter) {
28
+ this.db = db;
29
+ }
30
+ async exec(sql: string) {
31
+ await this.db.execute(sql);
32
+ }
33
+ async run(sql: string, ...params: SqliteValue[]) {
34
+ await this.db.execute(sql, params);
35
+ }
36
+ async get<T extends object>(sql: string, ...params: SqliteValue[]): Promise<T | undefined> {
37
+ return this.db.get<T>(sql, params);
38
+ }
39
+ async all<T extends object>(sql: string, ...params: SqliteValue[]): Promise<T[]> {
40
+ return this.db.query<T>(sql, params);
41
+ }
42
+ }
43
+
44
+ /** The `SqliteDatabase` facade over the session `db`. */
45
+ class SqlKvDatabase extends Executor implements SqliteDatabase {
46
+ readonly #session: Database;
47
+
48
+ constructor(db: Database) {
49
+ super(db);
50
+ this.#session = db;
51
+ }
52
+
53
+ /** Commits when the callback resolves; rolls back, and rejects with its error, when it rejects. */
54
+ transaction<T>(callback: (transaction: SqliteExecutor) => Promise<T>): Promise<T> {
55
+ return this.#session.transaction((tx) => callback(new Executor(tx)));
56
+ }
57
+
58
+ /** The session is the caller's to end, after the calls made before. */
59
+ async close() {}
60
+ }
61
+
62
+ /** Open pi-durable storage on the session `db`. */
63
+ export function openSqlKvStorage(db: Database): Promise<SqliteStorage> {
64
+ return SqliteStorage.open(new SqlKvDatabase(db), { prefix: PREFIX });
65
+ }