@restatedev/agents 0.11.2 → 0.12.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 (218) hide show
  1. package/README.md +189 -808
  2. package/dist/pi/factory.d.ts +73 -0
  3. package/dist/pi/factory.d.ts.map +1 -0
  4. package/dist/pi/factory.js +145 -0
  5. package/dist/pi/factory.js.map +1 -0
  6. package/dist/pi/index.d.ts +5 -129
  7. package/dist/pi/index.d.ts.map +1 -1
  8. package/dist/pi/index.js +31 -571
  9. package/dist/pi/index.js.map +1 -1
  10. package/dist/pi/keepalive.d.ts +3 -16
  11. package/dist/pi/keepalive.d.ts.map +1 -1
  12. package/dist/pi/keepalive.js +38 -41
  13. package/dist/pi/keepalive.js.map +1 -1
  14. package/dist/pi/left.d.ts +16 -0
  15. package/dist/pi/left.d.ts.map +1 -0
  16. package/dist/pi/left.js +23 -0
  17. package/dist/pi/left.js.map +1 -0
  18. package/dist/pi/storage.d.ts +19 -76
  19. package/dist/pi/storage.d.ts.map +1 -1
  20. package/dist/pi/storage.js +50 -368
  21. package/dist/pi/storage.js.map +1 -1
  22. package/dist/pi/tools.d.ts +12 -0
  23. package/dist/pi/tools.d.ts.map +1 -0
  24. package/dist/pi/tools.js +70 -0
  25. package/dist/pi/tools.js.map +1 -0
  26. package/package.json +11 -254
  27. package/src/pi/factory.ts +231 -0
  28. package/src/pi/index.ts +31 -759
  29. package/src/pi/keepalive.ts +46 -56
  30. package/src/pi/left.ts +52 -0
  31. package/src/pi/storage.ts +75 -409
  32. package/src/pi/tools.ts +78 -0
  33. package/dist/agentlib/agent.d.ts +0 -32
  34. package/dist/agentlib/agent.d.ts.map +0 -1
  35. package/dist/agentlib/agent.js +0 -174
  36. package/dist/agentlib/agent.js.map +0 -1
  37. package/dist/agentlib/index.d.ts +0 -5
  38. package/dist/agentlib/index.d.ts.map +0 -1
  39. package/dist/agentlib/index.js +0 -15
  40. package/dist/agentlib/index.js.map +0 -1
  41. package/dist/agentlib/messages.d.ts +0 -39
  42. package/dist/agentlib/messages.d.ts.map +0 -1
  43. package/dist/agentlib/messages.js +0 -177
  44. package/dist/agentlib/messages.js.map +0 -1
  45. package/dist/agentlib/model.d.ts +0 -31
  46. package/dist/agentlib/model.d.ts.map +0 -1
  47. package/dist/agentlib/model.js +0 -140
  48. package/dist/agentlib/model.js.map +0 -1
  49. package/dist/agentlib/options.d.ts +0 -58
  50. package/dist/agentlib/options.d.ts.map +0 -1
  51. package/dist/agentlib/options.js +0 -2
  52. package/dist/agentlib/options.js.map +0 -1
  53. package/dist/agentlib/runtime.d.ts +0 -37
  54. package/dist/agentlib/runtime.d.ts.map +0 -1
  55. package/dist/agentlib/runtime.js +0 -216
  56. package/dist/agentlib/runtime.js.map +0 -1
  57. package/dist/agentlib/state.d.ts +0 -114
  58. package/dist/agentlib/state.d.ts.map +0 -1
  59. package/dist/agentlib/state.js +0 -52
  60. package/dist/agentlib/state.js.map +0 -1
  61. package/dist/agentlib/steering.d.ts +0 -23
  62. package/dist/agentlib/steering.d.ts.map +0 -1
  63. package/dist/agentlib/steering.js +0 -48
  64. package/dist/agentlib/steering.js.map +0 -1
  65. package/dist/agentlib/tools.d.ts +0 -33
  66. package/dist/agentlib/tools.d.ts.map +0 -1
  67. package/dist/agentlib/tools.js +0 -245
  68. package/dist/agentlib/tools.js.map +0 -1
  69. package/dist/agentlib/turn.d.ts +0 -82
  70. package/dist/agentlib/turn.d.ts.map +0 -1
  71. package/dist/agentlib/turn.js +0 -253
  72. package/dist/agentlib/turn.js.map +0 -1
  73. package/dist/calls.d.ts +0 -90
  74. package/dist/calls.d.ts.map +0 -1
  75. package/dist/calls.js +0 -241
  76. package/dist/calls.js.map +0 -1
  77. package/dist/claude/index.d.ts +0 -106
  78. package/dist/claude/index.d.ts.map +0 -1
  79. package/dist/claude/index.js +0 -386
  80. package/dist/claude/index.js.map +0 -1
  81. package/dist/client.d.ts +0 -90
  82. package/dist/client.d.ts.map +0 -1
  83. package/dist/client.js +0 -88
  84. package/dist/client.js.map +0 -1
  85. package/dist/common.d.ts +0 -410
  86. package/dist/common.d.ts.map +0 -1
  87. package/dist/common.js +0 -563
  88. package/dist/common.js.map +0 -1
  89. package/dist/companion.d.ts +0 -286
  90. package/dist/companion.d.ts.map +0 -1
  91. package/dist/companion.js +0 -463
  92. package/dist/companion.js.map +0 -1
  93. package/dist/conversation.d.ts +0 -576
  94. package/dist/conversation.d.ts.map +0 -1
  95. package/dist/conversation.js +0 -1476
  96. package/dist/conversation.js.map +0 -1
  97. package/dist/deepseek/barriers.d.ts +0 -11
  98. package/dist/deepseek/barriers.d.ts.map +0 -1
  99. package/dist/deepseek/barriers.js +0 -36
  100. package/dist/deepseek/barriers.js.map +0 -1
  101. package/dist/deepseek/index.d.ts +0 -97
  102. package/dist/deepseek/index.d.ts.map +0 -1
  103. package/dist/deepseek/index.js +0 -603
  104. package/dist/deepseek/index.js.map +0 -1
  105. package/dist/deepseek/persistence.d.ts +0 -83
  106. package/dist/deepseek/persistence.d.ts.map +0 -1
  107. package/dist/deepseek/persistence.js +0 -262
  108. package/dist/deepseek/persistence.js.map +0 -1
  109. package/dist/index.d.ts +0 -14
  110. package/dist/index.d.ts.map +0 -1
  111. package/dist/index.js +0 -17
  112. package/dist/index.js.map +0 -1
  113. package/dist/langgraph/checkpointer.d.ts +0 -52
  114. package/dist/langgraph/checkpointer.d.ts.map +0 -1
  115. package/dist/langgraph/checkpointer.js +0 -477
  116. package/dist/langgraph/checkpointer.js.map +0 -1
  117. package/dist/langgraph/context.d.ts +0 -10
  118. package/dist/langgraph/context.d.ts.map +0 -1
  119. package/dist/langgraph/context.js +0 -21
  120. package/dist/langgraph/context.js.map +0 -1
  121. package/dist/langgraph/errors.d.ts +0 -16
  122. package/dist/langgraph/errors.d.ts.map +0 -1
  123. package/dist/langgraph/errors.js +0 -30
  124. package/dist/langgraph/errors.js.map +0 -1
  125. package/dist/langgraph/graph.d.ts +0 -25
  126. package/dist/langgraph/graph.d.ts.map +0 -1
  127. package/dist/langgraph/graph.js +0 -378
  128. package/dist/langgraph/graph.js.map +0 -1
  129. package/dist/langgraph/index.d.ts +0 -119
  130. package/dist/langgraph/index.d.ts.map +0 -1
  131. package/dist/langgraph/index.js +0 -325
  132. package/dist/langgraph/index.js.map +0 -1
  133. package/dist/langgraph/keepalive.d.ts +0 -16
  134. package/dist/langgraph/keepalive.d.ts.map +0 -1
  135. package/dist/langgraph/keepalive.js +0 -51
  136. package/dist/langgraph/keepalive.js.map +0 -1
  137. package/dist/langgraph/nodes.d.ts +0 -71
  138. package/dist/langgraph/nodes.d.ts.map +0 -1
  139. package/dist/langgraph/nodes.js +0 -148
  140. package/dist/langgraph/nodes.js.map +0 -1
  141. package/dist/messages.d.ts +0 -18
  142. package/dist/messages.d.ts.map +0 -1
  143. package/dist/messages.js +0 -182
  144. package/dist/messages.js.map +0 -1
  145. package/dist/object.d.ts +0 -213
  146. package/dist/object.d.ts.map +0 -1
  147. package/dist/object.js +0 -309
  148. package/dist/object.js.map +0 -1
  149. package/dist/opencode/db.d.ts +0 -81
  150. package/dist/opencode/db.d.ts.map +0 -1
  151. package/dist/opencode/db.js +0 -249
  152. package/dist/opencode/db.js.map +0 -1
  153. package/dist/opencode/index.d.ts +0 -184
  154. package/dist/opencode/index.d.ts.map +0 -1
  155. package/dist/opencode/index.js +0 -1079
  156. package/dist/opencode/index.js.map +0 -1
  157. package/dist/output.d.ts +0 -25
  158. package/dist/output.d.ts.map +0 -1
  159. package/dist/output.js +0 -99
  160. package/dist/output.js.map +0 -1
  161. package/dist/pi/commits.d.ts +0 -6
  162. package/dist/pi/commits.d.ts.map +0 -1
  163. package/dist/pi/commits.js +0 -3
  164. package/dist/pi/commits.js.map +0 -1
  165. package/dist/steering.d.ts +0 -32
  166. package/dist/steering.d.ts.map +0 -1
  167. package/dist/steering.js +0 -45
  168. package/dist/steering.js.map +0 -1
  169. package/dist/tools.d.ts +0 -267
  170. package/dist/tools.d.ts.map +0 -1
  171. package/dist/tools.js +0 -305
  172. package/dist/tools.js.map +0 -1
  173. package/dist/webhook.d.ts +0 -71
  174. package/dist/webhook.d.ts.map +0 -1
  175. package/dist/webhook.js +0 -102
  176. package/dist/webhook.js.map +0 -1
  177. package/src/agentlib/README.md +0 -229
  178. package/src/agentlib/agent.ts +0 -216
  179. package/src/agentlib/index.ts +0 -16
  180. package/src/agentlib/messages.ts +0 -207
  181. package/src/agentlib/model.ts +0 -156
  182. package/src/agentlib/options.ts +0 -62
  183. package/src/agentlib/runtime.ts +0 -252
  184. package/src/agentlib/state.ts +0 -93
  185. package/src/agentlib/steering.ts +0 -53
  186. package/src/agentlib/tools.ts +0 -355
  187. package/src/agentlib/turn.ts +0 -302
  188. package/src/calls.ts +0 -333
  189. package/src/claude/README.md +0 -107
  190. package/src/claude/index.ts +0 -487
  191. package/src/client.ts +0 -187
  192. package/src/common.ts +0 -766
  193. package/src/companion.ts +0 -675
  194. package/src/conversation.ts +0 -1799
  195. package/src/deepseek/README.md +0 -202
  196. package/src/deepseek/barriers.ts +0 -63
  197. package/src/deepseek/index.ts +0 -740
  198. package/src/deepseek/persistence.ts +0 -337
  199. package/src/index.ts +0 -41
  200. package/src/langgraph/README.md +0 -199
  201. package/src/langgraph/checkpointer.ts +0 -614
  202. package/src/langgraph/context.ts +0 -27
  203. package/src/langgraph/errors.ts +0 -26
  204. package/src/langgraph/graph.ts +0 -422
  205. package/src/langgraph/index.ts +0 -500
  206. package/src/langgraph/keepalive.ts +0 -58
  207. package/src/langgraph/nodes.ts +0 -247
  208. package/src/messages.ts +0 -244
  209. package/src/object.ts +0 -454
  210. package/src/opencode/README.md +0 -249
  211. package/src/opencode/db.ts +0 -387
  212. package/src/opencode/index.ts +0 -1339
  213. package/src/output.ts +0 -116
  214. package/src/pi/README.md +0 -174
  215. package/src/pi/commits.ts +0 -7
  216. package/src/steering.ts +0 -68
  217. package/src/tools.ts +0 -515
  218. package/src/webhook.ts +0 -161
package/dist/pi/index.js CHANGED
@@ -1,577 +1,37 @@
1
- // pi agents in Restate virtual objects: a pi-durable Harness for each
2
- // invocation, with its storage in the object's database.
1
+ // pi-durable on a session object's database, with pi's own API.
3
2
  //
4
- // const assistant = pi.agent({ name: 'assistant', tools: [weather] });
5
- // const lead = pi.agent({ name: 'lead', tools: [subagent(coder)] });
3
+ // const pi = withPi({ models, agent: { model }, tools: (ctx) => [transfer(ctx)] }); // once, at module scope
4
+ // chat: (ctx, message: string) => pi(ctx, ({ ask }) => ask(message))
6
5
  //
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 }))`
6
+ // The closure gets a fresh `registry` (the option's tools in it),
7
+ // `ask(message, { requestId })`, `messages()` and `harness()` (factory.ts). The Harness it
8
+ // opens for writing is this wiring of the pieces below, closed when the
9
+ // closure ends:
9
10
  //
10
- // or, for more than a prompt:
11
+ // const harness = await Harness.open(await openSqlKvStorage(ctx.db), { models: keptModels(ctx, models),
12
+ // registry: keptTools(ctx, registry), settings: { restartLimit: Infinity } }, context);
13
+ // await abortLeft(ctx, harness, context);
11
14
  //
12
- // compact: (ctx) => withPi(ctx, { tools }, async ({ conversation, context }) => ...),
15
+ // Crash: pi stores each commit in the key's database (storage.ts). The message
16
+ // is submitted under its request id (by default the invocation id), so a retry
17
+ // waits for its run instead of asking again, and pi resumes the run; for the
18
+ // same reason a second `ask` under the same id gets the first's answer. The `agent` option is
19
+ // what pi creates the root conversation with; pi keeps it after that. A tool declared `replay: 'safe'` runs
20
+ // again under the same call id, so a callee invoked with an idempotency key
21
+ // built from that id runs once. `restartLimit: Infinity` keeps pi from parking
22
+ // work after 5 crashes.
13
23
  //
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. pi keeps its
20
- // own history (and compacts it); each commit of a prompt's run copies its
21
- // new entries (the model's replies, the tools' results) into the
22
- // conversation of turns (../conversation.ts) in the same transaction: what
23
- // clients read, and how turns end. A run another invocation left (killed)
24
- // is aborted, never finished, and the next prompt tells the model how the
25
- // turn before it ended. The Harness
26
- // is opened with `tools` (made with pi-durable's `defineTool`) and closed at
27
- // the end. A retried attempt (a crash, a lost connection) opens it again and
28
- // carries on: a prompt is submitted once, by its id (pi-durable's requestId),
29
- // an answered prompt returns its answer, and unfinished work resumes: a model
30
- // call is made again, and a tool call declared `replay: 'safe'` runs again
31
- // with the same call id, which a tool passes on to stay idempotent. A tool's
32
- // error fails the attempt, which Restate retries (pi-durable would hand it to
33
- // the model as the tool's result).
34
- //
35
- // With a `workspace` directory, the agent also gets pi-durable's coding
36
- // tools (`read`, `write`, `edit`, `bash`) over it, on the local file system.
37
- // The files are not in the database: they last as long as the disk does,
38
- // and a coding tool cut off by a crash is not run again (the model is told
39
- // it was interrupted).
40
- import * as restate from '@restatedev/sessions';
41
- import { awaitWithContext, BACKGROUND_CONTEXT, withCancel, withoutAbortSignal, } from '@earendil-works/chord/context';
42
- import { mkdir } from 'node:fs/promises';
43
- import { createModels } from '@earendil-works/pi-ai/models';
44
- import { builtinProviders } from '@earendil-works/pi-ai/providers/all';
45
- import { AssistantEntry, createRegistry, defineExtension, defineTool, GenerationTask, Harness, hook, section, } from '@earendil-works/pi-durable';
46
- import { keptModels } from './keepalive.js';
47
- import { NodeExecutionEnv } from '@earendil-works/pi-durable/env/node';
48
- import { CodingTools } from '@earendil-works/pi-durable/tools';
49
- import { AttemptEnded, chatHandler, CHECK_MODEL, checkModelName, configured, fromTool, inboxOf, ModelError, modelOf, providerOf, refusal, REFUSED, RETURNED_UNRECORDED, stopSignalOf, toolCallStarted, } from '../common.js';
50
- import { holding } from '../calls.js';
51
- import { answerOnce, invocationOf } from '../conversation.js';
52
- import { tookSteers } from '../steering.js';
53
- import { conversationView } from '../messages.js';
54
- import { withChecked } from '../output.js';
55
- import { sessionObject } from '../object.js';
56
- import { isTool, jsonSchemaOf } from '../tools.js';
57
- import { commitsDefault } from './commits.js';
58
- import { openSqlKvStorage, SqlKvDatabase } from './storage.js';
59
- /** The text of a message's content. */
60
- const textOf = (content) => typeof content === 'string' ? content : content.flatMap((c) => (c.type === 'text' ? [c.text] : [])).join('');
61
- /** No usage: a message the conversation makes, which no model gave. */
62
- const NO_USAGE = {
63
- input: 0,
64
- output: 0,
65
- cacheRead: 0,
66
- cacheWrite: 0,
67
- totalTokens: 0,
68
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
69
- };
70
- /**
71
- * pi's items: pi-ai's messages. A user's message is said by the user; an
72
- * assistant's (but one aborted, failed or deferred) says its text, with its
73
- * tool calls; a tool's result is a result; a system message says nothing.
74
- */
75
- export const items = {
76
- dump: (item) => JSON.stringify(item),
77
- load: (stored) => {
78
- // Only a pi message, with the entry it was copied from: another framework's row is not one.
79
- const item = JSON.parse(stored);
80
- const { message, entry, ...rest } = item;
81
- if (typeof message !== 'object' || message === null || typeof message.role !== 'string')
82
- throw new Error("not a pi item (a pi-ai message, with its entry's id)");
83
- if (Object.keys(rest).length > 0 || (entry !== undefined && typeof entry !== 'number'))
84
- throw new Error(`not a pi item: ${Object.keys(item).join(', ')}`);
85
- return item;
86
- },
87
- prompt: (text) => ({ message: { role: 'user', content: text, timestamp: 0 } }),
88
- reply: (text) => ({
89
- message: {
90
- role: 'assistant',
91
- content: [{ type: 'text', text }],
92
- api: 'restate',
93
- provider: 'restate',
94
- model: 'note',
95
- usage: NO_USAGE,
96
- stopReason: 'stop',
97
- timestamp: 0,
98
- },
99
- }),
100
- results: (results) => results.map(([call, output]) => ({
101
- message: {
102
- role: 'toolResult',
103
- toolCallId: call.id,
104
- toolName: call.name,
105
- content: [{ type: 'text', text: output }],
106
- isError: output !== RETURNED_UNRECORDED,
107
- timestamp: 0,
108
- },
109
- })),
110
- read: ({ message: m }) => {
111
- if (m.role === 'user')
112
- return { said: ['user', textOf(m.content)] };
113
- if (m.role === 'assistant') {
114
- if (m.stopReason === 'aborted' || m.stopReason === 'error' || m.stopReason === 'deferred')
115
- return {};
116
- const calls = m.content.flatMap((c) => c.type === 'toolCall' ? [{ id: c.id, name: c.name, input: c.arguments }] : []);
117
- // Each reply is a message of its own, its tool calls' too.
118
- return { said: ['assistant', textOf(m.content)], calls };
119
- }
120
- if (m.role === 'toolResult')
121
- return { results: [{ id: m.toolCallId, output: textOf(m.content), error: m.isError }] };
122
- return {};
123
- },
124
- };
125
- /** The kind of the entry of a message steered to a turn, as pi places it: its data is the message's id. */
126
- const STEER_ENTRY = 'restate.steer';
127
- /**
128
- * What each pi commit copies into `turn`, in its transaction: the entries of
129
- * the run of the turn's request `requestId` after its user entry (pi's
130
- * submission names it),
131
- * its replies, its tools' results, and the messages steered to the turn that
132
- * pi placed at a step (whose companion is told they are taken, in the
133
- * commit); nothing once `stopped()`, or once the turn is closed. Each entry
134
- * once: after the last one copied. `steps` is told when it copied a step
135
- * that a follower waits for: a reply with tool calls, or a tool's result.
136
- */
137
- function copying(ctx, turn, requestId, stopped, steps) {
138
- let from;
139
- return async (tx) => {
140
- if (stopped() || !turn.writable)
141
- return;
142
- if (!from) {
143
- const submitted = await tx.get("SELECT json_extract(record, '$.entry') AS entry, conversation_id AS conversation FROM restate_pi_submissions WHERE request_id = ?", [JSON.stringify(requestId)]);
144
- if (submitted?.entry === null || submitted?.entry === undefined)
145
- return;
146
- const copied = turn.items.flatMap((e) => (e.item.entry === undefined ? [] : [e.item.entry]));
147
- from = { conversation: submitted.conversation, last: Math.max(submitted.entry, ...copied) };
148
- }
149
- const rows = await tx.values('SELECT id, record FROM restate_pi_entries WHERE conversation_id = ? AND id > ? ORDER BY id', [from.conversation, from.last]);
150
- const copied = [];
151
- const held = new Set(turn.steered().map((e) => e.steer));
152
- for (const [id, record] of rows) {
153
- const entry = JSON.parse(String(record));
154
- from.last = Number(id);
155
- if (entry.kind === STEER_ENTRY) {
156
- const steer = typeof entry.data?.id === 'string' ? entry.data.id : undefined;
157
- const [message] = entry.model ?? [];
158
- if (steer !== undefined && message && !held.has(steer)) {
159
- copied.push({ item: { entry: Number(id), message }, steer });
160
- }
161
- continue;
162
- }
163
- if (entry.kind !== 'pi.assistant' && entry.kind !== 'pi.tool-result')
164
- continue;
165
- for (const message of entry.model ?? []) {
166
- copied.push({ item: { entry: Number(id), message }, reply: message.role === 'assistant' });
167
- }
168
- }
169
- if (copied.length === 0)
170
- return;
171
- await turn.copyIn(tx, copied);
172
- tookSteers(ctx, tx, copied.flatMap(({ steer }) => (steer === undefined ? [] : [steer])));
173
- if (copied.some(({ item: { message } }) => isStep(message)))
174
- steps();
175
- };
176
- }
177
- /** Whether `message` is a step of a turn that its followers are told of: a reply with tool calls, or a tool's result. */
178
- const isStep = (message) => message.role === 'toolResult' || (message.role === 'assistant' && message.content.some((c) => c.type === 'toolCall'));
179
- /** A registry of `provider`'s models, such as anthropicProvider() of @earendil-works/pi-ai/providers/anthropic. */
180
- function modelsOf(provider) {
181
- // All of pi-ai's providers, imported as they are named: one a bundler sees.
182
- const known = builtinProviders().find((p) => p.id === provider);
183
- if (!known)
184
- throw new ModelError(`pi knows no model provider "${provider}": ${CHECK_MODEL}`);
185
- const models = createModels();
186
- models.setProvider(known);
187
- return models;
188
- }
189
- /** `t` as a pi-durable tool. */
190
- const native = (t, ctx) => defineTool({
191
- name: t.name,
192
- description: t.description,
193
- parameters: jsonSchemaOf(t), // JSON Schema, as pi takes it
194
- replay: 'safe', // a crash runs it again, with the same call id
195
- // Aborted (the conversation's work, on a cancellation), it waits no more.
196
- execute: async (args, { callId }, task) => ({
197
- output: [{ type: 'text', text: await awaitWithContext(t.run(args, { ctx, callId }), task) }],
198
- }),
199
- });
200
- /**
201
- * The tools of an agent, `system` added to its system prompt, and, with a
202
- * `workspace`, pi's coding tools working there, with the environment they
203
- * run in.
204
- */
205
- async function extensions(tools, system, workspace, afterTools, ctx, effect) {
206
- const registry = createRegistry();
207
- registry.install(defineExtension({ name: 'tools', tools }));
208
- // Once a round's tools are done, before pi places what waits at its end: the messages steered to the turn.
209
- registry.install(defineExtension({
210
- name: 'steering',
211
- hooks: [hook(GenerationTask, { afterTools: (_assistant, _results, api) => afterTools(api.conversationId) })],
212
- }));
213
- if (system)
214
- registry.install(defineExtension({ name: 'system', sections: [section('system', () => system)] }));
215
- if (!workspace)
216
- return { registry, env: undefined };
217
- await mkdir(workspace, { recursive: true });
218
- registry.install(CodingTools);
219
- // Tell the model where the coding tools work.
220
- registry.install(defineExtension({ name: 'workspace', sections: [section('cwd', () => workspace)] }));
221
- // The coding tools run in `ctx.working`: they work on the machine (a `bash` may run for minutes), and never
222
- // wait on Restate. Installed after theirs, which they wrap.
223
- const kept = (t) => ({
224
- ...t,
225
- execute: (args, api, context) => effect(() => ctx.working(() => t.execute(args, api, context))),
226
- });
227
- const wraps = (CodingTools.tools ?? []).map((t) => ({ tool: t.name, wrap: kept }));
228
- registry.install(defineExtension({ name: 'keepalive', wraps }));
229
- return { registry, env: () => new NodeExecutionEnv({ cwd: workspace }) };
230
- }
231
- /**
232
- * The root conversation of `harness`, on `model`. It keeps the model it was
233
- * created with: on another one now (`model` or MODEL changed), it moves to
234
- * this one.
235
- */
236
- async function rootOn(harness, context, model) {
237
- const [provider, modelId] = providerOf(model);
238
- const root = await harness.root(context, { agent: { model: { provider, modelId } } });
239
- const { model: current } = await root.agent(context);
240
- if (current?.provider !== provider || current.modelId !== modelId) {
241
- await root.configure({ model: { provider, modelId } }, context);
242
- }
243
- return root;
244
- }
245
- /**
246
- * The error of prompt `id`, which ended unanswered for `reason` (and
247
- * `detail`, pi-durable's): {@link REFUSED} if there is no model, or its
248
- * provider refused it, as for the other frameworks.
249
- */
250
- function unanswered(id, why, detail, model) {
251
- const reason = why ?? 'unknown';
252
- const text = detail === undefined || detail === null ? '' : typeof detail === 'string' ? detail : JSON.stringify(detail);
253
- const message = `prompt ${id} unanswered: ${reason}${text ? `: ${text}` : ''}`;
254
- if (reason === 'no_model' || (reason === 'model_error' && refusal(new Error(text)))) {
255
- return new restate.TerminalError(`${message} (the model ${model}: ${CHECK_MODEL})`, { errorCode: REFUSED });
256
- }
257
- return new restate.TerminalError(message);
258
- }
259
- /**
260
- * Run `work(pi)` with a Harness over the object's database: `model` is the
261
- * model to use as `provider/model-id`, and `tools` the agent's tools. `pi`
262
- * has `prompt(text)`, and the `harness` and chord `context` for anything
263
- * else.
264
- */
265
- export const withPi = async (ctx, { model: named, models, system, tools = [], workspace, serviceTier, retry, commits = commitsDefault.commits, }, work) => {
266
- const model = modelOf(named);
267
- models ??= modelsOf(providerOf(model)[0]);
268
- // A tool's error fails the attempt, which Restate retries (pi-durable would
269
- // hand it to the model): the work is cancelled, so the tool call stores no
270
- // result, and the retry runs it again with the same call id.
271
- const { context, cancel } = withCancel(BACKGROUND_CONTEXT);
272
- const { promise: failure, reject: failed } = Promise.withResolvers();
273
- failure.catch(() => { });
274
- // A cancelled invocation, whenever it comes, aborts the conversation's
275
- // work instead (abortOn): pi-durable ends the turn, and the tool call with
276
- // it. An attempt that ends first cancels the work, as a tool's error does:
277
- // the next attempt goes on with it.
278
- let cancelled;
279
- const turn = stopSignalOf(ctx);
280
- const onStop = () => {
281
- const reason = turn.reason;
282
- failed(reason);
283
- if (reason instanceof AttemptEnded)
284
- cancel(reason);
285
- else
286
- cancelled = reason;
287
- };
288
- turn?.addEventListener('abort', onStop, { once: true });
289
- // The root conversation, once the Harness is open (below).
290
- const conversation = () => rootOn(harness, context, model);
291
- /**
292
- * Abort the run of a live input of the root conversation that `kept` does
293
- * not keep: a run a prompt left, whose turn is closed (or the next prompt
294
- * closes it), is aborted, never finished. pi's own writes (a compaction's)
295
- * are not runs, and an input without a request id is not a prompt's.
296
- */
297
- const abortLeft = async (kept) => {
298
- const { submissions } = await harness.inspect(context);
299
- const left = submissions.filter((s) => s.type === 'input' && s.requestId !== undefined && !kept(s.requestId));
300
- if (left.length === 0)
301
- return;
302
- const root = await conversation();
303
- if (left.some((s) => s.conversationId === root.id))
304
- await root.abort(context);
305
- };
306
- // A tool call's error: the attempt fails, and the call never returns.
307
- const stopped = (error, task) => {
308
- // The turn was cancelled, and the abort ended the call: pi-durable records it.
309
- if (cancelled)
310
- throw error;
311
- failed(error);
312
- if (error instanceof restate.CancelledError) {
313
- cancelled = error;
314
- return awaitWithContext(new Promise(() => { }), task);
315
- }
316
- cancel(error);
317
- return awaitWithContext(new Promise(() => { }), context);
318
- };
319
- // The messages steered to the turn of a prompt's run, submitted to pi as a publish lists them (`prompt`).
320
- let steering;
321
- // Whether a tool of the round asks to end the run (`terminate`, a handoff): pi then ends the round at its final
322
- // boundary, which would start a run of its own for a message submitted there, outside the turn.
323
- let ending = false;
324
- // pi's storage (storage.ts): with `commits: 'effects'` it batches pi's commits, which a failed commit loses
325
- // (reported to pi as done): that fails the attempt, as a tool's error does.
326
- const database = new SqlKvDatabase(ctx.db, {
327
- commits,
328
- failed: (error) => {
329
- failed(error);
330
- cancel(error);
331
- },
332
- });
333
- // With 'each' none of this is there: the code is as it was, without a batch in the way.
334
- const batching = commits === 'effects';
335
- const effect = !batching
336
- ? (run) => run()
337
- : async (run) => {
338
- const ended = database.effectStarted();
339
- try {
340
- await database.flush();
341
- return await run();
342
- }
343
- finally {
344
- ended();
345
- }
346
- };
347
- const tracked = (t) => ({
348
- ...t,
349
- execute: async (args, api, task) => {
350
- // A tool is an effect: what pi committed before it is written first, and its own commits are not batched.
351
- const ended = database.effectStarted();
352
- try {
353
- if (batching)
354
- await database.flush();
355
- await toolCallStarted(ctx);
356
- const result = await t.execute(args, api, task);
357
- if (result.control?.terminate === true || result.control?.handoff !== undefined)
358
- ending = true;
359
- return result;
360
- }
361
- catch (error) {
362
- // The tool's error: never taken for the model's provider refusing (a tool may call a model API).
363
- fromTool(ctx, error);
364
- return stopped(error, task);
365
- }
366
- finally {
367
- ended();
368
- }
369
- },
370
- });
371
- const { registry, env } = await extensions(tools.map((t) => tracked(isTool(t) ? native(t, ctx) : t)), system, workspace, async (of) => {
372
- // 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.
373
- const ends = ending;
374
- ending = false;
375
- if (ends)
376
- return;
377
- // The round's results are published before the inbox is read: a message steered while its tools ran is
378
- // told of by that publish (`INBOX`), and pi places it only if it is submitted now. A turn nobody can
379
- // steer has nothing to read.
380
- if (batching && inboxOf(ctx))
381
- await database.flush();
382
- await steering?.(of);
383
- }, ctx, effect);
384
- const settings = {
385
- // A task that crashes is run again however often Restate retries the attempt (its retry policy decides):
386
- // pi-durable would park it after 5 crashes in a row, and the prompt would never be answered.
387
- restartLimit: Infinity,
388
- // A provider's outage never ends the turn: pi asks again until it answers (pi-durable would give up after 3
389
- // retries, ending the turn unanswered for good). Each retry is committed: a retried attempt waits as it would.
390
- retry: { maxRetries: Infinity, ...retry },
391
- // Every message steered to a turn that waits at a step is placed there, not one a step.
392
- steeringMode: 'all',
393
- // pi-durable hands its stream settings to pi-ai's requests as they are: serviceTier is pi-ai's.
394
- ...(serviceTier ? { stream: { serviceTier } } : {}),
395
- };
396
- const harness = await Harness.open(await openSqlKvStorage(ctx.db, database),
397
- // Each request of a model is kept alive, whoever made the registry (see keepalive.ts), and is an effect.
398
- {
399
- models: keptModels(ctx, models, batching ? { started: () => database.effectStarted(), flush: () => database.flush() } : undefined),
400
- registry,
401
- env,
402
- settings,
403
- }, context);
404
- if (batching)
405
- await database.flush();
406
- /**
407
- * `run`, a prompt's run, with pi's commits batched between effects (`commits: 'effects'`), and written, however
408
- * it ends, before it returns: what others see of the turn (its close, the next call) comes after.
409
- */
410
- const batched = (run) => !batching
411
- ? run
412
- : async (store) => {
413
- database.armed = true;
414
- holding(ctx, () => database.flush(), 'pi');
415
- let ran = false;
416
- try {
417
- const result = await run(store);
418
- ran = true;
419
- return result;
420
- }
421
- finally {
422
- database.armed = false;
423
- holding(ctx, undefined, 'pi');
424
- // A failed write has failed the attempt already: it never hides the error the run ended with.
425
- await database.flush().catch((error) => {
426
- if (ran)
427
- throw error;
428
- });
429
- }
430
- };
431
- const prompt = (text, check, reminder) => {
432
- // 0.3.0's `prompt(text, id)` took a prompt's id: from JavaScript, it would
433
- // fail as the check is called, again at every retry.
434
- if (check !== undefined && typeof check !== 'function') {
435
- throw new restate.TerminalError(`pi's prompt(text, check) takes a check of the answer, not ${JSON.stringify(check)}: a prompt has an id of its own`);
436
- }
437
- return answerOnce(ctx, text, items, batched(async (store) => {
438
- const current = store.turn;
439
- const id = current.id;
440
- const root = await conversation();
441
- // The turn's own request: its prompt, or the message that asked again within it.
442
- const again = current.latestAsk() !== current.prompt;
443
- const requestId = again ? `${id}:again` : id;
444
- // A run an earlier prompt of this invocation left (its turn failed, say). A steered message is its run's.
445
- await abortLeft((r) => r === id || r === `${id}:again` || r.startsWith('steer:'));
446
- // Once stopped, the turn's close says how it ended: not pi's abort of its tools.
447
- // A commit that copied steps (a reply with tool calls, tools' results) is published once it is done,
448
- // for followers to read them there; its answer lists the messages steered to the turn (`steering`).
449
- let copiedSteps = false;
450
- database.onCommit = copying(ctx, current, requestId, () => cancelled !== undefined || stopSignalOf(ctx)?.aborted === true, () => {
451
- copiedSteps = true;
452
- });
453
- database.afterCommit = async () => {
454
- if (!copiedSteps)
455
- return;
456
- copiedSteps = false;
457
- // Failing, it fails the attempt, as a tool's error does: never pi's commit, which is done.
458
- await current.stepsCommitted().catch((error) => {
459
- failed(error);
460
- cancel(error);
461
- });
462
- };
463
- // Each message steered to the turn, submitted to pi once (keyed by its id, also by a retried attempt)
464
- // as a round of tool calls is done (`afterTools`): pi places it at the round's end, after its results,
465
- // as an entry of its own kind, which `copying` stores.
466
- const given = new Set();
467
- steering = async (of) => {
468
- const inbox = inboxOf(ctx);
469
- // The root conversation's rounds only: it is the turn's.
470
- if (!inbox || of !== root.id || cancelled !== undefined)
471
- return;
472
- if (stopSignalOf(ctx)?.aborted || !current.writable)
473
- return;
474
- const held = new Set(current.steered().map((e) => e.steer));
475
- for (const { id: steerId, text: said } of inbox.messages) {
476
- if (given.has(steerId) || held.has(steerId))
477
- continue;
478
- given.add(steerId);
479
- await root.submit({
480
- type: 'input',
481
- content: said,
482
- whenBusy: 'steer',
483
- requestId: `steer:${steerId}`,
484
- entry: { kind: STEER_ENTRY, data: { id: steerId } },
485
- }, context);
486
- }
487
- };
488
- // The model is told how the turn before this one ended, if its run did not answer it.
489
- const before = store.transcript.at(-2);
490
- const note = !again && before && before.status !== 'answered' && before.answer ? `(${before.answer})\n\n` : '';
491
- // pi keeps the prompt as it is given, the turn's reminder too; the conversation as it was asked.
492
- const asked = textOf(current.latestAsk().item.message.content) + (again ? '' : (current.reminder ?? ''));
493
- const submission = await root.submit({ type: 'input', content: note + asked, requestId }, context);
494
- const settled = await submission.wait(context);
495
- // A prompt the cancellation's abort ended fails with the cancellation.
496
- if (settled.status !== 'done' || settled.answer === undefined)
497
- throw cancelled ?? unanswered(id, settled.reason, settled.detail, model);
498
- const { answer } = settled;
499
- const entry = await root.commit((tx) => tx.entry(AssistantEntry, answer), context);
500
- const reply = entry?.model?.at(-1);
501
- if (!reply)
502
- throw new restate.TerminalError(`prompt ${id}: no answer entry`);
503
- return textOf(reply.content);
504
- }),
505
- // pi keeps the model's history: the conversation reads only its latest turns.
506
- { check, reminder, ownHistory: true });
507
- };
508
- // `failure`, once it comes. A cancellation aborts the conversation's work
509
- // instead: the work ends with it (a prompt closes its turn, cancelled).
510
- const abortOn = async () => {
511
- try {
512
- return await failure;
513
- }
514
- catch (error) {
515
- if (!(error instanceof restate.CancelledError))
516
- throw error;
517
- await (await conversation()).abort(context);
518
- return new Promise(() => { });
519
- }
520
- };
521
- // Whatever `work` does (a prompt, a compaction, a wait) has pi schedule
522
- // what it has: a run another invocation left is aborted first. This
523
- // invocation's own (a retried attempt's) goes on.
524
- const working = async () => {
525
- await abortLeft((r) => invocationOf(r) === ctx.request.id || r.startsWith('steer:'));
526
- if (batching)
527
- await database.flush();
528
- return work({ harness, context, conversation, prompt });
529
- };
530
- try {
531
- const done = await Promise.race([abortOn(), working()]);
532
- // Work the cancellation's abort ended (a wait for pi, say) fails with it, as a prompt does.
533
- if (cancelled)
534
- throw cancelled;
535
- return done;
536
- }
537
- finally {
538
- turn?.removeEventListener('abort', onStop);
539
- await harness.close(withoutAbortSignal(context));
540
- }
541
- };
542
- /**
543
- * Answer `text`, once: a retried attempt resumes the same prompt. Each prompt
544
- * of an invocation is a prompt of its own.
545
- * With `output`, it answers with the value the agent replies with (see
546
- * output.ts), not its text.
547
- */
548
- export const prompt = (ctx, text, options = {}) => withChecked(text, options, (t, o, check, reminder) => withPi(ctx, o, (session) => session.prompt(t, check, reminder)));
549
- /**
550
- * A chat handler: each message an invocation, the conversation in the
551
- * object's database, with `options`, or the options a function of the
552
- * invocation's context gives (each user's model, say). It takes the message
553
- * as plain text (`curl -d 'Hi'`) or as a JSON string (`curl --json '"Hi"'`).
554
- */
555
- export const chat = (options = {}) => {
556
- if (typeof options === 'object')
557
- checkModelName('pi', options.model);
558
- return chatHandler(async (ctx, message) => prompt(ctx, message, await configured(options, ctx)), { steers: true });
559
- };
560
- /**
561
- * A view of the conversation as clients read it: a page at a time, or what
562
- * is new or changed since a cursor; `view: 'summary'` for each turn's
563
- * message and answer. It answers while a message is answered.
564
- */
565
- export const messages = () => conversationView(items);
566
- /** An agent: a virtual object `name`, one per key, whose `chat` handler is {@link chat}, and `messages` {@link messages}. */
567
- export const agent = ({ name, description, schema, background, window, budget, ...options }) => sessionObject({
568
- name,
569
- description,
570
- schema,
571
- background,
572
- window,
573
- budget,
574
- handlers: { chat: chat(options) },
575
- views: { messages: messages() },
576
- });
24
+ // Keep-alive and stop: each model request (keepalive.ts) and tool call
25
+ // (tools.ts) runs in a `ctx.stoppable` scope and gets its stop signal; a tool
26
+ // may await a call to Restate in `ctx.suspendable`. A cancelled run ends
27
+ // unanswered, as cancelled. `abortLeft` (left.ts) aborts a run another
28
+ // invocation left, so the next message does not resume it, and keeps the runs
29
+ // of this invocation's earlier attempts, told apart by the writer pi's
30
+ // commits record (storage.ts). A Harness on another database than `ctx.db`
31
+ // gives `abortLeft` that database: `abortLeft(ctx, harness, context, db)`.
32
+ export { openSqlKvStorage, SqlKvDatabase } from './storage.js';
33
+ export { keptModels } from './keepalive.js';
34
+ export { keptTools } from './tools.js';
35
+ export { abortLeft } from './left.js';
36
+ export { withPi } from './factory.js';
577
37
  //# sourceMappingURL=index.js.map