@restatedev/agents 0.7.0 → 0.9.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,252 @@
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
+ }
@@ -0,0 +1,93 @@
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
+ }
@@ -0,0 +1,53 @@
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
+ }