@restatedev/agents 0.7.0 → 0.8.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 (81) hide show
  1. package/README.md +29 -5
  2. package/dist/agentlib/agent.d.ts +32 -0
  3. package/dist/agentlib/agent.d.ts.map +1 -0
  4. package/dist/agentlib/agent.js +172 -0
  5. package/dist/agentlib/agent.js.map +1 -0
  6. package/dist/agentlib/index.d.ts +5 -0
  7. package/dist/agentlib/index.d.ts.map +1 -0
  8. package/dist/agentlib/index.js +15 -0
  9. package/dist/agentlib/index.js.map +1 -0
  10. package/dist/agentlib/messages.d.ts +39 -0
  11. package/dist/agentlib/messages.d.ts.map +1 -0
  12. package/dist/agentlib/messages.js +177 -0
  13. package/dist/agentlib/messages.js.map +1 -0
  14. package/dist/agentlib/model.d.ts +29 -0
  15. package/dist/agentlib/model.d.ts.map +1 -0
  16. package/dist/agentlib/model.js +131 -0
  17. package/dist/agentlib/model.js.map +1 -0
  18. package/dist/agentlib/options.d.ts +58 -0
  19. package/dist/agentlib/options.d.ts.map +1 -0
  20. package/dist/agentlib/options.js +2 -0
  21. package/dist/agentlib/options.js.map +1 -0
  22. package/dist/agentlib/runtime.d.ts +37 -0
  23. package/dist/agentlib/runtime.d.ts.map +1 -0
  24. package/dist/agentlib/runtime.js +216 -0
  25. package/dist/agentlib/runtime.js.map +1 -0
  26. package/dist/agentlib/state.d.ts +114 -0
  27. package/dist/agentlib/state.d.ts.map +1 -0
  28. package/dist/agentlib/state.js +52 -0
  29. package/dist/agentlib/state.js.map +1 -0
  30. package/dist/agentlib/steering.d.ts +23 -0
  31. package/dist/agentlib/steering.d.ts.map +1 -0
  32. package/dist/agentlib/steering.js +48 -0
  33. package/dist/agentlib/steering.js.map +1 -0
  34. package/dist/agentlib/tools.d.ts +33 -0
  35. package/dist/agentlib/tools.d.ts.map +1 -0
  36. package/dist/agentlib/tools.js +243 -0
  37. package/dist/agentlib/tools.js.map +1 -0
  38. package/dist/agentlib/turn.d.ts +82 -0
  39. package/dist/agentlib/turn.d.ts.map +1 -0
  40. package/dist/agentlib/turn.js +253 -0
  41. package/dist/agentlib/turn.js.map +1 -0
  42. package/dist/common.d.ts +8 -0
  43. package/dist/common.d.ts.map +1 -1
  44. package/dist/common.js +12 -0
  45. package/dist/common.js.map +1 -1
  46. package/dist/companion.d.ts +2 -1
  47. package/dist/companion.d.ts.map +1 -1
  48. package/dist/companion.js.map +1 -1
  49. package/dist/deepseek/index.d.ts +2 -6
  50. package/dist/deepseek/index.d.ts.map +1 -1
  51. package/dist/deepseek/index.js +3 -14
  52. package/dist/deepseek/index.js.map +1 -1
  53. package/dist/index.d.ts +5 -3
  54. package/dist/index.d.ts.map +1 -1
  55. package/dist/index.js +6 -4
  56. package/dist/index.js.map +1 -1
  57. package/dist/opencode/index.d.ts.map +1 -1
  58. package/dist/opencode/index.js +11 -18
  59. package/dist/opencode/index.js.map +1 -1
  60. package/dist/tools.d.ts +53 -2
  61. package/dist/tools.d.ts.map +1 -1
  62. package/dist/tools.js +32 -15
  63. package/dist/tools.js.map +1 -1
  64. package/package.json +28 -4
  65. package/src/agentlib/README.md +229 -0
  66. package/src/agentlib/agent.ts +214 -0
  67. package/src/agentlib/index.ts +16 -0
  68. package/src/agentlib/messages.ts +207 -0
  69. package/src/agentlib/model.ts +150 -0
  70. package/src/agentlib/options.ts +62 -0
  71. package/src/agentlib/runtime.ts +252 -0
  72. package/src/agentlib/state.ts +93 -0
  73. package/src/agentlib/steering.ts +53 -0
  74. package/src/agentlib/tools.ts +353 -0
  75. package/src/agentlib/turn.ts +302 -0
  76. package/src/common.ts +15 -0
  77. package/src/companion.ts +2 -1
  78. package/src/deepseek/index.ts +5 -18
  79. package/src/index.ts +6 -4
  80. package/src/opencode/index.ts +12 -17
  81. package/src/tools.ts +118 -52
@@ -0,0 +1,214 @@
1
+ // The agentlib agent's virtual object: `chat`, which answers with agentlib's
2
+ // run, and the handlers and views that every agent here has.
3
+ import { GuardrailError } from '@restatedev/agentlib';
4
+ import { sdk as restate } from '@restatedev/sessions/internal';
5
+ import { type Messages, type MessagesRequest, messageSerde } from '../common.ts';
6
+ import {
7
+ type Notifications,
8
+ type Resolved,
9
+ type Signal,
10
+ type Steer,
11
+ type Steered,
12
+ type Waiting,
13
+ type Watch,
14
+ withCompanion,
15
+ } from '../companion.ts';
16
+ import type { Status, Stopped, Synced, SyncRequest } from '../object.ts';
17
+ import { readMessages } from './messages.ts';
18
+ import type { Definition, Options } from './options.ts';
19
+ import { Runtime } from './runtime.ts';
20
+ import {
21
+ callOwn,
22
+ companionAt,
23
+ CONVERSATION_META,
24
+ emptyMeta,
25
+ META,
26
+ type Meta,
27
+ TAKEN,
28
+ } from './state.ts';
29
+
30
+ type Exclusive = restate.ObjectContext;
31
+ type Shared = restate.ObjectSharedContext;
32
+
33
+ /**
34
+ * The options of every agentlib agent's object. An invocation starts with
35
+ * the small keys only, not the whole conversation (each message is a key of
36
+ * its own). It retries as every agent does: soon after a failure, then twice
37
+ * as long each time, up to 10 seconds apart, for weeks.
38
+ */
39
+ const OPTIONS = {
40
+ state: { preload: [META, TAKEN, CONVERSATION_META] },
41
+ retryPolicy: {
42
+ initialInterval: 50,
43
+ exponentiationFactor: 2,
44
+ maxInterval: 10_000,
45
+ maxAttempts: 100_000,
46
+ },
47
+ } satisfies restate.ObjectOptions;
48
+
49
+ /** A handler that takes a message as plain text or as a JSON string. */
50
+ const TEXT_INPUT = { input: messageSerde, accept: '*/*' };
51
+
52
+ /**
53
+ * An agent of agentlib: a virtual object `name` of the classic Restate SDK,
54
+ * with one conversation per key, in its state. `chat` answers a message with
55
+ * agentlib's run of the agent, journaled: after a crash, Restate replays it,
56
+ * so a model call or a tool call that finished is not made again. It has the
57
+ * views of every agent, and its companion, which `serve` serves beside it.
58
+ *
59
+ * A tool call that needs approval waits for the signal `approval`: `pending`
60
+ * lists it, and `signal` approves it (`true`, `"approved"`, `{ "approved":
61
+ * true }`) or denies it (anything else).
62
+ */
63
+ export function agent<P extends string, O = string>(definition: Options<O> & Definition<P>) {
64
+ const { name, description, background = false, options, metadata, ...agentOptions } = definition;
65
+ checkOneSdk(name);
66
+ const runtime = new Runtime<O>(name, background, agentOptions);
67
+
68
+ const object = restate.object({
69
+ name,
70
+ description,
71
+ metadata,
72
+ handlers: {
73
+ chat: restate.handlers.object.exclusive(TEXT_INPUT, (ctx: Exclusive, text: string) =>
74
+ runtime.answer(ctx, text),
75
+ ),
76
+ steered: restate.handlers.object.exclusive(
77
+ { ingressPrivate: true },
78
+ (ctx: Exclusive, message: Steer) => answerSteered(runtime, ctx, message),
79
+ ),
80
+ erase: restate.handlers.object.exclusive({ ingressPrivate: true }, erase),
81
+ messages: restate.handlers.object.shared(messages),
82
+ status: restate.handlers.object.shared(status),
83
+ pending: restate.handlers.object.shared(pending),
84
+ signal: restate.handlers.object.shared(signal),
85
+ stop: restate.handlers.object.shared(stop),
86
+ clear: restate.handlers.object.shared(clear),
87
+ steer: restate.handlers.object.shared(TEXT_INPUT, steer),
88
+ notifications: restate.handlers.object.shared(notifications),
89
+ watch: restate.handlers.object.shared(watch),
90
+ sync: restate.handlers.object.shared(sync),
91
+ },
92
+ options: { ...OPTIONS, ...options },
93
+ });
94
+ return withCompanion(object);
95
+ }
96
+
97
+ /**
98
+ * Checks that agentlib runs on the same copy of the Restate SDK as
99
+ * @restatedev/sessions. With two copies, agentlib's terminal errors are not
100
+ * the SDK's `TerminalError`, so a failed turn would look retryable.
101
+ */
102
+ function checkOneSdk(name: string) {
103
+ if (Object.getPrototypeOf(GuardrailError) === restate.TerminalError) return;
104
+ throw new Error(
105
+ `${name}: @restatedev/agentlib runs on another copy of @restatedev/restate-sdk ` +
106
+ 'than @restatedev/sessions. Install @restatedev/restate-sdk@1.18.2 ' +
107
+ '(the version @restatedev/sessions pins) beside them.',
108
+ );
109
+ }
110
+
111
+ // The private handlers.
112
+
113
+ /**
114
+ * A message steered to a turn (`steer`), which the companion sent here as it
115
+ * came, so that it keeps its place in the key's queue: answered as a turn of
116
+ * its own, unless the turn it was steered to took it.
117
+ */
118
+ async function answerSteered<O>(runtime: Runtime<O>, ctx: Exclusive, { id, text }: Steer) {
119
+ const taken = (await ctx.get<string[]>(TAKEN)) ?? [];
120
+ if (!taken.includes(id)) {
121
+ await runtime.answer(ctx, text);
122
+ return;
123
+ }
124
+ const left = taken.filter((other) => other !== id);
125
+ if (left.length > 0) ctx.set(TAKEN, left);
126
+ else ctx.clear(TAKEN);
127
+ }
128
+
129
+ /**
130
+ * `clear`'s work, once the messages before it are answered: forgets the
131
+ * conversation. Its ids go on from where they got to.
132
+ */
133
+ async function erase(ctx: Exclusive) {
134
+ const meta = (await ctx.get<Meta>(META)) ?? emptyMeta();
135
+ const next = meta.chats + (meta.live?.n ?? 0);
136
+ ctx.clearAll();
137
+ const cleared: Meta = { chats: next, cursor: meta.cursor + 1, first: next };
138
+ ctx.set(META, cleared);
139
+ await companionAt(ctx).reset();
140
+ }
141
+
142
+ // The views: they run beside the turn being answered.
143
+
144
+ /** The conversation, a page at a time, or what is new or changed since a cursor. */
145
+ async function messages(ctx: Shared, request?: MessagesRequest | null): Promise<Messages> {
146
+ return readMessages(ctx, request ?? {});
147
+ }
148
+
149
+ /** What the agent is doing: the message it answers, its waits, and the messages steered to it. */
150
+ async function status(ctx: Shared): Promise<Status> {
151
+ return companionAt(ctx).status();
152
+ }
153
+
154
+ /** The waits of the agent's tools. */
155
+ async function pending(ctx: Shared): Promise<Waiting[]> {
156
+ return companionAt(ctx).pending();
157
+ }
158
+
159
+ /** Resolves the wait of an id, or else the oldest wait for a name. */
160
+ async function signal(ctx: Shared, wanted: Signal): Promise<Resolved> {
161
+ return companionAt(ctx).resolve(wanted);
162
+ }
163
+
164
+ /** Cancels the invocation of the message being answered, and says which one, if any. */
165
+ async function stop(ctx: Shared): Promise<Stopped> {
166
+ const turn = (await companionAt(ctx).status()).answering;
167
+ if (!turn) return { stopped: null };
168
+ ctx.cancel(restate.InvocationIdParser.fromString(turn.invocationId));
169
+ return { stopped: turn.invocationId };
170
+ }
171
+
172
+ /** Stops the message being answered, then forgets the conversation. */
173
+ async function clear(ctx: Shared): Promise<Stopped> {
174
+ const stopped = await stop(ctx);
175
+ await callOwn(ctx, 'erase');
176
+ return stopped;
177
+ }
178
+
179
+ /**
180
+ * Sends a message to the turn being answered, which takes it at its next
181
+ * step. Otherwise it is answered as a turn of its own.
182
+ */
183
+ async function steer(ctx: Shared, text: string): Promise<Steered> {
184
+ return companionAt(ctx).steer({ id: ctx.request().id, text });
185
+ }
186
+
187
+ /** The conversation's revision. */
188
+ async function notifications(ctx: Shared): Promise<Notifications> {
189
+ return companionAt(ctx).notifications();
190
+ }
191
+
192
+ /** The revision, once there is one newer than `revision`, or at the timeout. */
193
+ async function watch(ctx: Shared, request: Watch): Promise<Notifications> {
194
+ return companionAt(ctx).watch(request);
195
+ }
196
+
197
+ /**
198
+ * The conversation since a cursor, the status and the revision. With
199
+ * `revision`, it waits until there is a newer one.
200
+ */
201
+ async function sync(ctx: Shared, request?: SyncRequest | null): Promise<Synced> {
202
+ const { cursor = 0, revision, timeoutSeconds = 50, limit = 100, view } = request ?? {};
203
+ if (revision !== undefined) await companionAt(ctx).watch({ revision, timeoutSeconds });
204
+
205
+ // The revision first: a change after it shows in the next sync.
206
+ const now = await companionAt(ctx).notifications();
207
+ const current = await companionAt(ctx).status();
208
+ // A call of its own: it reads the state as it is now, while this view
209
+ // read its state as it started.
210
+ const page: MessagesRequest = { cursor, limit };
211
+ if (view) page.view = view;
212
+ const changed = await callOwn<Messages>(ctx, 'messages', page);
213
+ return { revision: now.revision, status: current, ...changed };
214
+ }
@@ -0,0 +1,16 @@
1
+ // @restatedev/agents/agentlib: an agent of Restate's agentlib
2
+ // (@restatedev/agentlib) in a virtual object of the classic Restate SDK,
3
+ // journaled and replayed, with the handlers and views of every agent here.
4
+ //
5
+ // const assistant = agentlib.agent({ name: 'assistant', tools: [weather] });
6
+ // await serve(assistant);
7
+ //
8
+ // The modules: agent.ts (the object, its handlers and views), runtime.ts (a
9
+ // turn, from start to end), turn.ts (a turn's messages and the model's
10
+ // conversation), steering.ts, messages.ts (the messages clients read),
11
+ // model.ts, tools.ts (the tools of @restatedev/agents, made agentlib's), and
12
+ // state.ts (the object's state).
13
+ export { agent } from './agent.ts';
14
+ export { DEFAULT_MODEL } from './model.ts';
15
+ export type { Definition, Options } from './options.ts';
16
+ export type { AgentlibContext, AgentlibTool, Approval, Tools } from './tools.ts';
@@ -0,0 +1,207 @@
1
+ // The agentlib agent's messages as clients read them: rendered from
2
+ // agentlib's messages, kept one per key (`c/<id>`), and paged by the
3
+ // `messages` view.
4
+ import type { Message } from '@restatedev/agentlib';
5
+ import { sdk as restate } from '@restatedev/sessions/internal';
6
+ import type { ChatMessage, Messages, MessagesRequest, Part } from '../common.ts';
7
+ import { emptyMeta, entryKey, META, type Meta } from './state.ts';
8
+
9
+ type ToolPart = Extract<Part, { type: 'tool' }>;
10
+ type ToolResult = Extract<Message, { role: 'tool' }>['result'];
11
+
12
+ /** A message as clients read it, without its id (that is its key), as the agent stores it. */
13
+ export interface Entry {
14
+ role: ChatMessage['role'];
15
+ parts: Part[];
16
+ /** The cursor of the message's latest change. */
17
+ at: number;
18
+ /** It is its turn's message from the user (`view: 'summary'` shows these). */
19
+ prompt?: true;
20
+ /** It is its turn's answer (`view: 'summary'` shows these). */
21
+ answer?: true;
22
+ }
23
+
24
+ /** An entry before it is stored, without its cursor. */
25
+ export type Rendered = Omit<Entry, 'at'>;
26
+
27
+ /** Returns what a tool's result says, as a tool part's output. */
28
+ export function outputOf(result: ToolResult): Pick<ToolPart, 'output' | 'error'> {
29
+ switch (result.status) {
30
+ case 'success': {
31
+ const { output } = result;
32
+ return { output: typeof output === 'string' ? output : JSON.stringify(output) };
33
+ }
34
+ case 'error':
35
+ return { output: `Error: ${result.message}`, error: true };
36
+ case 'denied':
37
+ return { output: `Denied: ${result.message}`, error: true };
38
+ case 'cancelled':
39
+ return { output: `Cancelled: ${result.message}`, error: true };
40
+ case 'pending':
41
+ default:
42
+ return {};
43
+ }
44
+ }
45
+
46
+ /** A message steered to a turn, as agentlib notes it in the conversation. */
47
+ export function steeringNote(message: string): string {
48
+ return JSON.stringify({ source: 'agent-runtime', type: 'steering', message });
49
+ }
50
+
51
+ /** Returns a user message's text: for agentlib's steering note, the steered message. */
52
+ export function userText(content: string): string {
53
+ if (!content.startsWith('{')) return content;
54
+ try {
55
+ const note = JSON.parse(content) as { source?: unknown; type?: unknown; message?: unknown };
56
+ const steering = note.source === 'agent-runtime' && note.type === 'steering';
57
+ if (steering && typeof note.message === 'string') return note.message;
58
+ } catch {
59
+ // Not JSON: the user's own text.
60
+ }
61
+ return content;
62
+ }
63
+
64
+ /**
65
+ * Renders a turn's messages of agentlib as clients read them: each reply
66
+ * with its tool calls, each call with its result as its output. The first
67
+ * message is the turn's prompt, and the last reply its answer.
68
+ */
69
+ export function render(messages: readonly Message[]): Rendered[] {
70
+ const rendered: Rendered[] = [];
71
+ const callParts = new Map<string, ToolPart>();
72
+
73
+ for (const message of messages) {
74
+ switch (message.role) {
75
+ case 'user':
76
+ rendered.push({ role: 'user', parts: [{ type: 'text', text: userText(message.content) }] });
77
+ break;
78
+ case 'assistant': {
79
+ const parts: Part[] = [];
80
+ if (message.content) parts.push({ type: 'text', text: message.content });
81
+ for (const call of message.calls ?? []) {
82
+ const part: ToolPart = { type: 'tool', id: call.id, name: call.name, input: call.input };
83
+ callParts.set(call.id, part);
84
+ parts.push(part);
85
+ }
86
+ if (parts.length === 0) parts.push({ type: 'text', text: '' });
87
+ rendered.push({ role: 'assistant', parts });
88
+ break;
89
+ }
90
+ case 'tool': {
91
+ const part = callParts.get(message.callId);
92
+ if (part) Object.assign(part, outputOf(message.result));
93
+ break;
94
+ }
95
+ }
96
+ }
97
+
98
+ const first = rendered[0];
99
+ if (first?.role === 'user') first.prompt = true;
100
+ const last = rendered.at(-1);
101
+ if (last?.role === 'assistant') last.answer = true;
102
+ return rendered;
103
+ }
104
+
105
+ /** How many messages one read of the `messages` view fetches at once. */
106
+ const BATCH = 25;
107
+
108
+ type View = restate.ObjectSharedContext;
109
+
110
+ /**
111
+ * Reads the entry `id`. At runtime, `get` returns a RestatePromise, although
112
+ * its type says Promise.
113
+ */
114
+ function readEntry(ctx: View, id: number) {
115
+ return ctx.get<Entry>(entryKey(id)) as unknown as restate.RestatePromise<Entry | null>;
116
+ }
117
+
118
+ /** Reads the entries of `ids` at once. A missing entry is `null`. */
119
+ function readEntries(ctx: View, ids: number[]) {
120
+ return restate.RestatePromise.all(ids.map((id) => readEntry(ctx, id)));
121
+ }
122
+
123
+ /** Yields the ids from `from` down to `to` (included), newest first, a batch at a time. */
124
+ function* batches(from: number, to: number): Generator<number[]> {
125
+ for (let id = from; id >= to; id -= BATCH) {
126
+ const size = Math.min(BATCH, id - to + 1);
127
+ yield Array.from({ length: size }, (_, i) => id - i);
128
+ }
129
+ }
130
+
131
+ const chatMessage = (id: number, entry: Entry): ChatMessage => ({
132
+ id,
133
+ role: entry.role,
134
+ parts: entry.parts,
135
+ });
136
+
137
+ /** Whether `entry` belongs in the view that `request` asks for. */
138
+ function inView(request: MessagesRequest, entry: Entry): boolean {
139
+ if (request.view !== 'summary') return true;
140
+ return entry.prompt === true || entry.answer === true;
141
+ }
142
+
143
+ /** The `messages` view: a page of the conversation, or what changed since a cursor. */
144
+ export async function readMessages(ctx: View, request: MessagesRequest = {}): Promise<Messages> {
145
+ const meta = (await ctx.get<Meta>(META)) ?? emptyMeta();
146
+ const page =
147
+ request.cursor === undefined
148
+ ? await pageBefore(ctx, meta, request)
149
+ : await changedSince(ctx, meta, request);
150
+ if (meta.first !== undefined) page.first = meta.first;
151
+ return page;
152
+ }
153
+
154
+ /** The id after the conversation's last message (the turn being answered included). */
155
+ const endOf = (meta: Meta) => meta.chats + (meta.live?.n ?? 0);
156
+
157
+ /** The latest messages before `request.before` (by default, the end), at most `request.limit`. */
158
+ async function pageBefore(ctx: View, meta: Meta, request: MessagesRequest): Promise<Messages> {
159
+ const first = meta.first ?? 0;
160
+ const limit = request.limit ?? 50;
161
+ const messages: ChatMessage[] = [];
162
+ // The oldest id read so far: there are more if older ids are left.
163
+ let oldest = Math.min(request.before ?? endOf(meta), endOf(meta));
164
+
165
+ reading: for (const ids of batches(oldest - 1, first)) {
166
+ const entries = await readEntries(ctx, ids);
167
+ for (const [i, id] of ids.entries()) {
168
+ if (messages.length >= limit) break reading;
169
+ oldest = id;
170
+ const entry = entries[i];
171
+ if (entry && inView(request, entry)) messages.push(chatMessage(id, entry));
172
+ }
173
+ }
174
+
175
+ return { messages: messages.toReversed(), more: oldest > first, cursor: meta.cursor };
176
+ }
177
+
178
+ /**
179
+ * The messages new or changed since `request.cursor`, in the order they
180
+ * changed, at most `request.limit`. An ended turn's messages are rewritten
181
+ * in order as it ends, so the scan stops at the first message, older than
182
+ * the turn being answered, that did not change.
183
+ */
184
+ async function changedSince(ctx: View, meta: Meta, request: MessagesRequest): Promise<Messages> {
185
+ const cursor = request.cursor ?? 0;
186
+ const limit = request.limit ?? 50;
187
+ const liveFrom = meta.live?.from ?? endOf(meta);
188
+ const changed: [number, Entry][] = [];
189
+
190
+ scanning: for (const ids of batches(endOf(meta) - 1, meta.first ?? 0)) {
191
+ const entries = await readEntries(ctx, ids);
192
+ for (const [i, id] of ids.entries()) {
193
+ const entry = entries[i];
194
+ if (!entry) continue;
195
+ if (entry.at > cursor) changed.push([id, entry]);
196
+ else if (id < liveFrom) break scanning;
197
+ }
198
+ }
199
+
200
+ const ordered = changed
201
+ .toSorted(([, a], [, b]) => a.at - b.at)
202
+ .filter(([, entry]) => inView(request, entry));
203
+ const page = ordered.slice(0, limit);
204
+ const more = ordered.length > limit;
205
+ const next = more ? page.at(-1)![1].at : meta.cursor;
206
+ return { messages: page.map(([id, entry]) => chatMessage(id, entry)), more, cursor: next };
207
+ }
@@ -0,0 +1,150 @@
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 type { CompactionPolicy, Model, ModelRequest } from '@restatedev/agentlib';
4
+ import type { aiModel } from '@restatedev/agentlib/provider';
5
+ import { sdk as restate } from '@restatedev/sessions/internal';
6
+ import { CHECK_MODEL, ModelError, REFUSED } from '../common.ts';
7
+
8
+ /** The model of an agent that names none, without MODEL either: OpenAI's (OPENAI_API_KEY). */
9
+ export const DEFAULT_MODEL = 'openai/gpt-6-sol';
10
+
11
+ type LanguageModel = Parameters<typeof aiModel>[0]['model'];
12
+
13
+ /** The AI SDK's provider packages, by provider. OpenAI's uses its Responses API. */
14
+ const PROVIDERS: Record<string, () => Promise<(modelId: string) => LanguageModel>> = {
15
+ openai: async () => (await import('@ai-sdk/openai')).openai,
16
+ anthropic: async () => (await import('@ai-sdk/anthropic')).anthropic,
17
+ };
18
+
19
+ /**
20
+ * Returns what loads agent `agent`'s model on its first turn: `model` itself,
21
+ * or the model it names (`provider/model-id`, else MODEL, else
22
+ * {@link DEFAULT_MODEL}) on the AI SDK. A name it cannot take throws at once.
23
+ */
24
+ export function modelLoader(
25
+ agent: string,
26
+ model: string | Model | undefined,
27
+ ): () => Promise<Model> {
28
+ if (typeof model === 'function') return async () => model;
29
+
30
+ const id = model ?? process.env.MODEL ?? DEFAULT_MODEL;
31
+ const at = id.indexOf('/');
32
+ if (at <= 0 || at === id.length - 1) {
33
+ throw new Error(`${agent}: the model ${id} is not provider/model-id`);
34
+ }
35
+ const provider = id.slice(0, at);
36
+ const modelId = id.slice(at + 1);
37
+ const loadProvider = PROVIDERS[provider];
38
+ if (!loadProvider) {
39
+ throw new Error(
40
+ `${agent}: an agentlib agent takes openai/… and anthropic/… models by name, not ${id}. ` +
41
+ 'Give any other as a model of agentlib (aiModel of @restatedev/agentlib/provider).',
42
+ );
43
+ }
44
+
45
+ return async () => {
46
+ const { aiModel } = await import('@restatedev/agentlib/provider');
47
+ const languageModel = await loadLanguageModel(id, loadProvider, modelId);
48
+ // `retry: {}` sets no retry limit of the model's own: an outage fails the
49
+ // attempt, and Restate retries it, as for every agent.
50
+ const loaded = aiModel({ model: languageModel, retry: {} });
51
+ return provider === 'anthropic' ? withoutSchemaBounds(loaded) : loaded;
52
+ };
53
+ }
54
+
55
+ /** Creates the AI SDK model `modelId`, with a clear error if its provider package is missing. */
56
+ async function loadLanguageModel(
57
+ id: string,
58
+ loadProvider: () => Promise<(modelId: string) => LanguageModel>,
59
+ modelId: string,
60
+ ): Promise<LanguageModel> {
61
+ let create: (modelId: string) => LanguageModel;
62
+ try {
63
+ create = await loadProvider();
64
+ } catch (error) {
65
+ const provider = id.slice(0, id.indexOf('/'));
66
+ const advice = `install it beside @restatedev/agentlib (${String(error)})`;
67
+ throw new ModelError(`${id} needs @ai-sdk/${provider}: ${advice}`);
68
+ }
69
+ return create(modelId);
70
+ }
71
+
72
+ /**
73
+ * Whether `error`, thrown by a model, is its provider's refusal that a retry
74
+ * does not change: a request answered with a 4xx (a wrong API key, an unknown
75
+ * model, a rejected request), or a missing API key. Only a plain
76
+ * `TerminalError` qualifies: agentlib's own errors (an overflow, a protocol
77
+ * error) and cancellations are subclasses.
78
+ */
79
+ export function refused(error: unknown): error is restate.TerminalError {
80
+ if (!(error instanceof restate.TerminalError)) return false;
81
+ if (error.constructor !== restate.TerminalError) return false;
82
+ const clientError = error.code >= 400 && error.code < 500;
83
+ return clientError || /API key/i.test(error.message);
84
+ }
85
+
86
+ /** Wraps `model` so that its provider's refusals end the turn with a 424, as for every agent. */
87
+ export function refusing(model: Model): Model {
88
+ return function* (request: ModelRequest) {
89
+ try {
90
+ return yield* model(request);
91
+ } catch (error) {
92
+ if (!refused(error)) throw error;
93
+ const message = `the model's provider refused the request: ${CHECK_MODEL}. ${error.message}`;
94
+ throw new restate.TerminalError(message, { errorCode: REFUSED });
95
+ }
96
+ };
97
+ }
98
+
99
+ const NUMBER_BOUNDS = new Set([
100
+ 'minimum',
101
+ 'maximum',
102
+ 'exclusiveMinimum',
103
+ 'exclusiveMaximum',
104
+ 'multipleOf',
105
+ ]);
106
+
107
+ /** Returns `schema` (a JSON schema) without the bounds of its numbers, at any depth. */
108
+ export function withoutBounds(schema: unknown): unknown {
109
+ if (Array.isArray(schema)) return schema.map(withoutBounds);
110
+ if (typeof schema !== 'object' || schema === null) return schema;
111
+
112
+ const type = (schema as { type?: unknown }).type;
113
+ const types = Array.isArray(type) ? type : [type];
114
+ const numeric = types.includes('integer') || types.includes('number');
115
+
116
+ const kept = Object.entries(schema).filter(([key]) => !(numeric && NUMBER_BOUNDS.has(key)));
117
+ return Object.fromEntries(kept.map(([key, value]) => [key, withoutBounds(value)]));
118
+ }
119
+
120
+ /**
121
+ * Wraps an Anthropic `model` so that it gets its tools' schemas without
122
+ * numeric bounds. agentlib 0.1.0 asks for strict tools where a schema allows
123
+ * it, and Anthropic refuses strict tools with bounded numbers (such as
124
+ * agentlib's own `read_tool_result`). The tools still check their input.
125
+ */
126
+ function withoutSchemaBounds(model: Model): Model {
127
+ return (request) => {
128
+ const tools = request.tools.map((tool) => {
129
+ const inputSchema = withoutBounds(tool.inputSchema) as Record<string, unknown>;
130
+ return { ...tool, inputSchema };
131
+ });
132
+ return model({ ...request, tools });
133
+ };
134
+ }
135
+
136
+ /**
137
+ * Checks that agent `agent`'s `history` bounds are positive integers. agentlib
138
+ * checks them only when a turn compacts, with an error that a retry would meet
139
+ * again and again.
140
+ */
141
+ export function checkHistory(agent: string, history: CompactionPolicy) {
142
+ for (const bound of ['maxMessages', 'maxChars', 'retainMessages'] as const) {
143
+ const value = history[bound];
144
+ if (value === undefined) continue;
145
+ if (!Number.isSafeInteger(value) || value <= 0) {
146
+ const given = JSON.stringify(value);
147
+ throw new Error(`${agent}: history.${bound} must be a positive integer, not ${given}`);
148
+ }
149
+ }
150
+ }
@@ -0,0 +1,62 @@
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
+ }