@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
@@ -1,156 +0,0 @@
1
- // The agentlib agent's model: a model by name (`openai/…`, `anthropic/…`) or
2
- // one of agentlib's, and how its provider's refusals end a turn.
3
- import { isContextOverflow } from '@restatedev/agentlib';
4
- import type { CompactionPolicy, Model, ModelRequest } from '@restatedev/agentlib';
5
- import type { aiModel } from '@restatedev/agentlib/provider';
6
- import { sdk as restate } from '@restatedev/sessions/internal';
7
- import { CHECK_MODEL, ModelError, REFUSED } from '../common.ts';
8
-
9
- /** The model of an agent that names none, without MODEL either: OpenAI's (OPENAI_API_KEY). */
10
- export const DEFAULT_MODEL = 'openai/gpt-6-sol';
11
-
12
- type LanguageModel = Parameters<typeof aiModel>[0]['model'];
13
-
14
- /** The AI SDK's provider packages, by provider. OpenAI's uses its Responses API. */
15
- const PROVIDERS: Record<string, () => Promise<(modelId: string) => LanguageModel>> = {
16
- openai: async () => (await import('@ai-sdk/openai')).openai,
17
- anthropic: async () => (await import('@ai-sdk/anthropic')).anthropic,
18
- };
19
-
20
- /**
21
- * Returns what loads agent `agent`'s model on its first turn: `model` itself,
22
- * or the model it names (`provider/model-id`, else MODEL, else
23
- * {@link DEFAULT_MODEL}) on the AI SDK. A name it cannot take throws at once.
24
- */
25
- export function modelLoader(
26
- agent: string,
27
- model: string | Model | undefined,
28
- ): () => Promise<Model> {
29
- if (typeof model === 'function') return async () => model;
30
-
31
- const id = model ?? process.env.MODEL ?? DEFAULT_MODEL;
32
- const at = id.indexOf('/');
33
- if (at <= 0 || at === id.length - 1) {
34
- throw new Error(`${agent}: the model ${id} is not provider/model-id`);
35
- }
36
- const provider = id.slice(0, at);
37
- const modelId = id.slice(at + 1);
38
- const loadProvider = PROVIDERS[provider];
39
- if (!loadProvider) {
40
- throw new Error(
41
- `${agent}: an agentlib agent takes openai/… and anthropic/… models by name, not ${id}. ` +
42
- 'Give any other as a model of agentlib (aiModel of @restatedev/agentlib/provider).',
43
- );
44
- }
45
-
46
- return async () => {
47
- const { aiModel } = await import('@restatedev/agentlib/provider');
48
- const languageModel = await loadLanguageModel(id, loadProvider, modelId);
49
- // `retry: {}` sets no retry limit of the model's own: an outage fails the
50
- // attempt, and Restate retries it, as for every agent.
51
- const loaded = aiModel({ model: languageModel, retry: {} });
52
- return provider === 'anthropic' ? withoutSchemaBounds(loaded) : loaded;
53
- };
54
- }
55
-
56
- /** Creates the AI SDK model `modelId`, with a clear error if its provider package is missing. */
57
- async function loadLanguageModel(
58
- id: string,
59
- loadProvider: () => Promise<(modelId: string) => LanguageModel>,
60
- modelId: string,
61
- ): Promise<LanguageModel> {
62
- let create: (modelId: string) => LanguageModel;
63
- try {
64
- create = await loadProvider();
65
- } catch (error) {
66
- const provider = id.slice(0, id.indexOf('/'));
67
- const advice = `install it beside @restatedev/agentlib (${String(error)})`;
68
- throw new ModelError(`${id} needs @ai-sdk/${provider}: ${advice}`);
69
- }
70
- return create(modelId);
71
- }
72
-
73
- /**
74
- * Whether `error`, thrown by a model, is its provider's refusal that a retry
75
- * does not change: a request answered with a 4xx (a wrong API key, an unknown
76
- * model, a rejected request), or a missing API key. Only a plain
77
- * `TerminalError` qualifies: agentlib's own errors (an overflow, a protocol
78
- * error) and cancellations are subclasses. An overflow is never one: it is a
79
- * subclass only on the first attempt, and replay restores it as a plain
80
- * `TerminalError` with code 413, which agentlib still has to see to compact.
81
- */
82
- export function refused(error: unknown): error is restate.TerminalError {
83
- if (!(error instanceof restate.TerminalError)) return false;
84
- if (isContextOverflow(error)) return false;
85
- if (error.constructor !== restate.TerminalError) return false;
86
- const clientError = error.code >= 400 && error.code < 500;
87
- return clientError || /API key/i.test(error.message);
88
- }
89
-
90
- /** Wraps `model` so that its provider's refusals end the turn with a 424, as for every agent. */
91
- export function refusing(model: Model): Model {
92
- return function* (request: ModelRequest) {
93
- try {
94
- return yield* model(request);
95
- } catch (error) {
96
- if (!refused(error)) throw error;
97
- const message = `the model's provider refused the request: ${CHECK_MODEL}. ${error.message}`;
98
- throw new restate.TerminalError(message, { errorCode: REFUSED });
99
- }
100
- };
101
- }
102
-
103
- const NUMBER_BOUNDS = new Set([
104
- 'minimum',
105
- 'maximum',
106
- 'exclusiveMinimum',
107
- 'exclusiveMaximum',
108
- 'multipleOf',
109
- ]);
110
-
111
- /** Returns `schema` (a JSON schema) without the bounds of its numbers, at any depth. */
112
- export function withoutBounds(schema: unknown): unknown {
113
- if (Array.isArray(schema)) return schema.map(withoutBounds);
114
- if (typeof schema !== 'object' || schema === null) return schema;
115
-
116
- const type = (schema as { type?: unknown }).type;
117
- const types = Array.isArray(type) ? type : [type];
118
- const numeric = types.includes('integer') || types.includes('number');
119
-
120
- const kept = Object.entries(schema).filter(([key]) => !(numeric && NUMBER_BOUNDS.has(key)));
121
- return Object.fromEntries(kept.map(([key, value]) => [key, withoutBounds(value)]));
122
- }
123
-
124
- /**
125
- * Wraps an Anthropic `model` so that it gets its tools' schemas without
126
- * numeric bounds. agentlib 0.1.0 asked for strict tools where a schema
127
- * allowed it, and Anthropic refuses strict tools with bounded numbers (such as
128
- * agentlib's own `read_tool_result`). 0.2.0 leaves strict mode to the AI SDK's
129
- * defaults; the bounds still go, which costs nothing: the tools still check
130
- * their input.
131
- */
132
- function withoutSchemaBounds(model: Model): Model {
133
- return (request) => {
134
- const tools = request.tools.map((tool) => {
135
- const inputSchema = withoutBounds(tool.inputSchema) as Record<string, unknown>;
136
- return { ...tool, inputSchema };
137
- });
138
- return model({ ...request, tools });
139
- };
140
- }
141
-
142
- /**
143
- * Checks that agent `agent`'s `history` bounds are positive integers. agentlib
144
- * checks them only when a turn compacts, with an error that a retry would meet
145
- * again and again.
146
- */
147
- export function checkHistory(agent: string, history: CompactionPolicy) {
148
- for (const bound of ['maxMessages', 'maxChars', 'retainMessages'] as const) {
149
- const value = history[bound];
150
- if (value === undefined) continue;
151
- if (!Number.isSafeInteger(value) || value <= 0) {
152
- const given = JSON.stringify(value);
153
- throw new Error(`${agent}: history.${bound} must be a positive integer, not ${given}`);
154
- }
155
- }
156
- }
@@ -1,62 +0,0 @@
1
- // What an agentlib agent takes.
2
- import type { AgentOptions as LibOptions, CompactionPolicy, Model } from '@restatedev/agentlib';
3
- import type { sdk as restate } from '@restatedev/sessions/internal';
4
- import type { AgentlibContext, Approval, Tools } from './tools.ts';
5
-
6
- /** agentlib's options that the agent sets itself, or takes under another name. */
7
- type Replaced = 'model' | 'name' | 'instructions' | 'tools' | 'onApproval' | 'onHumanApproval';
8
-
9
- /**
10
- * The options of an agentlib agent. agentlib's other options (`maxSteps`,
11
- * `compaction`, `contextWindow`, `toolResults`, `skills`, `beforeTool`,
12
- * `afterRun`...) go to its `agent()` as they are.
13
- */
14
- export interface Options<O = string> extends Omit<LibOptions<AgentlibContext, O>, Replaced> {
15
- /**
16
- * `provider/model-id` (`openai/…` or `anthropic/…`), else MODEL, else
17
- * `openai/gpt-6-sol`; or a model of agentlib (`aiModel` of
18
- * `@restatedev/agentlib/provider`, for any provider of the AI SDK).
19
- */
20
- model?: string | Model;
21
-
22
- /** The system prompt: a text, or agentlib's function of the run's context that returns one. */
23
- system?: LibOptions<AgentlibContext, O>['instructions'];
24
-
25
- /**
26
- * The tools: those of `@restatedev/agents` (`tool()`, `call`, `send`,
27
- * `workflow`, `signal`, `subagent`), and agentlib's own by the name the
28
- * model calls them, as in `[weather, { transfer: asyncTool(...) }]`.
29
- */
30
- tools?: Tools;
31
-
32
- /**
33
- * The tools of `@restatedev/agents` whose calls wait for a person's
34
- * approval before they run, by name, or a function of a call that says
35
- * whether it does. `pending` lists the wait, and `signal` approves it
36
- * (`true`, `"approved"`, `{ "approved": true }`) or denies it (anything
37
- * else). agentlib's own tools take `needsApproval` instead.
38
- */
39
- approval?: Approval;
40
-
41
- /**
42
- * How the model's conversation stays short from turn to turn. At a turn's
43
- * start, once its messages since the last summary pass `maxMessages`
44
- * (default 64) or `maxChars` (default 64 000), the earliest are summarized
45
- * by `model` (by default the agent's), and the latest `retainMessages`
46
- * (default 12) are kept. The summary is kept for the next turns. `false`
47
- * keeps the whole conversation. `messages` shows every turn either way.
48
- */
49
- history?: false | (CompactionPolicy & { model?: Model });
50
- }
51
-
52
- /** An agent's name, and what it is beside its options. */
53
- export interface Definition<P extends string> {
54
- name: P;
55
- /** What it is: for the UI, and for the model of a parent that hands it tasks (`subagent`). */
56
- description?: string;
57
- /** It works unwatched (a sub-agent, say): its turn tells its companion at its end only. */
58
- background?: boolean;
59
- /** Options of the object, beside the ones the agent sets (its `retryPolicy`, say). */
60
- options?: restate.ObjectOptions;
61
- metadata?: Record<string, string>;
62
- }
@@ -1,252 +0,0 @@
1
- // How an agentlib agent answers a message: a turn, from its start at the
2
- // companion, through agentlib's run (journaled), to its end.
3
- import {
4
- agent as agentlibAgent,
5
- type Agent as LibAgent,
6
- type AgentOptions as LibOptions,
7
- type ApprovalRequest,
8
- type CompactionPolicy,
9
- type Model,
10
- type ProgressEvent,
11
- type RunOptions,
12
- type RunResult,
13
- type ToolContext,
14
- } from '@restatedev/agentlib';
15
- import { execute, internal, type Operation } from '@restatedev/restate-sdk-gen';
16
- import { sdk as restate } from '@restatedev/sessions/internal';
17
- import { approves, CANCELLED, ModelError, REFUSED, UNANSWERED } from '../common.ts';
18
- import type { Started } from '../companion.ts';
19
- import { checkHistory, modelLoader, refusing } from './model.ts';
20
- import type { Options } from './options.ts';
21
- import { Steering, takenIds } from './steering.ts';
22
- import { companionAt, companionSendAt, read, TAKEN, waitForSignal } from './state.ts';
23
- import { type AgentlibContext, type AgentlibTool, toolsOf } from './tools.ts';
24
- import { conversationOf, Turn } from './turn.ts';
25
-
26
- const { adopt } = internal;
27
-
28
- /** agentlib's agent, once its model is loaded, and the model that summarizes its conversation. */
29
- interface Loaded<O> {
30
- lib: LibAgent<AgentlibContext, O>;
31
- summarizer: Model;
32
- }
33
-
34
- /**
35
- * One agentlib agent's turns. Its model, and with it agentlib's agent, load
36
- * on the first turn (a missing provider package fails that turn, not the
37
- * process); everything else is checked when the agent is defined.
38
- */
39
- export class Runtime<O> {
40
- private readonly name: string;
41
- private readonly background: boolean;
42
- private readonly libOptions: Omit<
43
- Options<O>,
44
- 'model' | 'system' | 'tools' | 'approval' | 'history'
45
- >;
46
- private readonly system: Options<O>['system'];
47
- private readonly tools?: Record<string, AgentlibTool>;
48
- private readonly history: Options<O>['history'];
49
- private readonly loadModel: () => Promise<Model>;
50
- private loading?: Promise<Loaded<O>>;
51
-
52
- constructor(name: string, background: boolean, options: Options<O>) {
53
- const { model, system, tools, approval, history, ...libOptions } = options;
54
- this.name = name;
55
- this.background = background;
56
- this.libOptions = libOptions;
57
- this.system = system;
58
- this.history = history;
59
- this.loadModel = modelLoader(name, model);
60
- if (history) checkHistory(name, history);
61
- // Restate's tools become agentlib's here, so that a mistake fails now: two tools of one
62
- // name, or an approval of a tool the agent does not have (with no tools at all, too).
63
- const named = toolsOf(name, tools ?? [], approval);
64
- if (tools !== undefined) this.tools = named;
65
- }
66
-
67
- /** Answers `text` in the turn of `ctx`'s invocation. */
68
- async answer(ctx: restate.ObjectContext, text: string): Promise<O | string> {
69
- const steering = new Steering();
70
- steering.saw(await companionAt(ctx).start(await this.started(ctx)));
71
- const turn = await Turn.start(ctx, text);
72
-
73
- let lib: LibAgent<AgentlibContext, O>;
74
- try {
75
- lib = await this.prepare(ctx, turn);
76
- } catch (error) {
77
- await this.end(ctx, turn, UNANSWERED);
78
- if (error instanceof restate.TerminalError) throw error;
79
- throw new ModelError(`${this.name}: its model: ${String(error)}`);
80
- }
81
-
82
- let result: RunResult<O>;
83
- try {
84
- result = await execute(ctx, lib.run(text, this.runOptions(ctx, turn, steering)));
85
- } catch (error) {
86
- // Only a terminal error ends the turn. Any other error fails the attempt:
87
- // Restate retries it, and replays the run from its journal.
88
- if (!(error instanceof restate.TerminalError)) throw error;
89
- await this.end(ctx, turn, noteOf(error));
90
- throw error;
91
- }
92
-
93
- const answer = answerOf(result);
94
- // A cancellation that comes after the answer does not undo it: the turn still ends.
95
- await despiteCancellation(() => turn.answered(answer));
96
- await despiteCancellation(() => companionAt(ctx).close(ctx.request().id));
97
- return answer;
98
- }
99
-
100
- /** What the companion learns as the turn starts. */
101
- private async started(ctx: restate.ObjectContext): Promise<Started> {
102
- const since = new Date(await ctx.date.now()).toISOString();
103
- const started: Started = { invocationId: ctx.request().id, since, steers: !this.background };
104
- // A watched turn's start is its first publish, which returns the
105
- // messages already steered to it.
106
- if (!this.background) started.publishes = true;
107
- return started;
108
- }
109
-
110
- /** Loads the agent (once), and gives the turn what summarizes its conversation. */
111
- private async prepare(
112
- ctx: restate.ObjectContext,
113
- turn: Turn,
114
- ): Promise<LibAgent<AgentlibContext, O>> {
115
- this.loading ??= this.load();
116
- let loaded: Loaded<O>;
117
- try {
118
- loaded = await this.loading;
119
- } catch (error) {
120
- // The next turn tries again.
121
- this.loading = undefined;
122
- throw error;
123
- }
124
- if (this.history !== false) {
125
- const policy = policyOf(this.history);
126
- turn.compactor = conversationOf(ctx, { model: loaded.summarizer, policy });
127
- }
128
- return loaded.lib;
129
- }
130
-
131
- /** Loads the model, and makes agentlib's agent with it. */
132
- private async load(): Promise<Loaded<O>> {
133
- const model = refusing(await this.loadModel());
134
- const options: LibOptions<AgentlibContext, O> = {
135
- ...this.libOptions,
136
- name: this.name,
137
- model,
138
- onHumanApproval: askForApproval,
139
- };
140
- if (this.system !== undefined) options.instructions = this.system;
141
- if (this.tools !== undefined) options.tools = this.tools;
142
-
143
- // A summarizer of its own refuses with a 424, as the agent's model does.
144
- const custom = this.history ? this.history.model : undefined;
145
- const summarizer = custom ? refusing(custom) : model;
146
- return { lib: agentlibAgent<AgentlibContext, O>(options), summarizer };
147
- }
148
-
149
- /** The options of agentlib's run of the turn. */
150
- private runOptions(
151
- ctx: restate.ObjectContext,
152
- turn: Turn,
153
- steering: Steering,
154
- ): RunOptions<AgentlibContext> {
155
- const options: RunOptions<AgentlibContext> = {
156
- name: this.name,
157
- context: { ctx },
158
- conversation: turn,
159
- onProgress: (event) => this.onProgress(ctx, turn, steering, event),
160
- };
161
- if (!this.background) options.controls = { steering: steering.source };
162
- return options;
163
- }
164
-
165
- /**
166
- * Records a progress event of the run. A change that clients see is
167
- * published to the companion, whose answer says which messages are steered
168
- * to the turn; the run gets them at its next event.
169
- */
170
- private *onProgress(
171
- ctx: restate.ObjectContext,
172
- turn: Turn,
173
- steering: Steering,
174
- event: ProgressEvent,
175
- ): Operation<void> {
176
- yield* recordTaken(ctx, event);
177
- const changed = turn.progress(event);
178
- if (!changed || this.background) return;
179
-
180
- steering.saw(yield* adopt(companionAt(ctx).publish()));
181
- yield* steering.hand();
182
- }
183
-
184
- /** Ends a turn that has no answer, with `note`, at the agent and at its companion. */
185
- private async end(ctx: restate.ObjectContext, turn: Turn, note: string) {
186
- await turn.close(note);
187
- await companionAt(ctx).close(ctx.request().id);
188
- }
189
- }
190
-
191
- /**
192
- * Waits for the signal `approval` for a tool call that needs one (agentlib's
193
- * `needsApproval`, its `humanApprovalTool`, a tool's `approve`). `pending`
194
- * lists the wait, with the tool and its input; `signal` decides it.
195
- */
196
- function* askForApproval(
197
- request: ApprovalRequest,
198
- { context }: ToolContext<AgentlibContext>,
199
- ): Operation<boolean> {
200
- const { call, question } = request;
201
- const input: Record<string, unknown> = { tool: call.name, input: call.input };
202
- if (question !== undefined) input.question = question;
203
- // A call may ask more than once: agentlib names each ask (`<agent>:approval:<call>:<n>`).
204
- const value = yield* waitForSignal(context.ctx, request.signalName, 'approval', input);
205
- return approves(value);
206
- }
207
-
208
- /**
209
- * Remembers the steered messages that the run took, so that their own
210
- * `steered` turns do nothing, and tells the companion.
211
- */
212
- function* recordTaken(ctx: restate.ObjectContext, event: ProgressEvent): Operation<void> {
213
- const ids = takenIds(event);
214
- if (ids.length === 0) return;
215
- const taken = (yield* read<string[]>(ctx, TAKEN)) ?? [];
216
- ctx.set(TAKEN, [...taken, ...ids]);
217
- companionSendAt(ctx).taken(ids);
218
- }
219
-
220
- /** The bounds of the agent's `history`, without its model. */
221
- function policyOf(history: Options['history']): CompactionPolicy {
222
- if (!history) return {};
223
- const { maxMessages, maxChars, retainMessages } = history;
224
- return { maxMessages, maxChars, retainMessages };
225
- }
226
-
227
- /** The answer of a run: its output, or else why it stopped. */
228
- function answerOf<O>(result: RunResult<O>): O | string {
229
- if (result.status === 'completed') return result.output;
230
- if (result.output !== undefined) return result.output;
231
- return `Stopped: ${result.reason}`;
232
- }
233
-
234
- /** The note that says how a turn that failed for good ended. */
235
- function noteOf(error: restate.TerminalError): string {
236
- if (error instanceof restate.CancelledError) return CANCELLED;
237
- if (error.code === REFUSED) return UNANSWERED;
238
- return `Failed: ${error.message}`;
239
- }
240
-
241
- /**
242
- * Runs `step` of a turn that has its answer. Restate delivers a cancellation
243
- * once: if it interrupts the step, the step runs again.
244
- */
245
- async function despiteCancellation(step: () => Promise<unknown>) {
246
- try {
247
- await step();
248
- } catch (error) {
249
- if (!(error instanceof restate.CancelledError)) throw error;
250
- await step();
251
- }
252
- }
@@ -1,93 +0,0 @@
1
- // The agentlib agent's key/value state, and how its handlers reach that state,
2
- // the agent's companion, and the agent itself.
3
- import { internal, type Future, type Operation } from '@restatedev/restate-sdk-gen';
4
- import { sdk as restate } from '@restatedev/sessions/internal';
5
- import { companionFor } from '../companion.ts';
6
-
7
- const { adopt } = internal;
8
-
9
- type Context = restate.ObjectContext | restate.ObjectSharedContext;
10
-
11
- /** The turn being answered: its invocation, its message, and where its messages are. */
12
- export interface LiveTurn {
13
- /** The invocation id of the turn. */
14
- turn: string;
15
- /** The user's message that started it. */
16
- prompt: string;
17
- /** The id of the turn's first message. */
18
- from: number;
19
- /** How many messages the turn has so far. */
20
- n: number;
21
- }
22
-
23
- /** The bookkeeping of the messages that clients read, kept under {@link META}. */
24
- export interface Meta {
25
- /** How many messages the answered turns have: the id the next turn starts at. */
26
- chats: number;
27
- /** The cursor of the latest change. Every message written takes the next one. */
28
- cursor: number;
29
- /** The id of the first message, once the conversation was cleared. */
30
- first?: number;
31
- /** The turn being answered, if any. */
32
- live?: LiveTurn;
33
- }
34
-
35
- export const META = 'meta';
36
-
37
- /** The ids of steered messages that a turn took, so that their own `steered` turn does nothing. */
38
- export const TAKEN = 'taken';
39
-
40
- /** The model's conversation (agentlib's `LazyStateConversation`): chunks `t/<n>`, and `t/meta`. */
41
- export const CONVERSATION = 't';
42
- export const CONVERSATION_META = `${CONVERSATION}/meta`;
43
-
44
- /** The key of the message `id`, as clients read it. */
45
- export const entryKey = (id: number) => `c/${id}`;
46
-
47
- export const emptyMeta = (): Meta => ({ chats: 0, cursor: 0 });
48
-
49
- /** Reads state `key` inside an operation of the generator SDK. */
50
- export function read<T>(ctx: restate.ObjectContext, key: string): Future<T | null> {
51
- // At runtime, `get` returns a RestatePromise, although its type says Promise.
52
- const value = ctx.get<T>(key) as unknown as restate.RestatePromise<T | null>;
53
- return adopt(value);
54
- }
55
-
56
- /** The agent's companion (`<agent>.prebuilt.restate`), at the agent's key. */
57
- export function companionAt(ctx: Context) {
58
- const agent = ctx.request().target.service;
59
- return ctx.objectClient(companionFor(agent), ctx.key);
60
- }
61
-
62
- /** The agent's companion, for one-way sends. */
63
- export function companionSendAt(ctx: restate.ObjectContext) {
64
- const agent = ctx.request().target.service;
65
- return ctx.objectSendClient(companionFor(agent), ctx.key);
66
- }
67
-
68
- /** Calls one of the agent's own handlers, at its own key, with JSON in and out. */
69
- export function callOwn<T>(ctx: Context, handler: string, input?: unknown) {
70
- return ctx.genericCall<unknown, T>({
71
- service: ctx.request().target.service,
72
- method: handler,
73
- key: ctx.key,
74
- parameter: input,
75
- inputSerde: restate.serde.json,
76
- outputSerde: restate.serde.json,
77
- });
78
- }
79
-
80
- /**
81
- * Waits for the signal `name` and returns its value. The wait's id is
82
- * `<invocation id>:<id>`; `pending` lists it with `input`, and `signal`
83
- * resolves it.
84
- */
85
- export function* waitForSignal(
86
- ctx: restate.ObjectContext,
87
- id: string,
88
- name: string,
89
- input?: unknown,
90
- ): Operation<unknown> {
91
- const wait = { id: `${ctx.request().id}:${id}`, name, input };
92
- return yield* adopt(companionAt(ctx).wait(wait));
93
- }
@@ -1,53 +0,0 @@
1
- // Messages steered to an agentlib turn (the `steer` view), handed to
2
- // agentlib's run as its steering.
3
- import type { ProgressEvent, SteeringUpdate } from '@restatedev/agentlib';
4
- import { channel, type Channel, type Future, type Operation } from '@restatedev/restate-sdk-gen';
5
- import type { Published, Steer } from '../companion.ts';
6
-
7
- /**
8
- * The messages steered to a turn. The turn learns of them when it publishes
9
- * a change to its companion, which answers with the messages it holds for
10
- * the turn. They go to the run, all at once, as one steering update, at the
11
- * run's next progress event after it asks for one.
12
- */
13
- export class Steering {
14
- private next?: Channel<string | SteeringUpdate>;
15
- private waiting: Steer[] = [];
16
- private readonly handed = new Set<string>();
17
-
18
- /** agentlib's `controls.steering`: the next steering update, once there is one. */
19
- readonly source = (): Future<string | SteeringUpdate> => {
20
- this.next = channel<string | SteeringUpdate>();
21
- return this.next.receive;
22
- };
23
-
24
- /** Notes the messages that a publish (or the turn's start) says are steered to the turn. */
25
- saw(published: Published | undefined) {
26
- for (const steer of published?.steering ?? []) {
27
- const known = this.handed.has(steer.id) || this.waiting.some((s) => s.id === steer.id);
28
- if (!known) this.waiting.push(steer);
29
- }
30
- }
31
-
32
- /** Hands the waiting messages to the run, if it asked for an update. */
33
- *hand(): Operation<void> {
34
- const next = this.next;
35
- if (!next || this.waiting.length === 0) return;
36
-
37
- const batch = this.waiting.splice(0);
38
- for (const { id } of batch) this.handed.add(id);
39
- this.next = undefined;
40
-
41
- const message = batch.map((steer) => steer.text).join('\n\n');
42
- const ids = batch.map((steer) => steer.id);
43
- yield* next.send({ message, data: { steer: ids } });
44
- }
45
- }
46
-
47
- /** Returns the ids of the steered messages that a `steering` event says the run took. */
48
- export function takenIds(event: ProgressEvent): string[] {
49
- if (event.type !== 'steering') return [];
50
- const ids = (event.data as { steer?: unknown } | undefined)?.steer;
51
- if (!Array.isArray(ids)) return [];
52
- return ids.filter((id): id is string => typeof id === 'string');
53
- }